[Tutor] importing variables

Dave Angel davea at ieee.org
Thu Nov 12 20:08:29 CET 2009

Stefan Lesicnik wrote:
> On Thu, Nov 12, 2009 at 6:26 PM, bob gailer <bgailer at gmail.com> wrote:
>> Stefan Lesicnik wrote:
>>> Hi guys,
>>> Im trying to do something and hit a bit of a wall, potentially im
>>> going about this the wrong way. Essentially the problem is:
>>> features file contains
>>> rt='text'''
>>> import features
>>> a =rt'
>>> print features.rt  #this works
>>> print features.a  #this fails
>>> I need to use features.a as i am iterating through a list and a would
>>> be the different features i want to check if they exist, and then use
>>> the variable.
>>> I hope that makes sense, or if anyone has any suggestion on how
>>> properly to do this!
>> Even though Alan missed your point, I understood it. So your explanation was
>> OK (for me).
>> print getattr(features, a)
> Thanks Bob!
> That works. I hadn't heard about getattr
> Much appreciated
> stefan
1) Bob's suggestion is what I would have said as well, but using a 3rd 
argument to avoid getting exceptions:
    thisfeature = getattr(features, a, None)

But now that I see it, I'd mention other possibilities.

2)  Since the features.py is being generated, why not just make sure it 
has all the required attributes, perhaps using None as a flag to 
indicate that the feature is disabled.

3) Alternatively, let features.py generate an instance of a class you 
define in your (non-generated) code.  That class can have default 
behaviors to handle missing features, as well as interrelated features 
(eg. if feature3 is enabled, then disable feature4, even if the user 
wants it).

    import features
    myfeatures = features.factory()

and now  myfeatures.rt is guaranteed to exist, because the class makes 
sure of it.

General principle, avoid indexing by string if all the strings could be 
known in advance - that's what regular attribute notation is for.  And 
if there's a part that's out of your control (say data from bob.txt), 
isolate knowledge of that from the rest of the code.

Avoiding code generation:
I don't know cheetah or mako, and can't say I really understand your 
environment.   But if it's CGI stuff for example, I'd beware of 
generating code, since you then run the risk of multiple clients 
colliding with each other.  If you can do things entirely in data 
structures, things can be safely made reusable with no risk of two 
separate instances of the interpreter interfering with each other.

More information about the Tutor mailing list