Kevin Kostlan
Kevin Kostlan

Reputation: 3519

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?

Upvotes: 11

Views: 14016

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124170

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.

Upvotes: 16

Related Questions