How Do I Import Other Python Files?

Importing Other Python Files In A File

Python is a high-level interpreter-based language. It has really short syntaxes and high computational capabilities. Due to this Python is often used for data analysis. Python also has the ability to create packages. Packages are simply a directory that has Python files in it and an __init__.py. Python has the capability to import other Python files or packages in a file.

This helps a lot when you want to create big programs which require thousands or lakhs of lines of code to create to completion. You can just import work done before or even by other fellow programmers if it is available. This prevents redundancy, organizes the code, and also saves a lot of manpower and time to hardcode everything.

Python files and modules

A Python file is just a file containing text and uses the .py extension as in, it has Pythonic text in it. A Python file can be interpreted using an interpreter as Python is an interpreter-based language. Else it can be imported into other Python files and the functions in it can be used there. The name of the Python file is saved as the global variable __name__. A module is simply a file containing Python script which can either be interpreted directly or can be imported and used in other Python files.

Python is a pretty flexible language i.e. it doesn’t have any absolute structure. But in general Python files follows the following schema:-

  • Importing dependencies
  • Defining constant or global variables
  • Defining functions and classes
  • Main execution.

How to Create a Python File

To create a Python file, first, you need to download Python. You can download Python from the official Python download page. After you’ve download Python, you need a text editor or you can directly start writing the code in the notepad. Using a text editor is a good idea. After you’ve written some Pythonic text in a text file, save the file with the .py extension.

Related:: Learn how to download Python.

A Python File
A Python File

After that, go to the terminal or PowerShell in Windows and change the current directory to where your file is present using cd or cd ..
After that, run the command python3 <filename>.py in the terminal.

Running A Pthon File
Running A Python File

Boom! you got output. Now you can write any Python code in it and run the same way. Let’s write code for a simple function in it.

Main Function
Main Function

OUTPUT
Hello everyone! Welcome to askPython.

We defined the main function using the def keyword and then ran the main() function after that. When we executed the program we got the same output as before.

Import statement

The import statement is used to import another Python file or package into the file. It is a form of inheritance that is one of the property of Object Oriented Programming language. You can even import a particular function or class from a file. To import a file or package the import keyword is used.

How to import other files in a file?

We will create another file named main.py in the same directory where welcome.py resides. We will import welcome.py in main.py by writing “import welcome” in main.py.

Now if you execute main.py you’ll notice it gives the output which you got when you executed the welcome.py file. Why so? The reason behind it is that when you import a file, the code in it becomes part of this new file. So the interpreter when encounters “import welcome.py” starts executing the welcome.py file.

So how can we prevent this?

Anything we want to execute i.e. everything except functions and classes must be in an if statement which looks like

if __name__=="__main__":
      # your executable code goes here

What this if statement does, is, check if the name of the current file is the same as the name of the file is the same as the file that is been executed. If it’s not, it won’t execute the following code. This prevents the execution of the file which has been imported. So the welcome.py should contain the following code.

def main():
	print("Hello everyone! Welcome to askPython.")
if __name__=="__main__":
	main()

Now it won’t execute the main() code line when imported in another file.

from‘ and ‘as‘ keywords

You could enhance the abilities of the import statement by using the ‘from‘ and ‘as‘ keywords in pair with the import keyword. The purpose of the from keyword is to import only a particular part of a bigger file or a particular module from a bigger package. This saves up the space consumed by the program.

Let’s try to import just the main() function from welcome.py.

from welcome import main
main()
Code And Output For Importing File
Code And Output For Importing File

Now you can call the main() function as if it was part of the file it is imported in.

You can also give an alias to the function by using the ‘as‘ keyword.

 from welcome import main as m

Now you can use the main() function as m(). The alias is really useful when you are just trying to use a small part of a big library (a package containing a bunch of other packages). At these moments, you would have a big path. For example, “import matplotlib.pyplot“. Now you will have to type it each time you use a function of it. In those times, you can just import it as ‘plt‘ and use it by the name plt.

What is PYTHONPATH?

Pythonpath is an environment variable. A local variable has its scope to a particular function, a global variable has its scope to the entire program. An environment variable has its scope up to all the programs in the environment. Pythonpath variables store the addresses of all the directories where the interpreter is supposed to look for imported modules and packages.

Related: Learn more about environment variables.

You can check the pythonpath variable using the sys.path function from the sys module.

import sys
print(sys.path)
Code And Output For Sys Path
Code And Output For Sys Path

You can also append a path in the sys.path by the following syntax.

import sys
sys.path.append(path/to/directory)

What is importlib?

Importlib is a module used for performing dynamic imports. With the import keyword, the interpreter imports the modules before it starts executing the file. With the importlib module, files can be imported dynamically during runtime. Using it, we can even take the names of the file as user input that we want to import.

Handling errors during import

Even though the syntax of Python is quite simple, errors keep on occurring now and then. The most common error that occurs during an import is the File not Found error. It can be due to a number of reasons. Usually, there’s a spelling error in specifying the name of the module or package.

Also, remember to use the correct format of the import statement. It goes like “from <...> import <...> as <...>“.

Best practices while importing files

Make sure you properly organize your files in directories so that you can easily access them when required. Avoid circular imports (circular import is when you import ‘module a’ in ‘module b’ and ‘module b’ in ‘module a’. Avoid importing unnecessary files. Use import all(*) only when required.

Conclusion

Python is a versatile language that makes it easy for us to create complex programs due to these big libraries such as numpy, pandas, sympy, etc. The vast community built over decades has made Python one of the most powerful languages ever due to these big libraries and the amount of flexibility Python provides. Knowing how you can import other files opens the gates for a pool of possibilities. You must keep learning more and try your best to give back to the community what it gave you.

References

Official Python Documentation.

Stack Overflow answer for the same question.