David Callanan
David Callanan

Reputation: 5968

Python why is it importing builtin

parser.py

foo = 27

bar.py

import parser
print(parser.foo)

This does not work because the built-in parser library is being used instead of the parser.py that resides in the same directory.

How do I fix this? I thought your own modules take priority when there are name clashes.

Upvotes: 1

Views: 55

Answers (2)

Jordan Brière
Jordan Brière

Reputation: 1055

This does not work because the built-in parser library is being used instead of the parser.py that resides in the same directory.

Use relative imports if a package, or import from file otherwise. E.g.

import os

# If a package, use relative import
if __package__ is not None:
    from . import parser

# Otherwise, load from file
else:
    from importlib.machinery import SourceFileLoader
    parser = SourceFileLoader(
        # Don't overwrite the sys.modules entry
        '_parser',
        os.path.join(os.path.dirname(__file__), 'parser.py')
    ).load_module()
    # We don't need that anymore, cleanup
    del SourceFileLoader

Upvotes: 1

Arnie97
Arnie97

Reputation: 1069

From https://docs.python.org/3/tutorial/modules.html#the-module-search-path:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path.

Upvotes: 2

Related Questions