automatically naming a global variable

Alex Martelli aleaxit at yahoo.com
Tue May 22 17:13:31 EDT 2001


"Chad Everett" <chat at linuxsupreme.homeip.net> wrote in message
news:slrn9gl8fv.5j4.chat at linuxsupreme.homeip.net...
    ...
> I have sets that are described by a list of attributes and
> properties that are implemented using python dictionaries.
> One of a set's attributes is its name.  I need to provide
> the user with a mechanism for referring to a dictionary that
> represents a set, by using the set's name.  The user does
> not want to have to reference the set via something like:
>
> sets['set_name']

So far, so good.


> They need to have a variable that references to the dictionary
> for the set by simply using set_name.

Naah!  What they need is to have an object that groups
all sets, and use set.name rather than set_name for their
references.


> I need to be able do this:
>
> set_name = sets['set_name'], so that:
>
> >>> set_name
>
> and
>
> >>> sets['set_name']
>
> reference exactly the same thing.

class SetOfSets:
    def __init__(self, refdict):
        self.__ref = refdict
    def __getattr__(self, name):
        return self.__ref[name]
set = SetOfSets(sets)

That's it.  Now, sets['name'] and set.name
reference exactly the same thing forevermore.
If you INSIST on the 'set_' prefix for the key
in dictionary sets, just change the last line
of the SetOfSets classbody to:
        return self.__ref['set_'+name]
though I'm not sure what this buys you.

This way you avoid all kinds of problems typical
of the overuse of globals -- such as the user not
religiously using the set_ stropping-prefix and
accidentally hiding builtins such as 'len()' by
naming a set that way...

If you INSIST on creating such horrible problems
for your users, as I said, then

    setattr(sys.modules[__name__],
        'set_name', sets['set_name'])

lets you do that for one name at a time, or even

    sys.modules[__name__].__dict__.update(sets)

for faster, mass-slaughter kind of suicide:-).


(PS, if the 'user code' in question is something you
are handling with eval, or exec, or execfile, etc,
you can pass arbitrary dictionaries to it -- then,
preparing an artificial dictionary of "globals" which
includes your 'dictionary of sets' is a far more
sensible approach than damaging the actual dict
of globals... similarly, you can use new.function or
other techniques to tweak the globals for user
functions that you get as function-objects, etc...).


Alex






More information about the Python-list mailing list