__getattr__ for globals?

Alex Martelli aleax at aleax.it
Fri Apr 18 23:40:52 CEST 2003

Kevin Smith wrote:

> Is there a way to get the same type of effect of the __getattr__ method
> on class instances with global variables?  I want to be able to look up
> the value of global variables from an external source if they don't
> exist in the current set of globals.

Module objects don't offer this functionality -- when you access a
global X in module Y (whether by syntax Y.X from elsewhere, or by
just X from code inside Y), you get a direct access to Y.__dict__['X'],
period.  And you cannot rebind Y.__dict__ , either.

So why don't you use a class instance to hold your "globals"

class Globals:
    "whatever you wish"
glob = Globals

and use glob.X, glob.Y and so on rather than the corresponding
barenames.  This way you get to do whatever you wish AND your
code arguably gets more readable too...


More information about the Python-list mailing list