class version of func_globals?

S

samwyse

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

Dave Angel

samwyse said:
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.
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
 
S

samwyse

samwyse said:
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.

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

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

Jan Kaliszewski

29-12-2009 samwyse said:
samwyse said:
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.

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

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,966
Members
47,515
Latest member
Harvey7327

Latest Threads

Top