Search code examples
pythonimport

How can I import from the standard library, when my project has a module with the same name? (How can I control where Python looks for modules?)


There is a module in my project folder called calendar. Elsewhere in the code, I would like to use the standard library Calendar class. But when I try to import this class, using from calendar import Calendar, this imports from my own module instead, causing errors later.

How can I avoid this? Do I have to rename the module?


Solution

  • In Python 3.5 and up, use the standard library importlib module to import directly from a specified path, bypassing import's lookup mechanism:

    import importlib.util
    import sys
    
    # For illustrative purposes.
    import tokenize
    file_path = tokenize.__file__  # returns "/path/to/tokenize.py"
    module_name = tokenize.__name__  # returns "tokenize"
    
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    

    In actual code, file_path can be set to any path to a .py file to import; module_name should be the name of the module that will be imported (the name that the import system uses to look up the module when further import statements are attempted). Subsequent code will use module as the name of the module; change the variable name module to use a different name.

    To load a package instead of a single file, file_path should be the path to the package's root __init__.py.