[Tutor] Re: Tutor digest, Vol 1 #970 - 5 msgs

Charlie Clark Charlie Clark <charlie@begeistert.org>
Sun, 22 Jul 2001 12:00:00 +0200


> 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 ?
>
>from the prompt I can do:

>where the file 'foo.py' contains:
>===================================
>#!/usr/bin/python
> 
>class MyFoo:
>	pass
>class HisFoo:
>	x = 'foo'
>class HerFoo:
>	x = 'bar'
I think those classes are not quite correctly constructed but that isn't 
important at the moment.
>====================================
>  ....ehe....Am I being clear enough ?...if not please tell me and I'll send
>  some more code along.
If you don't have it already I can highly recommend "Learning Python" by Mark 
Lutz & David Ascher. On page 141 you'll find all the different but equivalent 
ways of checking attribute names and it's worth spending some time thinking 
about names and namespaces as they are very important in Python partly 
because it's so easy to overwrite them. The next page has an example script 
which extracts object names from other scripts and includes a test on itself.

Let me know if you need the source so I can send it you outside of the list.

What I haven't quite understood is why you need to get the name of the module 
itself: when the module is run it's name is in the global namespace outside 
of it and thus not directly accessible by the module itself.

If you run dir() you'll get a list of all the current namespaces:
>>> namespaces = dir()
>>> namespaces
>>> ['__builtins__', '__doc__', '__name__', 'test']  

You could then try our_module = namespaces[3] but I think this not likely to 
be reliable.

You can access all the names in the modules namespace either by using 
dir(module_name) or module_name.__dict__.keys(). Once you've done that you 
can ignore the built-ins to list your functions or classes.

Does that make any sense?

Charlie

-- 
Charlie Clark
Helmholtzstr. 20
Düsseldorf
D- 40215
Tel: +49-211-938-5360
GSM: +49-178-463-6199
http://www.begeistert.org