import - To import a module

The import keyword is used to add the code in the specified module (a Python code file) to the code that making the import.  Importing modules makes the objects in those modules accessible to the module doing the import.

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