Equivalent to 'from module import *' but including private members - python

I have a git repo that has a python module defining a few classes, some of which are private. I'm using that git repo as a git submodule elsewhere and want to add a new python module with the same name and a few more classes.
The idea is something like:
repo1/module.py:
class _foo:
def __init__(self, _arguments_):
#dostuff
class bar(_foo):
def __init__(self, _arguments_):
#dostuff
repo2/module.py:
class baz(_foo):
def __init__(self, _arguments_):
#dostuff
What I'm stuck on is how to correctly handle the importing in repo2/module.py so that I can use _foo as the super for baz, but also allow importing of repo2/module to provide access to bar.
If I start repo2/module.py with:
from repo1.module import *
I don't get _foo available to use as a super, but I do get bar available when repo2/module.py is imported elsewhere. On the other hand I could do:
from repo1 import module as mod
and then I have mod._foo available to use as the super, but I don't get bar available for use elsewhere.
Is there a way to do something equivalent to
from module import *
that also includes private members, or should I do something like
from module import *
from module import _foo
or is there something nicer/better/safer/cleaner? If it makes a difference, I dislike from module import * and would prefer to avoid it if possible.

Related

package imports libraries without even intializing class

The doubt is the if import a class from a package inside another package like this :
from bar import foo
Does it initialize the class? and if the module has an import at the first line like :
import tensorflow
class foo:
def __init__(self):
# some things
Does it import the package even if we don't initialize the class from another file?
Does it initialize the class?
No, it just gives your program access to that class - ready to be instantiated to an object when you want to (then it will call the __init__ method).
Does it import the package even if we don't initialize the class from another file?
Yes. You can see this as if you were to just import bar, then you would be able to access the imported tensorflow module with bar.tensorflow, i.e. it is actually imported even if there is nothing else in the module.
In your specific case of just importing foo from bar, we can still access tensorflow via the inspect built-in package that will give us a reference to bar and thus .tensorflow from foo.
import inspect
from bar import foo
print(inspect.getmodule(foo).itertools) #<module 'itertools' (built-in)>
I'm not sure if there is an easier way to "get at" bar from foo without using inspect, but this is what I found for the purpose of explaining your case fully!

Why does using import on two files/modules at once giving me errors, but not when I only do it on one? [duplicate]

This question already has answers here:
What can I do about "ImportError: Cannot import name X" or "AttributeError: ... (most likely due to a circular import)"?
(17 answers)
Closed 6 months ago.
I know the issue of circular imports in python has come up many times before and I have read these discussions. The comment that is made repeatedly in these discussions is that a circular import is a sign of a bad design and the code should be reorganised to avoid the circular import.
Could someone tell me how to avoid a circular import in this situation?: I have two classes and I want each class to have a constructor (method) which takes an instance of the other class and returns an instance of the class.
More specifically, one class is mutable and one is immutable. The immutable class is needed
for hashing, comparing and so on. The mutable class is needed to do things too. This is similar to sets and frozensets or to lists and tuples.
I could put both class definitions in the same module. Are there any other suggestions?
A toy example would be class A which has an attribute which is a list and class B which has an attribute which is a tuple. Then class A has a method which takes an instance of class B and returns an instance of class A (by converting the tuple to a list) and similarly class B has a method which takes an instance of class A and returns an instance of class B (by converting the list to a tuple).
Consider the following example python package where a.py and b.py depend on each other:
/package
__init__.py
a.py
b.py
Types of circular import problems
Circular import dependencies typically fall into two categories depending
on what you're trying to import and where you're using it inside each
module. (And whether you're using python 2 or 3).
1. Errors importing modules with circular imports
In some cases, just importing a module with a circular import dependency
can result in errors even if you're not referencing anything from the
imported module.
There are several standard ways to import a module in python
import package.a # (1) Absolute import
import package.a as a_mod # (2) Absolute import bound to different name
from package import a # (3) Alternate absolute import
import a # (4) Implicit relative import (deprecated, python 2 only)
from . import a # (5) Explicit relative import
Unfortunately, only the 1st and 4th options actually work when you
have circular dependencies (the rest all raise ImportError
or AttributeError). In general, you shouldn't be using the
4th syntax, since it only works in python2 and runs the risk of
clashing with other 3rd party modules. So really, only the first
syntax is guaranteed to work.
EDIT: The ImportError and AttributeError issues only occur in
python 2. In python 3 the import machinery has been rewritten and all
of these import statements (with the exception of 4) will work, even with
circular dependencies. While the solutions in this section may help refactoring python 3 code, they are mainly intended
for people using python 2.
Absolute Import
Just use the first import syntax above. The downside to this method is
that the import names can get super long for large packages.
In a.py
import package.b
In b.py
import package.a
Defer import until later
I've seen this method used in lots of packages, but it still feels
hacky to me, and I dislike that I can't look at the top of a module
and see all its dependencies, I have to go searching through all the
functions as well.
In a.py
def func():
from package import b
In b.py
def func():
from package import a
Put all imports in a central module
This also works, but has the same problem as the first method, where
all the package and submodule calls get super long. It also has two
major flaws -- it forces all the submodules to be imported, even if
you're only using one or two, and you still can't look at any of the
submodules and quickly see their dependencies at the top, you have to
go sifting through functions.
In __init__.py
from . import a
from . import b
In a.py
import package
def func():
package.b.some_object()
In b.py
import package
def func():
package.a.some_object()
2. Errors using imported objects with circular dependencies
Now, while you may be able to import a module with a circular import
dependency, you won't be able to import any objects defined in the module
or actually be able to reference that imported module anywhere
in the top level of the module where you're importing it. You can,
however, use the imported module inside functions and code blocks that don't
get run on import.
For example, this will work:
package/a.py
import package.b
def func_a():
return "a"
package/b.py
import package.a
def func_b():
# Notice how package.a is only referenced *inside* a function
# and not the top level of the module.
return package.a.func_a() + "b"
But this won't work
package/a.py
import package.b
class A(object):
pass
package/b.py
import package.a
# package.a is referenced at the top level of the module
class B(package.a.A):
pass
You'll get an exception
AttributeError: module 'package' has no attribute 'a'
Generally, in most valid cases of circular dependencies, it's possible
to refactor or reorganize the code to prevent these errors and move
module references inside a code block.
Only import the module, don't import from the module:
Consider a.py:
import b
class A:
def bar(self):
return b.B()
and b.py:
import a
class B:
def bar(self):
return a.A()
This works perfectly fine.
We do a combination of absolute imports and functions for better reading and shorter access strings.
Advantage: Shorter access strings compared to pure absolute imports
Disadvantage: a bit more overhead due to extra function call
main/sub/a.py
import main.sub.b
b_mod = lambda: main.sub.b
class A():
def __init__(self):
print('in class "A":', b_mod().B.__name__)
main/sub/b.py
import main.sub.a
a_mod = lambda: main.sub.a
class B():
def __init__(self):
print('in class "B":', a_mod().A.__name__)

How do I do python unittest doc's recommended method of lazy import?

Python's docs say that there's an alternative to local imports to prevent loading the module on startup:
https://docs.python.org/3/library/unittest.mock-examples.html#mocking-imports-with-patch-dict
...to prevent “up front costs” by delaying the import.
This can also be solved in better ways than an unconditional local
import (store the module as a class or module attribute and only do
the import on first use).
I don't understand the explanation in brackets. How do I do this? However I think about it, I seem to end up with local imports anyway.
The documentation likely refers to the use of importlib.import_module, which exposes Python's import functionality:
import importlib
class Example():
TO_IMPORT = "os" # the name of the module to lazily import
__module = None
def __init__(self):
if self.__module is None:
self.__module = importlib.import_module(self.TO_IMPORT)
Note that this way the module is only imported once when the class is first instantiated and is not available in global namespace.
Further, it allows you to change which module is imported, which could be useful e.g. in cases where the same class is used as an interface to different backends:
import importlib
class Example():
def __init__(self, backend="some_module"):
self.module = importlib.import_module(backend)

Unable to import class within package

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.

Python imports issue

I have a Utilities module which defines a few functions which are repeatedly used and am also adding in some constants. I'm running into trouble importing these constants though...
Let's say I'm working in class A, and I have a class in my constants also named A
from Utils.Constants import A as DistinctA
class A(object):
.... Implementation ....
some_var = DistinctA.SOME_CONSTANT
class Utils(object):
class Constants(object):
class A(object):
SOME_CONSTANT = "Constant"
I'm probably making this too much like Java, so if so just yell / smack my knuckles with a ruler.
When I attempt to import that class, I get an error that there is no module named Constants. What's this python newbie missing?
The identifier after 'from' must point to a module; you can't refer to a class. While I'm not qualified to say whether your nested classes are 'pythonic', I have never seen it done like that before. I'd be more inclined to create a constants.py module that contains the A class. Then you could do this:
from constants import A as DistinctA
If you really want those constants to live inside utils, you could make utils a package:
utils/
utils/__init__.py
utils/constants.py
Then you can do:
from utils.constants import A as DistinctA

Categories