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

class version of func_globals?

269 views
Skip to first unread message

samwyse

unread,
Dec 29, 2009, 4:40:35 AM12/29/09
to
Is there any way to get the global namespace of the module in which a
class was defined? Answers for both Python 2.x and 3.x will be
cheerfully accepted.

Dave Angel

unread,
Dec 29, 2009, 6:18:30 AM12/29/09
to samwyse, pytho...@python.org
I don't know if it's the same in general, but consider the following
sequence in 2.6:


import sys

class MyClass(object):
pass

print "class--", dir(MyClass)
print "module--", dir(MyClass.__module__)
mod = sys.modules[MyClass.__module__]
print mod
print "globals--", dir(mod)

DaveA

samwyse

unread,
Dec 29, 2009, 7:54:52 AM12/29/09
to

Excellent! Exactly what I wanted, but wasn't clever enough to figure
out for myself. Thank you very much.

Jan Kaliszewski

unread,
Dec 30, 2009, 6:24:22 PM12/30/09
to pytho...@python.org
29-12-2009 samwyse <sam...@gmail.com> wrote:

But dir(mod) gives you only names, not objects (though, of course, you
can get them "manually" with getattr(mod, name)). To get from a class
the same you get from function using func_globals (i.e. dictionary with
names as keys and objects as values), use:

mod = sys.modules[MyClass.__module__] # (as above)
vars(mod) # or mod.__dict__, though vars(mod) seems to me more elegant

Cheers,
*j

--
Jan Kaliszewski (zuo) <z...@chopin.edu.pl>

0 new messages