Search code examples
pythonclassmodulenameerror

Python | NameError when importing a class into a test script


so I have a Python module (time.py) which defines "class Time". Then I have a test script (test_time.py) which imports the class, but when I try to create an instance of the class, it throws a NameError. But if I change the module's name to time1.py the test script works fine. I just can't figure out why it won't work when the module is named time.py. Thanks in advance.

time.py:

class Time:
    def __init__(self, init_hr = 12, init_min = 0, init_ampm = "AM"):
        self.hr = init_hr
        self.min = init_min
        self.ampm = init_ampm
    def ..... etc.

test_time.py:

from time import *
if __name__ == "__main__":
    t1 = Time()
    t2 = ...... etc.

The error I get when I run test_time.py:

NameError: name 'Time' is not defined


Solution

  • Because time is a module of the standard library too but it contains no Time object. If you try to get the module directory that is imported with:

    import time
    print(time.__file__)
    

    you'll get an error like:

    AttributeError: 'builtin_function_or_method' object has no attribute '__file__'
    

    If you rename time.py to time1.py this mismatch is resolved and the test script use your local module.

    import time1
    print(time1.__file__)
    

    then you get:

    /<path-to-your-directory>/time1.pyc
    

    If you specify what you want to import from each module you can avoid such mismatchs, as it would give you an error immediatedly:

    from time import Time
    

    you get:

    ImportError: cannot import name Time
    

    and also rename your importing-from modules with more "complex" names in order to avoid such mismatches is a good practice.