Getting the module name from a method...

François Pinard pinard at iro.umontreal.ca
Tue Jun 6 14:52:57 EDT 2000


"Michael P. Reilly" <arcege at shore.net> writes:

> Olivier Deckmyn <olivier.deckmyn at mail.dotcom.fr> wrote:

> : I would like a method of my own to be able to print the module it is
> : declared in: ex: the text for the module : toto.py is :

> : class MyClass:
> :     def myMethod(self):
> :         print "I am in module", ????????

> : and then
> : MyClass().myMethod()
> : should produce :
> : 'toto'

> Unless the method was added as an instance attribute (self.method = ...),
> the global namespace should be the module where the method was defined,
> in this case "toto".  The less secure means would be globals()['__name__'],

In which way referring to `__name__' would not be secure?

> but you could also go with:

>   import os, sys
>   def mymodule():
>     try:
>       raise RuntimeError
>     except RuntimeError:
>       exc, val, tb = sys.exc_info()
>       code = tb.tb_frame.f_back.f_code
>       del exc, val, tb
>     if code.co_filename:
>       module = os.path.splitext(os.path.basename(code.co_filename))[0]
>     else:
>       module = '<string>'
>     return module

Why raise an exception?  Would not:

   import traceback
   frames = traceback.extract_stack()
   file_name, line_number, function_name, python_text = frames[-1]

give you enough information, while being of a much simpler writing?

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list