Python

 

 

 

 

import

 

'import' is a mechanism that enable you to include another python into the current file that you are working on. If you have any experience with C/C++, you can consider 'import' to be same as #include in C/C++

 

 

Order of Search

 

When you put 'import' in your script, Python tries to search the imported file or modules in various locations in the order as follows.

    i) The current directory.

    ii) PYTHONPATH environment variable directories (if set).

    iii) Standard library directories.

    iv) Third-party packages directories.

    v) sys.path attribute of the sys module, which can be modified at runtime to add new directories.

 

 

 

Different ways of import

 

One of the things that confused me a lot about 'import' was that there are many different ways of importing a module. In most cases I just blindly copied the way of import from a example code that I get from various sources. I thought it would be good to make a summary of the different way of import

 

standard import statement : Importing all names from a module into the global namespace, making them accessible without qualification.

    syntax : import module_name

 

 

from-import statement. : Importing only specific names from a module into the global namespace.

    syntax : from module_name import function_or_variable_name

 

 

as-import statement : Importing a module under an alternate name, making it easier to use in code.

    syntax : import module_name as alias

 

 

Importing specific names from a module : Importing all names from a module into a local namespace, avoiding name conflicts with other modules.

    syntax : from module_name import function_1, function_2, variable

 

 

 

What if the same module name is used by multiple imported files ?

 

If multiple files with the same module name are imported into a single Python program, only the first file imported will be used and any subsequent imports of the same module name will be ignored. This is because once a module has been imported, its contents are stored in Python's memory and any subsequent imports of the same module will simply reference the contents that are already in memory, rather than loading the module again.

 

If you need to use multiple versions of a module with the same name, you can use the as statement to give each version a unique alias, allowing you to access the different versions of the module within your program.

 

For example

    import module1 as m1

    import module2 as m2

 

and then you can use the same function in different modules as follows :

    m1.function_name()

    m2.function_name()