Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

getattr for modules not classes

10 views
Skip to first unread message

Daniel Nogradi

unread,
May 21, 2006, 3:52:25 PM5/21/06
to pytho...@python.org
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?

Heiko Wundram

unread,
May 21, 2006, 4:53:08 PM5/21/06
to pytho...@python.org

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
---

--- Heiko.

Daniel Nogradi

unread,
May 22, 2006, 4:10:08 AM5/22/06
to pytho...@python.org

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

Piet van Oostrum

unread,
May 24, 2006, 9:43:55 AM5/24/06
to
>>>>> Heiko Wundram <me+p...@modelnine.org> (HW) wrote:

>HW> y.py
>HW> ---
>HW> from x import test
>HW> print test.one
>HW> print test.two
>HW> print test.three
>HW> ---

Or even:
import x
x = x.test
print x.one
print x.two
print x.three

--
Piet van Oostrum <pi...@cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: pi...@vanoostrum.org

Heiko Wundram

unread,
May 26, 2006, 6:39:56 AM5/26/06
to pytho...@python.org
Am Mittwoch 24 Mai 2006 15:43 schrieb Piet van Oostrum:
> >>>>> Heiko Wundram <me+p...@modelnine.org> (HW) wrote:
> >
> >HW> y.py
> >HW> ---
> >HW> from x import test
> >HW> print test.one
> >HW> print test.two
> >HW> print test.three
> >HW> ---
>
> Or even:
> import x
> x = x.test
> print x.one
> print x.two
> print x.three

Or even:

---
from x import test as x


print x.one
print x.two
print x.three

---

--- Heiko.

Piet van Oostrum

unread,
May 27, 2006, 7:11:27 AM5/27/06
to
>>>>> Heiko Wundram <me+p...@modelnine.org> (HW) schreef:

>HW> from x import test as x
>HW> print x.one
>HW> print x.two
>HW> print x.three

Or replace test by x in x.py :=)

0 new messages