AppDividend
Latest Code Tutorials

Python import file: How to import modules in Python

If you are working on small or large projects, you always need to work with other modules and packages. Some files are you have created, or some of them are the third parties. To use any module in your code, you must make it accessible in your file, and that is why first, you have to import it.

You can’t use anything in Python before it is defined.

Some things are built-in; for example, the basic data types (like float, int, boolean, etc.) can be used whenever needed. But most of the things you have to do will need a little more than that. So you have first to import it, and then you can use its methods and functions.

What is a module in Python

A module is a file containing definitions and statements. To use the Python module, we have to import the module in other files or the files you have to execute.

Python import file

To import a file in Python, use the import statement. The import statement combines two operations; it searches for the named module, then binds the results of that search to a name in the local scope.

For example, if you want to create a random number, you need to import the random package using “import random“; if you’re going to access the file system, you will use the OS package.

Python language can put definitions in one file and use them in the script or an interactive instance of the interpreter. Such a file is called the module; definitions from a module can be imported into other modules or the main module (the collection of variables you have access to in the script executed at the top level and in calculator mode).

The file name is a module name with the suffix .py appended. The module’s name (as a string) is available as the value of the global variable __name__.

For example, create a new file called sum.py and add the following code inside the file.

# sum.py

def add(a, b):
  c = a + b
  return c

The sum.py file has one function called add(), which takes two parameters and returns the sum of the provided arguments.

The sum.py file is a module in the above file, and add() is its method.

Now, we can import the sum module using the “import sum” inside the other file. But, first, let’s import in the app.py file, which is in the same directory as the sum.py file.

# app.py

import sum

So, the import syntax is the following.

Python import syntax

import modulename

In our example, modulename = sum.

Now, we can use the add() function of the sum module.

# app.py

import sum

print(sum.add(3, 4))

Output

7

If you intend to use the add() function more than once in your file, you can assign it to a local name.

# app.py

import sum

summation = sum.add
print(summation(3, 4))

Output

7

In the above code, we have assigned the sum() function to summation the local name and then use it anywhere in the file.

More on Import Modules

Python modules can contain executable statements as well as function definitions. These statements are intended to initialize the module. Modules are executed only for the first time the module name is encountered in the import statement.

Python modules can import other modules. It is good practice but not required to place all the import statements at the beginning of a file or module (or script). Instead, the imported module names are placed in the importing module’s global symbol table, which Python tracks precisely.

Some variants of the import statement import names from the module directly into the importing module’s symbol table.

For instance, see the following code.

# app.py

from sum import add

print(add(3, 4))

Output

7

You will get the same output.

This does not introduce the module name from which the imports are taken in the local symbol table (so the sum is not defined).

There is even the variant to import all names that a module defines.

See the following code.

# app.py

from sum import *

print(add(3, 4))

Output

7

This imports all names except those beginning with an underscore (_).

So, these are the ways to import a file in Python. That’s it for this tutorial.

Related posts

How to import class from another file

Python cannot import name: How to Solve ImportError

Python Unresolved Import: How to Solve Pylint Error

2 Comments
  1. D says

    what to do if the file to import is in a different directory?

  2. Inercina says

    I must remove “-” and “_” from the name of the file to import; from “Coef-Binomiales23.py” to “CoefBinomiales.py” in order that can be imported.

    CoefBinomiales23
    from math import factorial
    def Comb(n, k):
    c = factorial(n)/(factorial(n – k)*factorial(k))

    Llama-Funcion.py
    a = int(input(“Dame valor grande = “))
    b = int(input(“Dame valor chico = “))
    y = CoefBinomiales23.Comb(a, b)
    print(“La combinación combinada es = “, y)

    Only when I remove – and _ from the names the importation can be done, despite they are allowed in varible names.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.