Asked By – twig
– There is a module in my project_folder called calendar
– I would like to use the built-in Calendar class from the Python libraries
– When I use from calendar import Calendar it complains because it’s trying to load from my module.
I’ve done a few searches and I can’t seem to find a solution to my problem.
- How to access a standard-library module in Python when there is a local module with the same name?
- How to avoid writing the name of the module all the time when importing a module in python?
Any ideas without having to rename my module?
Now we will see solution for issue: Importing from builtin library when module with same name exists
The accepted solution contains a now-deprecated approach.
The importlib documentation here gives a good example of the more appropriate way to load a module directly from a file path for python >= 3.5:
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)
So, you can load any .py file from a path and set the module name to be whatever you want. So just adjust the
module_name to be whatever custom name you’d like the module to have upon importing.
To load a package instead of a single file,
file_path should be the path to the package’s root