Coder Perfect

What is the best way to import other Python files?

Problem

In Python, how can I import additional files?

In main.py, for example, I have:

from extra import * 

Despite the fact that this provides me all of the definitions in extra.py, I may only need one:

def gap():
    print
    print

What should I include in the import statement to retrieve only gap from extra.py?

Asked by Tamer

Solution #1

Don’t just hastily pick the first import strategy that works for you or else you’ll have to rewrite the codebase later on when you find it doesn’t meet your needs.

I’ll start with the simplest example #1 and work my way up to the most professional and robust example #7.

Example 1: Using the Python interpreter to import a Python module:

Example 2: To execute another Python file in place, use execfile or (exec in Python 3) in a script:

Example 3: Take a cue from… bring in… functionality:

Example 4: If riaa.py is in a different file location than where it was imported, import it.

Use os.system in Example 5 (“python yourfile.py”)

import os
os.system("python yourfile.py")

Example 6: Using the python startuphook to import your file:

This example previously worked with both Python 2 and 3, but now only works with Python 2. Because it was misused by low-skill python library programmers, who used it to inadvertently inject their code into the global namespace, before all user-defined applications, python3 got rid of this user startuphook feature set. You’ll have to be more inventive if you want this to work on Python 3. If I show you how to accomplish it, the Python developers will disable that feature set as well, leaving you on your own.

See: https://docs.python.org/2/library/user.html

Put this code in /.pythonrc.py in your home directory.

class secretclass:
    def secretmessage(cls, myarg):
        return myarg + " is if.. up in the sky, the sky"
    secretmessage = classmethod( secretmessage )

    def skycake(cls):
        return "cookie and sky pie people can't go up and "
    skycake = classmethod( skycake )

Put the following code in your main.py file (it can be anywhere):

import user
msg = "The only way skycake tates good" 
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")

If you run it, you should get the following:

$ python main.py
The only way skycake tates good is if.. up in the sky, 
the skycookie and sky pie people can't go up and  have the sky pie! 
SKYCAKE!

Here’s what to do if you get an error: ModuleNotFoundError: If you don’t have a module named ‘user,’ that suggests you’re using Python 3, where startuphooks are disabled by default.

https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py is where this jist comes from. Please provide your up-boats.

Example 7, Most Robust: Use the basic import command to import files in Python:

Please read https://stackoverflow.com/a/20753073/445131 for my post on how to incorporate ALL.py files under a directory.

Answered by Eric Leschinski

Solution #2

Python 3 has importlib, which allows you to import a module programmatically.

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

ModuleName should have the.py extension removed. For relative imports, the function also defines a package argument.

In python 2.x:

pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))

For additional information, type help( import ).

Answered by tabdulradi

Solution #3

To import a specific Python file with a known name at ‘runtime’:

import os
import sys

scriptpath = "../Test/"

# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import MyModule

Answered by James

Solution #4

In the first instance, You wish to import file A.py into file B.py, and they’re both in the same folder:

. 
├── A.py 
└── B.py

This can be done in file B.py:

import A

or

from A import *

or

from A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you’ll be able to use all of file A.py’s functions in file B.py.

The second instance You wish to import file folder/A.py into file B.py, however they’re not in the same folder:

.
├── B.py
└── folder
     └── A.py

This can be done in the B.py file.

import folder.A

or

from folder.A import *

or

from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you’ll be able to use all of file A.py’s functions in file B.py.

Summary

Consult this page for further information about packages and modules.

Answered by Bohao LI

Solution #5

To move a python file from one folder to another, you don’t have many complicated techniques. Simply create a init .py file to declare this folder as a Python package, and then simply type import into your host file.

import variable, class, anything from root.parent.folder.file

Answered by Fatih Karatana

Post is based on https://stackoverflow.com/questions/2349991/how-to-import-other-python-files