Python import Keyword

Modules (usually code in sub-directories) are a way of organizing your code. The import keyword is used to tell Python "hey, I want to use some code in another this other module."  This is particularly useful when the module has many Python code files. Using the import keyword, you can then access the functions and classes defined in the imported module.

Python
import myModule

Example

Let's say you have a file called "moduleToImport.py" that looks like this:

Python
class ImportedClass():
    def sayHello(self):
        print('hello')

the module name is "moduleToImport" which can be used like this:

Python
import moduleToImport
myImportedClass = moduleToImport.ImportedClass()
myImportedClass.sayHello()

Output

Hello

Notes: The code that is imported is run immediately. Let's change the above example a little bit.

moduleToImport.py:

Python
print('I am imported')
a = 5

class ImportedClass():
    def sayHello(self):
        print('hello')

And we run this:

Python
print("Before import...")
import moduleToImport
print("After import...")
print("My code:")
print(moduleToImport.a)
moduleToImport.ImportedClass().sayHello()

Output

Before import...
I am imported
After import...
My code:
5
hello