pythonpython-import

Why won't this Python module import into my code


I have this entry point:

# main.py

from 022 import *

print("Hello from main.py")

I have 022.py also. It is:

print("Hello World")

When I run main.py I get this error:

  File "C:\Users\nicholdw\source\repos\InClass20250121-4010-001\InClass20250121-4010-001\mainPackage\main.py", line 3
    from 022 import *
         ^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

Solution

  • Python interprets 022 as a decimal literal, which is invalid for the name. You just need to rename the file to something that starts with a letter.

    If you can't rename the python script, you can dynamically load the module.

    import importlib.util
    
    module_name = "022"
    module_path = "./022.py"
    
    spec = importlib.util.spec_from_file_location(module_name, module_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    

    This will load the 022.py file as a module stored in the variable module. Also, your Hello World message will print.