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
Related
I work with Django Framework, and I try to open a Python file from outside the Django package.
I use the OS library to get to the path that is outside the Django package, like this:
file_path = OS.path.join(settings.FILES_DIR, 'execute_get_symbols.py')
In file_path I got only the file path
I want to run a function that is inside the file "execute_get_symbols.py".
My questions are:
It is possible?
And if it is possible, so how.
And if it's not possible, So... how can I import files that are outside the Django package and execute the function?
Like from package.file_name import function
You can imoprt your file by adding it to sys.path (the list of paths python looks at to import things) - i believe that this is a kinda hacky way but still commonly used by django users:
import sys
sys.path.append(path_to_your_file)
import your_file
Afterwards you should be able to use it normally
I added the following code in settings file on Django:
sys.path.append(os.path.join(BASE_DIR.parent.parent, "")) # To get the path from root until current directory
And because of that, all the packages recognize on run time.
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.
I have a program consistring of several modules specifying the respective web application handlers and one, specifying the respective router.
The library I use can be found here.
Excerpt from webapp.service (there are more such modules):
from webapp.router import ROUTER
#ROUTER.route('/service/[id:int]')
class ServicePermissions(AuthenticatedService):
"""Handles service permissions."""
NODE = 'services'
NAME = 'services manager'
DESCRIPTION = 'Manages services permissions'
PROMOTE = False
webapp.router:
ROUTER = Router()
When I import the webapp.router module, the webapp.service module does obviously not run. Hence, the #ROUTER.route('/service/[id:int]') decorator is not run and my web aplication will fail with the message, that the respective route is not available.
What is the best practice in that case to run the code in webapp.service to "run" the decorators? I do not really need to import the module itself or any of its members.
As stated in the comments fot the question,
you simply have to import the modules. As for linter complaints, those are the lesser of your problems. Linters are there to help - if they get into the way, just don't listen to them.
So, the simple way just to get your things working is, at the end of your __main__.py or __init__.py, depending on your app structure, to import explicitly all the modules that make use of the view decorator.
If you have a linter, check how to silence it on the import lines - that is usually accomplished with a special comment on the import line.
Python's introspection is fantastic, but it can't find instances of a class, or subclasses, if those are defined in modules that are not imported: such a module is just a text file sitting on the disk, like any data file.
What some frameworks offer as an approach is to have a "discovery" utility that will silently import all "py" files in the project folders. That way your views can "come into existence" without explicit imports.
You could use a function like:
import os
def discover(caller_file):
caller_folder = os.path.dirname(caller_file)
for current, folders, files in os.walk(caller_folder):
if current == "__pycache__":
continue
for file in files:
if file.endswith(".py"):
__import__(os.path.join(current, file))
And call it on your main module with discover(__file__)
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
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(".")