getattr for modules not classes

Daniel Nogradi nogradi at gmail.com
Mon May 22 04:10:08 EDT 2006


> > Is there something analogous to __getattr__ for modules?
> >
> > I know how to create a class that has attributes from a list and
> > nothing else by overloading __getattr__ and making sure that the
> > accessed attribute appears in my list. Now I would like to do the same
> > with a module, say x.py, in which I have a list, say mylist, and after
> > importing x from another module I would like to be able to say x.one(
> > ) or x.two( ) if 'one' and 'two' are in mylist and raise an exception
> > if they aren't. Is this possible?
>
> Not really. But, why not create an instance of some custom type in x.py, and
> import that instance into the current namespace? Just as convenient.
>
> x.py
> ----
> mylist = {"one":1,"two":2}
> class test(object):
>     def __getattr__(self,name):
>         return mylist.get(name,None)
> test = test()
> ---
>
> y.py
> ---
> from x import test
> print test.one
> print test.two
> print test.three
> ---

Thanks, that looks pretty good, I'll do that.



More information about the Python-list mailing list