简体   繁体   中英

Python - How do I import parent package from extended namespace

So I have two different packages. The first one is my main package "bobzilla", and the other package extends the first "bobzilla.structure".

Ie

bobzilla/
  __init__.py

Where bobzilla/__init__.py contains:

class Foo(object):
    def __init__(self, bar):
        self.bar=bar

And:

bobzilla/
  __init__.py
  structure/
    __init__.py

Where bobzilla/structure/__init__.py contains:

import bobzilla
foo=Foo("bar")

When executing the bobzilla/structure/__init__.py I get:

AttributeError: 'module' object has no attribute 'Foo'

My question is, how can I reference the namespace "bobzilla" from "bobzilla.structure" without "bobzilla.structure" overwriting it.

Note:

The one who set the "This question may already have an answer here" is wrong. I have already tried that and it did not work. This is two different packages, not the same one.

It looks like you're trying to create a namespace package without creating a namespace package, which… isn't going to work.

To explicitly designate a package as a namespace package, you need to use the pkgutil library (or the fancier stuff in setuptools ), something like this at the top of bobzilla/__init__.py :

__path__ = pkgutil.extend_path(__path__, __name__)

If you want an implicit namespace package , you can do that in Python 3.3 and later… but only if bobzilla is empty . Implicit namespace packages cannot contain an __init__.py file, and will never have any contents but their modules. (Well, you could create an implicit namespace package, then add a subpackage or external module that explicit adds things into it once it's created… but I'm not sure why you'd do that.)

bobzilla/structure/__init__.py should be:

from bobzilla import Foo
foo=Foo("bar")

Testing the above with identical structure and code mention in the question. bobzilla being in /path/to/test . Result:

>>> from site import addsitedir
>>> addsitedir("/path/to/test")
>>> import bobzilla.structure as struc
>>> struc.foo
<bobzilla.Foo object at 0x7f2f8c716810>
>>> 

Try:

import bozilla.structure as struct
import bozilla

A working example with the NLTK library, http://nltk.org :

>>> import nltk.corpus as corpus
>>> nltk
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'nltk' is not defined
>>> import nltk
>>> nltk.corpus
<LazyModule 'nltk.corpus'>
>>> corpus
<LazyModule 'nltk.corpus'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM