简体   繁体   中英

Python import using dot notation doesn't work as expected

I recently installed a library in Python 3.3.2. I tried to import a module from it like this: import cx_Freeze.freezer . However, cx_Freeze.freezer is not defined as I would have expected, as shown in IDLE:

>>> ================================ RESTART ================================
>>> import cx_Freeze.freezer
>>> cx_Freeze.freezer
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    cx_Freeze.freezer
AttributeError: 'module' object has no attribute 'freezer'
>>> 

The same thing happens in the command line. I think I am misunderstanding what happens when you use import with dot notation; what name does the module get assigned to?

In order to fix this seeming problem, I tried import cx_Freeze.freezer as f after restarting the shell, but that gave the same error as before. Can someone please explain why these import statements aren't giving me access to the module?

cx_Freeze/__init__.py has the following contents:

version = "5.0"

import sys
from cx_Freeze.dist import *
if sys.platform == "win32":
    from cx_Freeze.windist import *
elif sys.platform == "darwin":
    from cx_Freeze.macdist import *
from cx_Freeze.finder import *
from cx_Freeze.freezer import *
from cx_Freeze.main import *

del dist
del finder
del freezer

The parts important to this question are from cx_Freeze.freezer import * and del freezer . The first of those lines imports everything listed in cx_Freeze.freezer.__all__ directly into the cx_Freeze package, and the second line makes cx_Freeze.freezer not available directly. Thus, you should probably just use cx_Freeze ; it contains all the parts of cx_Freeze.freezer designed for external use. If you need cx_Freeze.freezer , perhaps to use some of the private functionality, you can find it in sys.modules :

import sys
freezer = sys.modules['cx_Freeze.freezer']

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