Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python import nested classes shorthand

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?

like image 837
Kevin Kostlan Avatar asked Apr 05 '14 19:04

Kevin Kostlan


People also ask

Can you have nested classes in Python?

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.

How do you organize imports in Python?

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 * .

How do you use relative import in Python?

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.


1 Answers

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.

like image 73
Martijn Pieters Avatar answered Sep 19 '22 01:09

Martijn Pieters