How to Import Other Python Files

How do I import other Python files?

importlib was added to Python 3 to programmatically import a module.

import importlib

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

The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.

In python 2.x:

  • Just import file without the .py extension
  • A folder can be marked as a package, by adding an empty __init__.py file
  • You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))

Type help(__import__) for more details.

How to import another python script (.py) into main python file

To include the dictionary, you could do this if your file location is in different directory (with caution of path.append as @Coldspeed mentioned):

import sys
sys.path.append("path/foo/bar/")
from light import *

If it is in same directory as current directory, you could just do:

from light import *

How to import libraries imported in a python file into another python file?

When you import from within the scope of a function, that import is only defined from within that function, and not in the scope that the function is called in.

I'd recommend looking at this question for a good explanation for scope rules in python.

To fix this, you can use python's star import.

imports.py:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

__all__ = [
'pd',
'np',
'sns',
'plt'
]

train.py:

from imports import *

...

The syntax from module import * imports all variables defined in the __all__ list from within that module.

Edit

I strongly discourage the use of this code, because has the opposite effect you intend it to have. This will remove the "clutter" of redundant import statements, at the cost of something much worse: confusing code, and a hidden bug waiting to come to the surface (explained below).

Alas, the solution:

import inspect

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

CODE_CONTEXT = ['from imports import *\n']

__all__ = [
'pd',
'np',
'sns',
'plt'
]

def _get_filename():
frame, *_ = filter(
lambda frame: getattr(frame, 'code_context', None) == CODE_CONTEXT,
inspect.stack()
)
return frame.filename

imported_from = _get_filename()

if imported_from == 'train.py':
import sklearn
__all__.append('sklearn')

elif imported_from == 'eda.py':
...

To understand how a bug might come from this code, consider this example:

imports.py:

import inspect

CODE_CONTEXT = ['from imports import *\n']

__all__ = []

def _get_filename():
frame, *_ = filter(
lambda frame: getattr(frame, 'code_context', None) == CODE_CONTEXT,
inspect.stack()
)
return frame.filename

imported_from = _get_filename()
print(imported_from)

a.py:

from imports import *

b.py:

from imports import *

main.py:

import a
import b

When you run python3 main.py what will print to the console?


a.py

Why isn't b.py printed? Because modules are only executed once, during their first import. Since a.py imported the module first, each subsequent import of imports.py won't re-execute the module, they will reuse the code that was built during its initial execution.

TLDR;

Any alterations made to __all__ will only apply to the first import of the module, and subsequent imports might be missing the modules that are needed.

How to import py files into a main python script?

I highly recommend checking out the official documentation or a tutorial to learn about the import command.

You can split them into individual files and import them if they are all in the same directory without any problems.

This answer assumes your directory has the following structure:

.
| - file1.py
| - file2.py
| - ...etc
| - main.py

If you wish to nest your directories, see the other answer. Their answer covers how to use __init__.py to take care of that.

If you have the classes defined in individual files, you only need to import standard libraries that are required for that script. For example, if CustomDataFrame required RequiredModule1 and RequiredModule2 but not matplotlib, you would write this in file1.py.

file1.py

import RequiredModule1
import RequiredModule2
#etc
class CustomDataFrame():
code

You can either separate them out into individual files, or group modules together into a single file and import each of them.
file2.py

class CustomDataFrameItem():
code
class Program():
code

main.py

from file1 import CustomDataFrame
from file2 import CustomDataFrameItem, Program
if __name__ == "__main__":
p = Program()
p.run()

Note that you do not put the file extension .py on the from fileX import xxx. The .py is inferred by the interpreter.

How to import the class within the same directory or sub directory?

Python 2

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".

Then just do...

from user import User
from dir import Dir

The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.

bin/
main.py
classes/
user.py
dir.py

So if the directory was named "classes", then you'd do this:

from classes.user import User
from classes.dir import Dir

Python 3

Same as previous, but prefix the module name with a . if not using a subdirectory:

from .user import User
from .dir import Dir

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Import py file in another directory in Jupyter notebook

There is no simple way to import python files in another directory.
This is unrelated to the jupyter notebook

Here are 3 solutions to your problem

  1. You can add the directory containing the file you want to import to your path and then import the file like this:
import sys  
sys.path.insert(0, '/path/to/application/app/folder')

import file

  1. You can create a local module by having an empty __init__.py file in the folder you want to import. There are some weird rules regarding the folder hierarchy that you have to take into consideration.

  2. You can create a module for the file you wish to import and install it globally.



Related Topics



Leave a reply



Submit