I am new to Python, so I might not be seeing the obvious solution to this. I have searched online for a solution and everyone seems to have the same answer. I am trying to import a file from a parent directory in Python. I am coming from JavaScript where you simply type import Function from '../ParenetDirectory/FileThatIncludesFunction' and you can import that module. Every website I have visited says you have to include the parent directory in your freakin' path to import it. Are we serious here? I assume I am missing something because it seems to me that Python would have a more elegant way to do this than editing your freaking path to import a class from a parent directory. Please tell me it does, or explain to me why it doesn't.
You can do this by using the sys module and adding the desired directory to its path.
"../ParenetDirectory/FileThatIncludesFunction.py" :
def Function():
return 'Hello, World!'
main.py :
import sys
sys.path.append('../ParenetDirectory')
from FileThatIncludesFunction import Function
print(Function())
Note that if you want to run this via cmd, make sure that the folder in cmd is exactly where the main.py file is located.
Related
I have an import error with python on VS Code.
Although I had this error, I could run this code with no error.
Maybe, VS Code can not recognize the "import" statement.
I'm glad if anyone solve this problem.
Thank you.
Error on from statement :
Unable to import 'ClassSample'
main.py
#main.py
#path
sys.path.append('sampleClass/myClass')
#my class
from ClassSample import ClassSample #error on from statement : Unable to import 'ClassSample'
ClassSample.py
#ClassSample.py
class ClassSample:
#select param
def selectParam(self, param):
param = "_" + param
return param
The VSCode Intellisense can not analysis this code when linting:
sys.path.append("sampleClass/myClass")
So, it will prompt you with the import error.
This code can work because it's under the workspace folder directly. If you move sampleClass folder to another place, such as the sample folder, it will not work.
This is because you are using the relative path, it depends on the cwd-- workspace folder path by default.
It seems you confused yourself when importing.
You have to tell to python which directory you want to import a module. Since main.py is in another subdirectory, we need to move one folder up and locate the proper subdirectory hence the inclusion of sampleClass when importing.
from sampleClass.myClass import ClassSample
The above code worked when importing the class ClassSample. All you have to do now is to initialize it.
If you want a solution with minimal change, you could do:
from ..myClass.ClassSample import ClassSample
Where .. is moving one directory up which means you are basically doing sampleClass.myClass here.
Sample Code.
# from sampleClass.myClass import ClassSample
from ..myClass.ClassSample import ClassSample
my_class = ClassSample
I have a Python application that conforms to the MVC model so I have folders called Controller, Model and View. In each of these folders I have Python files that I import into each other. It seems to work however when you hover the cursor over the import I see the "Unable to import XXXX" error and I am not sure why this is.
I have an empty __init__ file in each folder and have added the path to system path.
The directory of my application goes like this:
Desktop/Application--¬
Controller--¬
MainController.py
GraphEngine.py
APIMethods.py
Model-------¬
MainModel.py
DatabaseAccess.py
View
I use import sys
sys.path.append('C:/Users/XXXX/Desktop/Data-Processing-Engine-Sorted/Controller')
to set the system path and then use import MainController to actually gain access to the file.
This seems to work fine. The other file locates MainController and uses its methods with no issue, however in the IDE I can't get rid of the "Unable to import MainController" error. I am really quite confused as to why.
Thanks for your help in advance.
I found out the issue! It's very simple and quite embarrassing...
When calling one of the methods I was only calling the module rather than the class, for example:
controller = MainController() Would return with an error while
controller = MainController.MainController() Would create an instance of my class
A question like this has appeared multiple times here, but none of the answers have worked for me. I'm using Python 3.4 with PyCharm as my IDE. In file make_layers.py, I have the following little placeholder of a class (np is my imported numpy):
class Finder:
def __init__(self):
pass
def get_next_shape(self, uses_left):
mask = np.zeros(uses_left.shape, dtype=np.int16)
return mask
In another file in the same directory, box_finder.py, I try to import the class and make a subclass:
import make_layers as ml
class BoxFinder(ml.Finder):
def __init__(self):
pass
When I try to run this, it fails at the import statement, saying
AttributeError: module 'make_layers' has no attribute 'Finder'
I've tried endless variations on the syntax (including things like from make_layers import Finder), but nothing works. It must be something obvious, but I can't see the problem. Any help would be appreciated!
EDIT: Antti, you nailed it. There was a sneaky circular import in there. I moved Finder to its own file, and success! Thank you everyone!
Your modules look correct, and should work.
The most likely source of error is that another file called make_layers.py is being imported. To check this, print ml.__file__ to see where the make_layers module is being imported from.
If you are on Linux, to import your own classes you need to put them into your $PYTHONPATH environment variable.
export PYTHONPATH=$PYTHONPATH:/where/the/file/is
If this is the case i would suggest to put this line in your .bashrc to avoid doing the export in after every restart
Second, to make PyCharm recognise the importable classes from your script you have to mark the directory as sources root. After this PyCharm should see that you have a Finder class inml
i need to call a function from from one python class to another which are at different directories.
I'm using Eclipse and PyDev for developing scripts.
sample.py
class Employee:
def meth1(self,arg):
self.arg=arg
print(arg)
ob=Employee()
ob.meth1("world")
main.py
class main:
def meth(self,arg):
self.arg=arg
print(arg)
obj1=main()
obj1.meth("hello")
I need to access meth1 in main.py
updated code
main.py
from samp.sample import Employee
class main:
def meth(self,arg):
self.arg=arg
print(arg)
obj1=main()
obj1.meth("hello")
After executing main.py it is printing "world" automatically without calling it.
my requirement is i need to call meth1 from main.py explicitly
please find my folder below
import is the concept you need here. main.py will need to import sample and then access symbols defined in that module such as sample.Employee
To ensure that sample.py can be found at import time, the path to its parent directory can be appended to sys.path (to get access to that, of course, you will first need to import sys). To manipulate paths (for example, to turn a relative path like '../samp' into an absolute path, you might want to import os as well and take a look at the standard library functions the sub-module os.path has to offer.
You will have to import the sample.py file as a module to your main.py file. Since the files are in different directories, you will need to use the __init__.py
From the documentation:
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.
Here is a related stack overflow question which explains the solution in more detail.
It's generally not a good idea to alter the sys.path variable. This can make scripts non-portable. Better is to just place your extra modules in the user site directory. You can find out what that is with the following script.
import os
import sys
import site
print(os.path.join(site.USER_BASE, "lib", "python{}.{}".format(*sys.version_info[0:2]), "site-packages"))
Place your modules there. Then you can just import as any other module.
import sample
emp = sample.Employee()
Later you can package it using distutils or setuptools and the imports will still work the same.
This may seem like a easy question, but I have tried my best to figure it out.
I have two files:
Car.py and Dealership.py
They are in the same directory. Dealership.py contains a bunch of methods and another class that I would like to use in Car.py. The class name is "worker".
So in Car.py I write at the top of the file:
from Dealership import worker
I have also tried:
import Dealership
I continually get this error:
No module named Dealership
I can't understand why. As far as I know, and according to pydocs, I am writing the imports correctly, and the files are in the same directory.
Thanks for any advice
You need to add the current directory to the sys.path, so that the Python will try to find the module here.
import sys
sys.path.append(".")