Modules

Modules are files with .py extension containing Python code.  

Using (Importing) Modules

To use a module in an external Python code block, we need to import that specific module into our code structure.   The import statement with “import ” syntax is used to import the module code.   Module name here refers to the Python file name without “.py” extension.   Once the module is imported, use the dot notation, “.”, to access the elements inside the module.   Import an entire module:


from csv_get_module import *

You can rename the module while importing with with ‘import as ’ syntax.

Specific parts can (only) be imported if desired using the syntax ‘from import

Python has built-in __name__ attribute that gives us module name when the file is loaded as a module.   When the file is being run as a standalone script, it returns the __main__ string. Using the code below, you can cause a script file to run only when it is run as a standalone script.


if __name__ == '__main__':

WARNING: Don't give your script files (.py) the same names as built-in modules.

Packages group similar modules in a separate directory.

Related Links

Learn How to Organise Your Python Code with Modules and Packages in 5 Minutes

Day 21: Splitting Code Into Multiple Files