Suppose I have this folder structure:
module
module.py
__init__.py
main.py
Main.py imports module.py which itself should have functions that are only present in main.py. For example, main.py code:
from module import *
def foo(var):
print var
module.foo_module()
Content of module.py:
def foo_module():
foo("Hello world!")
Is there anyway I can achieve this without repeating the functions? If not, how can I import main.py into module.py?
Many thanks
Everything is an object in python, including functions. You can pass the necessary function as an argument. Whether this makes sense in your case, I don't have enough information to know.
def foo(var):
print var
module.foo_module(foo)
def foo_module(foo):
foo("Hello world!")
Avoid circular imports. You could do that here by placing foo in module.
If you don't want foo in module, you could instead create a separate module bar to hold foo, and import bar in both main and module.
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/
The project is structured as follows:
dir/
__init__.py
foo.py
Foo.py has a function that uses a local assignment:
"""foo.py"""
BAR = 12345
def foo():
# do something with BAR
My goal is to import the object BAR to use in my own code. However, __init__.py contains an import of bar that masks any attempt to import from foo as a module:
"""__init__.py"""
from dir.foo import foo
So when I interact with the package, I'm only able to see dir.foo as a function definition instead of a module. How can I get access to dir.foo.BAR?
Lame hack:
import sys
foo_module = sys.modules["dir.foo"]
bar = foo_module.BAR
Better way might be to ask the author of dir not to shadow the submodule name within the top-level namespace, for example by avoiding naming a function the same way as the module in which it was defined.
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 just noticed that relative import like this:
from .foo import myfunc
print myfunc # ok
print foo # ok
imports both foo and myfunc. Is such behaviour documented anywhere? Can I disable it?
-- Update
Basically problem is following.
bar/foo/__init__.py:
__all__ = ['myfunc']
def myfunc(): pass
bar/__init__.py:
from .foo import *
# here I expect that there is only myfunc defined
main.py:
import foo
from bar import * # this import shadows original foo
I can add __all__ to the bar/__init__.py as well, but that way I have to repeat names in several places.
I am assuming your package layout is
my_package/
__init__.py
from .foo import myfunc
foo.py
def myfunc(): pass
The statement from .foo import myfunc first imports the module foo, generally without introducing any names into the local scope. After this first step, myfunc is imported into the local namespace.
In this particular case, however, the first step also imports the module into the local namespace: sub-modules of packages are put in the package's namespace upon importing, regardless from where they are imported. Since __init__.py is also executed in the package's namespace, this happens to conincide with the local namespace.
You cannot reasonably disable this behaviour. If you don't want the name foo in your package's namespace, my advice is to rename the module to _foo to mark it as internal.
I have some problem, that look like some spaces in my understanding how python does import modules. For example i have module which called somemodule with two submodules a.py and b.py.
content of a.py:
from somemodule.b import b
def a():
b()
print "I'am A"
content b.py
from somemodule.a import a
def b():
a()
print "I'am B"
Now if i would like to invoke any module i get ImportError:
ImportError: cannot import name b
Whats wrong with me?
You've got a circular reference. You import module a which then imports module b. But module b imports function a from module a. But at the time it tries to do so, a has not been defined. Remember that Python import effectively executes the module.
The solution would appear to be to move the function definitions so that they appear before the imports.
Or, as #lazyr suggests, move the import statements to be inside the functions so that the import happens when the function is called, not at module import time.
You have recursive importing here:
a imports b which imports a which imports b which .....
In addition, please make sure you have an __init__.py file in the folder somemodule