The Beauty of Python File-like Objects

Posted on in Programming

As I mentioned the other day, I'm building a RADIUS client in Python for sending disconnect messages to Cisco routers.

One hang-up with the pyrad package is that it requires a dictionary file in order to map RADIUS attribute names to codes and types. In the case of my client, I only need two attributes: User-Name and Calling-Station-Id. I don't want to have to create a dictionary file for just these two entries. Fortunately, the StringIO module allows me to create an object that acts like a file, but works with a string I provide.

In my code, I can now do this:

from pyrad.client import Client
from pyrad.dictionary import Dictionary
from StringIO import StringIO

dict = StringIO("ATTRIBUTE User-Name 1 string\n" + 
                "ATTRIBUTE Calling-Station-Id 31 string")
client = Client(server="nas_hostname", 

Because StringIO provides all the methods that a normal file object does, the Dictionary() class is none the wiser.

Slaptijack's Koding Kraken