[Tutor] Name of a module within itself
D-Man
dsh8290@rit.edu
Sat, 21 Jul 2001 14:03:01 -0400
On Sat, Jul 21, 2001 at 04:02:08PM +0530, lonetwin@yahoo.com wrote:
| Hi there,
| One quick question, suppose I create a file (say 'foo.py'), that has classes
| MyFoo, HisFoo, HerFoo, and a function main(). Now, from main I need to
| refer to the name of the module (foo), such that, I could do something like:
|
| def main():
| ....
| ....
| getattr([refer to this module], 'HisFoo')
| ....
| ....
|
| how do I do that ?
Why do you want to use the getattr function? You could simply say
def main() :
...
HisFoo
...
since main and HisFoo are in the same module. That will be clearer
and works just as well. I don't think there is any way around
accessing a module-level variable like that. Inside a module there is
the __name__ attribute that is a string containing the name of the
module. You could use sys.modules or __import__ to get the module
object based on the name, but you have to get the name by referencing
a module object and you might as well just get that class directly.
HTH,
-D