using import inside class

Everything defined inside the namespace of a class has to be accessed from that class. That holds for methods, variables, nested classes and everything else including modules.

If you really want to import a module inside a class you must access it from that class:

class Test:
    import time as zeit
    def timer(self):
        self.zeit.sleep(2)
        # or Test.zeit.sleep(2)

But why would you import the module inside the class anyway? I can't think of a use case for that despite from wanting it to put into that namespace.

You really should move the import to the top of the module. Then you can call zeit.sleep(2) inside the class without prefixing self or Test.

Also you should not use non-english identifiers like zeit. People who only speak english should be able to read your code.


You want time.sleep. You can also use;

from time import sleep

Edit: Importing within class scope issues explained here.


sleep is not a python builtin, and the name as is, does not reference any object. So Python has rightly raised a NameEror.

You intend to:

import time as zeit

zeit.sleep(2)

And move import time as zeit to the top of the module.

The time module aliased as zeit is probably not appearing in your module's global symbol table because it was imported inside a class.