[Tutor] When is and isn't "__file__" set?
Steven D'Aprano
steve at pearwood.info
Fri Jan 12 19:27:47 EST 2018
On Fri, Jan 12, 2018 at 05:22:05PM +0000, Albert-Jan Roskam wrote:
>
> On Jan 11, 2018 03:47, Steven D'Aprano <steve at pearwood.info> wrote:
[...]
> > Modules which are loaded from a .py or .pyc file on disk should always
> > have __file__ set. If they don't, that's a bug in the interpreter.
> >
> > Modules which are loaded from a .dll or .so binary file also should have
> > __file__ set.
>
> And .pyd? I would hope so
The full list of file extensions handled by Python is version and
platform dependent. There are also .pyo files, on Windows there is at
least one other, .pyw, and there may be more on other platforms.
I don't know the full list.
> > Modules that you create on the fly like this:
> >
> > py> from types import ModuleType
> > py> module = ModuleType('module')
> > py> module.__file__
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in <module>
> > AttributeError: module 'module' has no attribute '__file__'
>
> Fascinating. Will this allow you to write a BLOB of the marshalled
> module object to a database? Do you happen to know a use case of this?
Apparently you cannot either marshal or pickle a module:
py> import pickle, marshal
py> from types import ModuleType
py> x = ModuleType('x')
py> pickle.dumps(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_pickle.PicklingError: Can't pickle <class 'module'>: attribute lookup
module on builtins failed
py> marshal.dumps(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unmarshallable object
--
Steve
More information about the Tutor
mailing list