Search code examples
pythonpython-3.xpythonpath

How can I import a python module whose name is a uid?


For some reason, I had to change a module name from A.py to 0880ceae-8a46-11eb-bcf6-38f9d349be8e.py. 0880ceae-8a46-11eb-bcf6-38f9d349be8e.py is a uid generated by uuid.uuid1().

After my change, I try to import a class B from the py file by the following two ways, both do not work out.

First solution is to import directly

from 0880ceae-8a46-11eb-bcf6-38f9d349be8e import B

It has an error SyntaxError: invalid token

Second solution is to define a variable before import

uid = '0880ceae-8a46-11eb-bcf6-38f9d349be8e'
from uid import Model_API

And it has en error ModuleNotFoundError: No module named 'uid'

Anyone has a good idea? Thanks.


Solution

  • Here is possible solution to your problem tested using python3:

    
    # Modern approach
    import importlib
    module = importlib.import_module(".", "0880ceae-8a46-11eb-bcf6-38f9d349be8e")
    module.hello()
    
    # Deprecated way
    module = __import__("0880ceae-8a46-11eb-bcf6-38f9d349be8e")
    module.hello()
    

    Both of the above methods are tested and works.

    Here are the rules to keep in mind:

    • Check your filename should end with .py extension, .py.py will cause ModuleNotFoundError.
    • Make sure to not include .py extension while using in importlib module.