Django import module: Unable to import module by name - python

I have sub-directories inside my django app folder, and on each I was trying to call a module. The issue that I am having is that I am able to import a module by using * but not by name which produces an error "Exception Value: cannot import name [my module]"
from foo import Bar # throws error
from foo import * # works
I dont know if I am missing anything on my settings.py but definitely I have included the app directory on my INSTALLED_APPS and also I have init.py on each directory. I also tried to check if my app folder is included on python paths and it was included.
Any help will be appreciated. THanks in advance

I expect you are thinking in terms of Java. In Python, you import things by module, not class name. So if a directory foo contains a file bar.py which defines a class Bar, you must do from foo.bar import Bar, not from foo import Bar.

After looking over my directories I found out that I have a file that has the same name as my app/Foo. after removing this it started working.
Foo/
- Bar.py
Process/
- Foo.py # deleted this
- views.py
from Foo import Bar #Foo.py was overriding the app/Foo that I was trying to call
Thanks for all your response!

if this is in django, try doing
from . import form
from . import models
from . import views
This should solve the issue.
Apart from that, fist make sure you have a init.py file in the directory.

Related

How to import a file in python?

How to access models/usrs from resources/user
├───models
| └───user.py
├───resources
| └───user.py
First I import it like this one:
from code.models.user import UserModel
But I got a compile-time error:
`Cannot find reference 'models' in 'code.py'`
And I tried another way like this one:
from ..models.user import UserModel
But I got a runtime error:
ImportError: attempted relative import beyond top-level package
And I added init.py in both files but still doesn't work.
And also I tried these solutions but they don't fix my issue, please help me
Add the models and resources directories to your $PYTHONPATH or use sys.path:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
Or:
import sys
sys.path.insert(0, "/home/project-name/models")
Or add "__ init__.py" to code directory:
from code.models import user
And finally, I fix my issue:
As #Little Bamboo said: I used sys concept for the import like below:
import sys
sys.path.append("D:\\Projects\\Python\\UdemyProjects\\SixSimplifyingTwo")
from mycode.models.userone import UserModel
But that was not all, some of my files had the same names and I changed the names of the files.
And also I had a folder called code, and from the below link I understood that code is a built-in Python module and I changed the code folder name.
Werkzeug AttributeError: 'module' object has no attribute 'InteractiveInterpreter'

Python relative imports testing my sanity

EDIT: A circular dependency issue was the reason why from .. import auth didn't work, see my own answer below. Cheers to all.
I'm dabbling with relative imports in Python while reorganizing some code and what should have taken 10 minutes is now taking untold amounts of time. Here's my file structure:
project/
/__init__.py
/application.py
/lib/
/__init__.py
/auth.py
/utils.py
/views/
/__init__.py
/login_view.py
/test.py
In login_view.py I have:
from . import auth
which yields: ImportError: cannot import name auth
However this works:
from ..auth import untoken, req_auth_or_error
Which I don't understand: auth is only one level above login_view, why the .. and not .?
This also fails with the same error:
from .. import auth
In test.py I tried the following:
import types
from .. import *
def imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
print 'imported: ', val.__name__
imports()
which results in:
imported: lib.utils
imported: lib.views
imported: types
... I'm at a loss as to why lib.auth is not imported. What am I doing wrong?
I'm running the code as such (the abs. path is /scratch/project/):
$ cd project/
$ ./application.py
In Python a single dot in import represents the current package, NOT the current module.
Then every additional dot represents a new level of "parentness" (ok this word does not exist but I think it expresses well what I mean).
So the behaviour you notice in your first case is just normal.
For your second case, I to reproduced your hierarchy with those contents:
application.py
lib.views import login_view
print("oh yeah")
login_view.py
lib.views import login_view
print("oh my god")
... and running application.py from the project directory does not cause any error. I get the following output:
$ python application.py
oh my god
oh yeah
However, adding a from lib.views import test (using the exact same test.py content you provided) in the application.py gives me the following output showing that some lib modules are not loaded:
$ python application.py
oh my god
imported: types
imported: lib.views
imported: lib.auth
oh yeah
The lib.utils module is missing :/
What I think is that since from .. import * names nothing: no package, no module, no function or variable or anything, the import statement simply imports nothing. TH displayed modules/packages are only the one which have been loaded earlier.
That said, there is a way to force a "correct" behaviour by using the __all__ magic variable, which defines which modules are loaded when using the splat import, in the lib/__init__.py file:
__all__ = ['auth', 'views', 'utils']
After doing this, running again the application.py file shows the following:
$ python application.py
oh my god
imported: types
imported: lib.auth
imported: lib.views
imported: lib.utils
oh yeah
In the first case, from . import auth the . means the package views. That is why Python can't find it.
But, to avoid those problems is recommended that you use absolute import instead of relative imports.
What if you went up 1 more directory when importing?
from ... import auth
The problem was a circular dependency one and not one of relative imports.
Indeed, .. is needed to load a module from the parent directory.
However somewhere in auth.py I had an import views.login_view. I believe that the from .. import auth in login_view.py tried to import the auth module as it was being loaded itself. This is probably why from ..auth import untoken works because those functions had already been loaded.

Python not able to reference module in parent

I am trying to set up a library in python. I have created a setup.py file and in a folder under that I have a library folder, and then I tried to create an sample and test folder (for sample code and tests that I would include)
Folders:
- setup.py
- cvImageUtils # this is the library
- __init__.py # this includs ColorUtils
- ColorUtils.py # this includes a class called ColorUtils
- examples
- color.py # this is shown below
init.py in ColorUtils folder
from . import ColorUtils
ColorUtils.py
class ColorUtils:
def __...
Color.py
from cvImageUtils import ColorUtils
m1 = cv2.imread(os.path.join(image_folder, "bb.jpeg"), 1) # 1 = load color
cv2.imshow('grayscale', ColorUtils.convert_rbg_to_grayscale(m1))
At first, it said, unable to find the module, so I added to the top of the file the following based on another SO solution:
import sys
sys.path.append('../')
Now that seems broken to me already, but it did get me past the no module found, but now it says ColorUtils has no method convert_rbg_to_grayscale. So Then I had to change it to ColorUtils.ColorUtils.convert_rbg_to_grayscale
cv2.imshow('grayscale', ColorUtils.ColorUtils.convert_rbg_to_grayscale(m1))
How can I setup the folder so that it allows me to include the library without sys, and call it without declaring ColorUtils twice.
change your __init__.py:
from cvImageUtils.ColorUtils import ColorUtils
I don't think you'll need to import sys anymore, and you don't have import ColorUtils twice. but just like you have to instantiate an object, you should create a ColorUtils object.
my personal preference would be not creating a Class for Utils.
you might have done this already, but if you want to use a method straight from a class like you did in python, you might want to declare it static.
class ColorUtils:
#staticmethod
def util_method():
pass
then you can just do:
ColorUtils.util_method()
Update:
you can read more about relative/absolute import from here as well.
to fix your actual problem though, you can do:
color.py
remove your import sys and sys call from color.py
change: import cvImageUtils.ColorUtils as ct
to: from cvImageUtils.ColorUtils import *
remove all your ct reference instead just use the actual functions.
cvImageUtils/__init__.py
change: from . import ColorUtils
to __all__=['ColorUtils']
I was able to run color.py to get all the images printed out on screen.
a image.png was also generated locally as well.
Every directory that you want to expose in module search(we usually hide test.py) in python need a init.py file. That should be rule of thumb, by using sys module you can add the module to your "module search path".
After having init.py in your directories, you need to import packages/modules/funcitons you want to use:-
import cvImageUtils.ColorUtils.convert_rbg_to_grayscale
You can execute following code in python to see, what have included in your sys path(used by python to search for modules/packages)
import sys
sys.path
Look into below links for more detailed explations
https://www.programiz.com/python-programming/package
https://www.programiz.com/python-programming/modules#search

Python-Django: module import syntax conflicting

I hope this is not a duplicate, I couldn't find any other answer.
Going straight to the point, my problem is as follows.
I have a project in Django where django-apps use external custom modules.
This is the structure:
Project_dir/
- core/
- module_1.py
- module_2.py
- django_project/
- __init__.py
- settings.py
- urls.py
- wsgi.py
- django_app_A/
- views.py
- manage.py
The problem is that I need to import some classes and methods of moudule_2 in module_1, and I would do so by simply, in module_1,
from module_2 import foo
When I run module_1 for testing, everything works fine. Nonetheless, I need to import module_1 in django_app_A/views.py, and I would do so by
from core.module_1 import Bar
Here's the problem: if I have another relative import in module_1, as I have, I will get a
ModuleNotFoundError: No module named 'module_2'
UNLESS I use in module_1 the syntax
from .module_2 import foo
By doing so, the Django app will work fine and page will properly load, but at the same time I "break" the module_1, as I won't be able to run it stand-alone anymore, as I will get a
ModuleNotFoundError: No module named '__main__.module_2'
I have no idea how to fix this conflict and make both import syntax work at the same time.
Any clues? Am I missing something?
Thanks in advance
You should use absolute imports as much as you can.
from core.module_2 import foo
I can't be sure, but it sounds like a circular import problem to me.
Do you need the import to be on the "main" level? If you import module 2 inside of a class or function, simply write
def function_in_question():
import module_1
return module_1.whatever()
Another thing to look for: are you using it in a way that is actually circular? A function in module_2 using a function in module_1 that uses the function in module_2?

Python: Unit Testing Module and Relative Imports

Currently have the following file hierarchy:
\package
__init__.py
run_everything.py
\subpackage
__init__.py
work.py
work1.py
work2.py
\test
__init__.py
test_work.py
test_work1.py
My first question is regarding relative imports. Suppose in \subpackage\work.py I have a function called custom_function(), and I would like to test that function in test_work.py. For some reason I can not figure out how to make this import from one module to another. Trying from .. subpackage.work1 import custom_function() does not seem to work, and yields the error Attempted relative import in non-package Is there any way to resolve this?
2)
I would like to run all test files from run_everything.py with one function, would adding a suite() function in each test_work*.py file, which adds each unit_testing class to suite.addTest(unittest.makeSuite(TestClass)), and finally importing them into the top-level run_everything.py be the most conventional way in Python2.7?
Here is a hack*
Insert the path's to "subpackage" and "test" to your python path in run_everything using:
import sys
sys.path.insert(0, '/path/to/package/subpackage')
sys.path.insert(0, '/path/to/package/test')
And then, you can import all your files using vanilla imports in run_everything:
import work, work1, work2
import test_work, test_work1
*This won't permanently affect your PYTHONPATH.

Categories

Resources