Le Samedi 24 Juin 2006 04:41, Jorge Vargas a écrit :
> On 6/23/06, Jorge Vargas <[EMAIL PROTECTED]> wrote:
> > Hi everyone I have wasted 2 hours trying to figure out how to get a
> > reference to the module object. that is the one returned by
> >
> > __import__ or when you call a module for name like
> >
> > >>> import sys
> > >>> sys
> >
> > <module 'sys' (built-in)>


In [16]: from types import ModuleType

In [17]: print ModuleType.__doc__
module(name[, doc])

Create a module object.
The name must be a string; the optional doc argument can have any type.

In [18]: ModuleType is type(sys)
Out[18]: True

> >
> > the reason I want this is that I want to introspec my module
> >
> > so I need some way to indentify what elements are inside the module, to
> > execute something like:
> >
> > ""for all the classes defined in this module do <something>"
>

Like for any other object, use the __dict__ attribute :

In [19]: sys.__dict__.items()[:3]
Out[19]:
[('setrecursionlimit', <built-in function setrecursionlimit>),
 ('getfilesystemencoding', <built-in function getfilesystemencoding>),
 ('stdout', <open file '<stdout>', mode 'w' at 0xa7ddc068>)]


Also, you''ll need these :

In [59]: from types import ClassType

In [60]: import subprocess

In [61]: subprocess.__dict__['Popen']
Out[61]: <class 'subprocess.Popen'>

In [62]: isinstance(subprocess.__dict__['Popen'], type)
Out[62]: True

In [63]: isinstance(subprocess.__dict__['Popen'], ClassType)
Out[63]: False

In [64]: ClassType # old-style class
Out[64]: <type 'classobj'>



putting all togetther :


In [75]: def find_classes(mod) :
   ....:     for k, v in mod.__dict__.iteritems() :
   ....:         if isinstance(v, type) : print 'new style class : ', k
   ....:         elif isinstance(v, ClassType) : print 'old style class : ', k
   ....:
   ....:

In [76]: find_classes(subprocess)
new style class :  Popen

In [77]: find_classes(sys)

In [78]: find_classes(os)
old style class :  _Environ
new style class :  stat_result
old style class :  error
new style class :  statvfs_result


> I found an ugly hack to the docs  help(type(sys))

This is not ugly, people used to do "type('')" rather than "import types; 
types.StringType", in prior versions of python (2.1).


-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to