Add some clarification and examples based on Guido's feedback.

This commit is contained in:
Barry Warsaw 2012-05-21 15:56:20 -04:00
parent e7606f50c9
commit bb6f79b4ad
1 changed files with 47 additions and 2 deletions

View File

@ -386,14 +386,59 @@ module. The rules for producing a module repr are now standardized as:
* If the module has an ``__loader__`` and that loader has a ``module_repr()``
method, call it with a single argument, which is the module object. The
value returned is used as the module's repr.
* Exceptions from ``module_repr()`` are ignored, and the following steps
are used instead.
* If an exception occurs in ``module_repr()``, the exception is
caught and discarded, and the calculation of the module's repr
continues as if ``module_repr()`` did not exist.
* If the module has an ``__file__`` attribute, this is used as part of the
module's repr.
* If the module has no ``__file__`` but does have an ``__loader__``, then the
loader's repr is used as part of the module's repr.
* Otherwise, just use the module's ``__name__`` in the repr.
Here is a snippet showing how namespace module reprs are calculated
from its loader::
class NamespaceLoader:
@classmethod
def module_repr(cls, module):
return "<module '{}' (namespace)>".format(module.__name__)
Built-in module reprs would no longer need to be hard-coded, but
instead would come from their loader as well::
class BuiltinImporter:
@classmethod
def module_repr(cls, module):
return "<module '{}' (built-in)>".format(module.__name__)
Here are some example reprs of different types of modules with
different sets of the related attributes::
>>> import email
>>> email
<module 'email' from '/home/barry/projects/python/pep-420/Lib/email/__init__.py'>
>>> m = type(email)('foo')
>>> m
<module 'foo'>
>>> m.__file__ = 'zippy:/de/do/dah'
>>> m
<module 'foo' from 'zippy:/de/do/dah'>
>>> class Loader: pass
...
>>> m.__loader__ = Loader
>>> del m.__file__
>>> m
<module 'foo' (<class '__main__.Loader'>)>
>>> class NewLoader:
... @classmethod
... def module_repr(cls, module):
... return '<mystery module!>'
...
>>> m.__loader__ = NewLoader
>>> m
<mystery module!>
>>>
References
==========