How to import nested package using the "as" shorthand?
This question is similar to importing a module in nested packages only the nesting is within the same .py file, not across folders.
In foo.py (All python files are in the same package, and are version 3.4):
class Foo:
class Bar:
...
I can access these subclasses in another .py file:
from . import foo
...
bar = foo.Foo.Bar()
What I would like to do:
from . import foo.Foo.Bar as Bar # DOES NOT WORK: "unresolved reference" error.
...
bar = Bar() # saves typing.
bar2 = Bar()
...
Is there a way to do this?
Inner or Nested classes are not the most commonly used feature in Python. But, it can be a good feature to implement code. The code is straightforward to organize when you use the inner or nested classes.
Organize imports into groups: first standard library imports, then third-party imports, and finally local application or library imports. Order imports alphabetically within each group. Prefer absolute imports over relative imports. Avoid wildcard imports like from module import * .
Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.
There is little point in nesting Python classes; there is no special meaning attached to doing so other than nesting the namespaces. There rarely is any need to do so. Just use modules instead if you need to produce additional namespaces.
You cannot directly import a nested class; you can only import module globals, so Foo
in this case. You'd have to import the outer-most class and create a new reference:
from .foo import Foo
Bar = Foo.Bar
del Foo # remove the imported Foo class again from this module globals
The del Foo
is entirely optional. The above does illustrate why you'd not want to nest classes to begin with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With