I am having an issue with Python imports. I created a module to conveniently import a few classes inside of the module with a single statement. I put all of my imports inside of the init of that module, but it doesn't seem to work.
maindir\
- driver.py
- Utility\
- __init__.py
- UtilityClasses.py
My folder structure looks like the above.
Inside of UtilityClasses I have one a class that I have created called MyClass.
Inside of the init file in the Utility folder, I have code that says:
import UtilityClasses
from UtilityClasses import MyClass
Inside of driver.py I have code that says:
import Utility
myVar = MyClass(param1)
However, when I run this, I get an error telling me that name MyClass is not defined.
In __init__.py, you can do
from UtilityClasses import *
from SomeOtherFile import *
This will import everything from UtilityClasses.py and SomeOtherFile.py.
But you still have to access it using the module name
Update: You can access everything like this
In driver.py:
from Utility import *
a = MyClass()
b = ClassInSomeOtherFile()
Your code
import Utility
myVar = MyClass(param1)
of course won't work -- MyClass is nowhere mentioned and it won't come magically from nowhere. Explicit is better than implicit:
from Utility import MyClass
myVar = MyClass(param1)
should work like a charm!
Related
Suppose I have a module named 'module1', which has many classes. I want to use all of their classes in my main controller main.py . I can import whole module with import module1, however, I assume that the class names in 'module1' are unique and I do not want to reference module1 every time I call its function such as module1.class1().
How can I import the whole contents of a module without explicitly having to state class/function names and still being able to refer to them without stating the module name.
Such as:
# module1.py.
class Class1():
pass
class Class2():
pass
# __main__.py
import module1
# The following will not work.
object1 = Class1()
object2 = Class2()
You can use the * import pattern
from module1 import *
This lets you use everything inside that module without referencing it.
from module1 import *
instance = Class1()
However, this is generally discouraged. For reasons why, some additional reading:
Why is "import *" bad?
https://www.geeksforgeeks.org/why-import-star-in-python-is-a-bad-idea/
i have following project structure: 1
and here is content of files:
# run.py
from module.submodule.base import DefaultObject
d = DefaultObject()
# module/sumbodule/base.py
from module.submodule.modulea import A
class BaseObject(object):
pass
class DefaultObject(BaseObject):
def return_something(self):
return A()
# module/submodule/modulea.py
from module.submodule.moduleb import B
class A(object):
def return_something(self):
return B()
# module/submodule/moduleb.py
from module.submodule.base import BaseObject
class B(BaseObject):
pass
and when I try to run python3 run.py I get ImportError: cannot import name 'BaseObject
I don't understand why I am able to import class B in modulea.py, but I am not able to class BaseObject in moduleb.py
What is correct way to make imports in such situation?
You have a circular import - base imports modulea which imports moduleb which imports base. Python doesn't support circular imports so it cannot technically work, and even for languages that technically supports them, circular dependencies are a very bad thing anyway.
Your solutions here are either to regroup interdependant objects (classes, functions etc) in a same module - note that Python is not Java and doesn't require "one module per class" (it's even actually an antipattern in Python) - or to move DefaultObject to it's own module.
I am trying to write a unit test. My unit test file is test_file . My main code is in a file(main_file.py) which has a class defined and several methods.
All my files are in same dir, so my tree structure looks like :
├── main_file.py
├── __init__.py
├── test_file.py
In my main_file i have a class name my_class and has method send_request.
In my test file i am trying to import the method to use:
from main_file import send_request
and when i run my unit test (python test_file.py) or even using nosetests it keeps throwing error:
ImportError: No module named main_file
my init.py is just empty.
When you are importing a file, you need to import the CLASS and not just the method if it is inside of a class. So you would need to do:
from main_file import my_class
instead of importing the function within the class. Then when you call the class you can do something such as
my_class.send_request()
when you call the function in your new .py
As you know you could import all of the classes and modules from main_file by doing:
import main_file
from main_file import *
Which will get you all of the classes/functions as well, although that may not be what you're looking for.
Besides that I would make sure they're all in the same directory again, and if it still fails, I usually just save everything to my "downloads" folder. When all else fails, and then it works.
you have to import class to use the method
from main_file import my_class
from my_class import FUNCTION_NAME or from my_class import *
I am creating a custom Python module that I wanted to work similarly to something like numpy where most of the functionality can be accessed by calling np.function() or what have you. However, in creating my submodules and __init__.py file, I think that I've run into a circular import reference. Here's what I'm trying to do and the error I'm seeing, any tips to help me get this working the way I envisioned are greatly appreciated:
Let's call the module "foobar" and say I have a folder named "foobar" on the path and in this folder are three py files: "__init__.py", "foo.py", and "bar.py".
An example of submodule 1, "foo.py":
import bar
class Foo():
def __init__(self):
pass
def runfunc(self):
bar.func()
An example of submodule 2, "bar.py":
import foo
def func():
f=foo.F()
An example of __init__.py:
import numpy
from foo import *
from bar import *
__all__ = ['foo', 'bar']
So what I perceive to be my issue is that when foo is imported, it imports bar, which imports foo, which creates a loop (in my mind). I am also confused as to the use of __init__.py if, when it is called and imports other modules they cannot see each other when executing (i.e. I need to import bar into foo even though __init__.py did this).
When I run something from a script trying to import the entire module, I get the error in bar.py "ImportError: cannot import name foo". I am actually also having this issue elsewhere in the same module where I have a file with the base class "Base" and the extended class "Extended" where base.py needs to import extended.py so it can spawn instances of the expanded class and extended.py needs to import base.py so it can inherit the class.
Thanks for any help in advance!
I am new to python and found that I can import a module without importing any of the classes inside it. I have the following structure --
myLib/
__init__.py
A.py
B.py
driver.py
Inside driver.py I do the following --
import myLib
tmp = myLib.A()
I get the following error trying to run it.
AttributeError: 'module' object has no attribute A
Eclipse does not complain when I do this, in fact the autocomplete shows A when I type myLib.A.
What does not it mean when I import a module and not any of the classes inside it?
Thanks
P
Python is not Java. A and B are not classes. They are modules. You need to import them separately. (And myLib is not a module but a package.)
The modules A and B might themselves contain classes, which might or might not be called A and B. You can have as many classes in a module as you like - or even none at all, as it is quite possible to write a large Python program with no classes.
To answer your question though, importing myLib simply places the name myLib inside your current namespace. Anything in __init__.py will be executed: if that file itself defines or imports any names, they will be available as attributes of myLib.
If you do from myLib import A, you have now imported the module A into the current namespace. But again, any of its classes still have to be referenced via the A name: so if you do have a class A there, you would instantiate it via A.A().
A third option is to do from myLib.A import A, which does import the class A into your current namespace. In this case, you can just call A() to instantiate the class.
You need to do
from mylib import A
Because A is not an attribute of __init__.py inside mylib
When you do import mylib it imports __init__.py
See my answer.
About packages