[Python-3000] the types module

tomer filiba tomerfiliba at gmail.com
Thu Feb 1 12:43:03 CET 2007


i've had some difficulty with code that attempts to locate a type
by its __module__ and __name__, something like:
    getattr(sys.modules[t.__module__], t.__name__)

the trouble is, all builtin types claim to belong to the __builtin__ module.

for example:
    >>> types.FunctionType
    <type 'function'>
    >>> types.FunctionType.__name__
    'funcrtion'
    >>> types.FunctionType.__module__
    '__builtin__'

but --
    >>> __builtin__.function
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'module' object has no attribute 'function'

most, but not all, of the types are exposed in __builtin__... this required
me to create an artificial mapping in which "__builtin__.function" is mapped

to types.FunctionType, and then use this mapping instead of sys.modules,
which adds more special cases on my part.

on the other hand, the exceptions module works differently. all builtin
exceptions are defined in the exceptions module, but are exposed
through __builtin__:
    >>> EOFError.__module__
    'exceptions'
    >>> exceptions.EOFError
    <type 'exceptions.EOFError'>
    >>> __builtin__.EOFError
    <type 'exceptions.EOFError'>

so i thought why not do the same with all builtin types? currently the
types module (types.py) exposes some type objects (not all), and uses
witchcraft to obtain them:
    try:
        raise TypeError
    except TypeError:
        tb = sys.exc_info()[2]
        TracebackType = type(tb)
        FrameType = type(tb.tb_frame)

instead, let's make it a builtin module, in which all types will be defined;
the useful types (int, str, ...) would be exposed into __builtin__ (just as
the exceptions module does), while the less useful will be kept unexposed.

this would make FunctionType.__module__ == "types", rather than
"__builtin__",
which would allow me to fetch it by name from sys.modules.


-tomer
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-3000/attachments/20070201/162438b9/attachment.html 


More information about the Python-3000 mailing list