Python Modules

Python modules are a way to organize and reuse code. They are files containing Python definitions and statements. The module can be imported by other Python programs to make use of its functionality. Modules are a convenient way to share code between different projects and to organize large codebases.

Create python module

To create a Python module, you need to create a new file with a .py extension and write your Python code in it. For example, you can create a file called "addmodule.py" and put the following code in it:

1def add_value(x): 2 return x + x

Import Module

Then, in another Python file, you can import this module and use the add_value by using the import statement:

1import addmodule 2result = add_value.add_value(5) 3print(result) # Output: 10

You can also use an alias for the module name to shorten it

1import addmodule as add 2result = add.add_value(5) 3print(result) # Output: 10

or you can import only the specific function you need

1from addmodule import add_value 2result = add_value(5) 3print(result) # Output: 10

This way, you can share and reuse the functionality defined in the addmodule.py file across multiple Python programs.

Import Variables from Module

To import variables from a module in Python, you can use the from keyword followed by the module name and the specific variable you want to import.

For example, let's say you have a module called storevar.py with the following variables defined in it:

1K = [1, 2, 3] 2D = {'a': 1, 'b': 2}

To import the list K from the module, you can use the following code:

1from storevar import K 2print(K) # Output: [1, 2, 3]

To import the dict D from the module, you can use the following code:

1from storevar import D 2print(D) # Output: {'a': 1, 'b': 2}

You can also import multiple variables from a module at once by separating them with a comma:

1from storevar import K, D 2print(K) # Output: [1, 2, 3] 3print(D) # Output: {'a': 1, 'b': 2}

It's important to remember that this method of importing variables from a module can lead to naming conflicts if the imported variable has the same name as a variable in your current scope.