Python how to import module from another folder
Python how to import module from another folder
Can’t get Python to import from a different folder
I can’t seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:
Here’s the contents of server.py:
The error is: AttributeError: ‘module’ object has no attribute ‘User’
8 Answers 8
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I believe you need to create a file called __init__.py in the Models directory so that python treats it as a module.
Then you can do:
You can include code in the __init__.py (for instance initialization code that a few different classes need) or leave it blank. But it must be there.
You have to create __init__.py on the Models subfolder. The file may be empty. It defines a package.
Then you can do:
Read all about it in python tutorial, here.
There is also a good article about file organization of python projects here.
u=user.User() #error on this line
Because of the lack of __init__ mentioned above, you would expect an ImportError which would make the problem clearer.
You don’t get one because ‘user’ is also an existing module in the standard library. Your import statement grabs that one and tries to find the User class inside it; that doesn’t exist and only then do you get the error.
It is generally a good idea to make your import absolute:
to avoid this kind of ambiguity. Indeed from Python 2.7 ‘import user’ won’t look relative to the current module at all.
If you really want relative imports, you can have them explicitly in Python 2.5 and up using the somewhat ugly syntax:
The right way to import a module located on a parent folder, when you don’t have a standard package structure, is:
(you can merge the last two lines but this way is easier to understand).
This solution is cross-platform and is general enough to need not modify in other circumstances.
You’re missing __init__.py. From the Python tutorial:
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
Put an empty file named __init__.py in your Models directory, and all should be golden.
My preferred way is to have __init__.py on every directory that contains modules that get used by other modules, and in the entry point, override sys.path as below:
This makes the files in specified directories visible for import, and I can import user from Server.py.
In my code I had a cyclic import of classes. For example:
The way I resolved the error was by re-factoring my code to move the functionality in cyclic import class so that I could remove the cyclic import of classes.
Note, I have __init__.py file in my ‘src‘ folder as well as ‘tests‘ folder and still was able to get rid of the ‘ImportError‘ just by re-factoring the code.
Following stackoverflow link provides much more details on Circular dependency in Python.
Importing Python modules from different working directory
I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.
For example, I would call
and agent.py has a number of imports, including:
where checks is in a file in the same directory as agent.py
When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors.
How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g.
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Actually your example works because checks.py is in the same directory as agent.py, but say checks.py was in the preceeding directory, eg;
Then you could do the following:
You should NOT need to fiddle with sys.path. To quote from the Python 2.6 docs for sys.path:
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
You need to add the path to the currently executing module to the sys.path variable. Since you called it on the command line, the path to the script will always be in sys.argv[0].
Now when import searches for the module, it will also look in the folder that hosts the agent.py file.
Set the PYTHONPATH environment variable prior to running your script.
I think you should consider making the agent directory into a proper Python package. Then you place this package anywhere on the python path, and you can import checks as
If you know full path to check.py use this recipe (http://code.activestate.com/recipes/159571/)
To generalize my understanding of your goal, you want to be able to import custom packages using import custom_package_name no matter where you are calling python from and no matter where your python script is located.
A number of answers mention what I’m about to describe, but I feel like most of the answers assume a lot of previous knowledge. I’ll try to be as explicit as I can.
To achieve the goal of allowing custom packages to be imported via the import statement, they have to be discoverable somewhere through the path that python uses to search for packages. Python actually uses multiple paths, but we’ll only focus on the one that can be found by combining the output of sys.prefix (in your python interpreter) with /lib/pythonX.Y/site-packages (or lib/site-packages if you’re using windows) where X.Y is your python version.
Concretely, find the path that your python uses by running:
This path should look something like /usr/local/lib/python3.5/site-packages if you’re using python 3.5, but it could be much different depending on your setup.
Python uses this path (and a few others) to find the packages that you want to import. So what you can do is put your custom packages in the /usr/local/lib/python3.5/site-packages folder. Don’t forget to add an init.py file to the folder.
Python — How to Import Modules From Another Folder?
The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation.
Table of Contents
Problem Formulation
Problem: How to import a file or a module from another folder or directory in Python?
Example: Say, you’ve given the following folder structure:
Method 1: sys.path.append()
The first method appends the path of the file_1.py to the system’s path variable.
Note that you need to replace the first three dots in ‘/. /application/app/folder’ with the concrete path to the applications folder.
By the way, feel free to join my free email academy and download your Python cheat sheets here:
It’s fun—and thousands of Finxters have told me that they love the cheat sheets!
Okay, let’s move on to a slightly modified solution to this problem:
Method 2: sys.path.insert()
A similar alternative is to insert the path of file_1.py to position 1 of the system’s path variable.
This ensures that it’s loaded with higher priority and avoids some naming conflicts:
Again, replace the first three dots in ‘/. /application/app/folder’ with the concrete path to the applications folder.
Method 3: Dot Notation with __init__.py
You can also do the following trick—creating a new package.
However, make sure to include an empty __init__.py file in the directory.
This file tells Python to treat the directory as a package. I’d consider this to be the most Pythonic way of solving this problem.
Method 4: Importlib
A not-so Pythonic alternative — it’s more clunky and is based on external dependencies — would be to use the importlib module.
Here’s an example:
Related Video
Feel free to watch the following explainer video where Finxter Creator Peter shows you how to call a function from another file:
References
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
More Finxter Tutorials
Learning is a continuous process and you’d be wise to never stop learning and improving throughout your life. 👑
What to learn? Your subconsciousness often knows better than your conscious mind what skills you need to reach the next level of success.
I recommend you read at least one tutorial per day (only 5 minutes per tutorial is enough) to make sure you never stop learning!
💡 If you want to make sure you don’t forget your habit, feel free to join our free email academy for weekly fresh tutorials and learning reminders in your INBOX.
Also, skim the following list of tutorials and open 3 interesting ones in a new browser tab to start your new — or continue with your existing — learning habit today! 🚀
Python Basics:
Python Dependency Management:
Import Script from a Parent Directory
How do I import a module(python file) that resides in the parent directory?
Both directories have a __init__.py file in them but I still cannot import a file from the parent directory?
In this folder layout, Script B is attempting to import Script A:
The following code in Script B doesn’t work:
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You don’t import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).
In general it is preferable to use absolute imports rather than relative imports.
You can do this in packages, but not in scripts you run directly. From the link above:
Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always «__main__», modules intended for use as the main module of a Python application should always use absolute imports.
If you create a script that imports A.B.B, you won’t receive the ValueError.
If you want to run the script directly, you can:
Not the answer you’re looking for? Browse other questions tagged python import or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Import Modules From Another Folder in Python
In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder.
It can be done in two ways:
Create a module for demonstration:
File name: module0.py
Python3
Method 1: Using sys.path
sys.path: It is a built-in variable within the python sys module. It contains a list of directories that the interpreter will search in for the required modules.
Python3
Output:
In this approach, Insert or Append the path of the directory containing the modules in sys.path.
Example: Suppose we need to import the following modules from “Desktop\\Task\\modules” in “Desktop\\VScode\\Projects\\ImportModule\\main.py”.
Insert/Append the path to sys.path and import module0 present in the directory and call its run function.
Python3
Output:
Method 2: Using PYTHONPATH
PYTHONPATH : It is an environment variable which you can set to add additional directories where python will look for modules and packages.
Open a terminal or command prompt and enter the following command:
Add the path to PYTHONPATH and import module0 present in the directory and call its run function.
Below is the implementation:
Источники информации:
- http://stackoverflow.com/questions/1046628/importing-python-modules-from-different-working-directory
- http://blog.finxter.com/python-how-to-import-modules-from-another-folder/
- http://stackoverflow.com/questions/8951255/import-script-from-a-parent-directory
- http://www.geeksforgeeks.org/import-modules-from-another-folder-in-python/