Python import using dot notation doesn't work as expected - python

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']

Related

pytest: how might I simulate non-availability of a pip-installed module? [duplicate]

I'm trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils):
try:
import pwd
do stuff
except ImportError:
do other stuff
I want the import to fail, as it will on the actual GAE server, but the problem is that it doesn't fail on my development box (ubuntu). How to make it fail, given that the import is not in my own code?
Even easier than messing with __import__ is just inserting None in the sys.modules dict:
>>> import sys
>>> sys.modules['pwd'] = None
>>> import pwd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pwd
In your testing framework, before you cause docutils to be imported, you can perform this setup task:
import __builtin__
self.savimport = __builtin__.__import__
def myimport(name, *a):
if name=='pwd': raise ImportError
return self.savimport(name, *a)
__builtin__.__import__ = myimport
and of course in teardown put things back to normal:
__builtin__.__import__ = self.savimport
Explanation: all import operations go through __builtin__.__import__, and you can reassign that name to have such operations use your own code (alternatives such as import hooks are better for such purposes as performing import from non-filesystem sources, but for purposes such as yours, overriding __builtin__.__import__, as you see above, affords truly simple code).

Python cannot import from another file name not defined

I am trying to import a custom function from another python file but keep getting an error NameError: name 'testme' is not defined. I confirmed that I am importing the file correctly according to this SO post and that the function is top level. What else can I try to fix this?
My main python file is:
import sys
import dbconn
#from dbconn import testme #<----did not work
dev=True
if(dev):
categId='528'
pollIds=[529,530,531]
else:
categId=str(sys.argv[1])
pollIds=[529,530,531]
df=testme(categIds)#callServer(categId,pollIds)
df
if(not categId.isdigit):
print('categ id fail. expected digit got: '+categId)
.....
and dbconn.py:
import pymysql #pip3 install PyMySQL
import pandas as pd
from scipy.stats.stats import pearsonr
from scipy import stats
def testme(categIds):
try:
df=categIds
except Exception as e:
print("broke")
return categIds
Not sure if it makes a difference but I am running the main python file from within a Jupyter notebook, and have a compiled version of dbconn.py in the same directory
In response to the suggestions I tried:
df=dbconn.testme(categIds)
got the error:
module 'dbconn' has no attribute 'testme'
You Have to follow these fox exact import
1)import <package>
2)import <module>
3)from <package> import <module or subpackage or object>
4)from <module> import <object>
in your case, you have tried
from dbconn import testme
you have to use only packages in from section and module in import section
like >>
from testme import dbconn

Import all modules from a package

I have setup the following structure: Python 201: Creating Modules and Packages.
The mymathpackage is available at that link.
When you run the code below:
import sys
sys.path.append('G:\MyPython\Package')
import mymath
print (mymath.add(4,5))
print (mymath.division(4, 2))
print (mymath.multiply(10, 5))
print (mymath.fibonacci(8))
print (mymath.squareroot(48))
Python Version: 3.4
outer __init__.py contents:
from add import add
from divide import division
from multiply import multiply
from subtract import subtract
from adv.fib import fibonacci
from adv.sqrt import squareroot
My goal is to call division,add,subtract, etc, but if I try to call the module I get:
Traceback (most recent call last):
File "G:\MyPython\Package\myscript.py", line 1, in <module>
import mymath
File "G:\MyPython\Package\mymath\__init__.py", line 1, in <module>
from add import add
ImportError: No module named 'add'
Python 3.x has changed import resolution. You must now specify a full relative import if you want to perform a relative import.
from .add import add

package import and NameError

I have some troubles with importation of self-made modules, I just can't see what I am doing wrong.
I have a package named basics, which has all my base classes
I have a second package named components, and every module in componentsuses the modules from basics.
I have a script file, located in another folder, which calls upon the basics and components modules.
I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "H:/scripts/CIF_utilities/scripts/hello world.py", line 11, in <module>
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
File "H:\scripts\CIF_utilities\components\textwriter.py", line 23, in __init__
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
NameError: global name 'Layout' is not defined
There is my script: hello world.py
#hello world.py
import basics
from components.textwriter import *
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
cell=TW.writeText('Hello World',30e3)
cell.draw()
layout=Layout()
layout.addCell(cell)
layout.workCell=cell
layout.exportCIF('hello world',os.getcwd())
textwriter.py is the one giving the error. In init, I load some data from a preformatted file using the Layout class (which will make the import)
in textwriter.py
#texwriter.py
import basics
import os, os.path, sys
import re
from numpy import *
from scipy import *
class TextWriter:
def __init__(self,pathToCIF=None):
if pathToCIF==None:
path=os.path.split(textwriter.__file__)[0]
else:
path=pathToCIF
###line that crashes is here
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
self.alphabet=layout.workCell
There is the layout.py class:
#layout.py
import basics
from numpy import *
from scipy import *
import Tkinter
import tkFileDialog
import os, os.path
import re
import datetime
class Layout:
countCell=0
#classmethod
def getNewNumber(self):
Layout.countCell+=1
return Layout.countCell
def __init__(self,File=None):
self.cellList=[]
self.layerList=[]
self.nameFile=""
self.comments=""
self.workCell=None
if File!=None:
self.importCIF(File)
the init.py of the basics package contains all the necessary importations:
#__init__.py in basics folder
from baseElt import *
from cell import *
from layout import *
from transformation import *
the init.py from components is empty
I am currently using the anaconda 64bits distribution (python 2.7 if I recall well)
Thanks for your much needed help!
Since Layout is imported in basics/__init__.py, it only exists in the basics namespace, not in helloworld.py. Either access it with
layout = basics.Layout()
or explicitly import Layout into helloworld.py with
from basics import Layout
In textwriter.py, you want to switch
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
for
layout=basics.Layout(File=os.path.join(path,'alphabet.CIF'))
You may have similar problems along your code. it is good to note that it is not pythonic to use
from package import *
It is recommended to instead use
from package_or_module import specific_item
import package_or_module
Remember, if you import with regular import you have to use the module/package name to access the object you want (i.e. basics.Layout).

ImportError: cannot import name SlotMap

I am encountering an import error
Traceback (most recent call last):
File "C:\Users\bartis\Desktop\Python\TEC-KB\SlotMapper.pyw", line 9, in <module>
from SlotMapper import SlotMap
File "C:\Users\bartis\Desktop\Python\TEC-KB\SlotMapper.pyw", line 9, in <module>
from SlotMapper import SlotMap
ImportError: cannot import name 'SlotMap
This should be a straightforward issue, but I can’t seem to find the problem. If I place the SlotMapper.py file in the same directory as the GUI I am using the import of SlotMap occurs without error. If I move the file to a directory under the current working directory and add - sys.path.append(os.path.join(os.getcwd(), 'appLib')) I receive the error above. See import statements and modification of PYTHONPATH below. I know the PYTHONPATH has been modified after I checked it from the debugger. I also know since there are other files under appLib required for the GUI to operate. Finally, I have checked all of the imported files for a circular reference and find none… So stuck. Any suggestions welcome
import os
import sys
sys.path.append(os.path.join(os.getcwd(), 'appLib', 'KB-GUI'))
sys.path.append(os.path.join(os.getcwd(), 'appLib'))
from tkinter import *
from SlotMapper import SlotMap
from ShelfTypeSelection import ShelfTypeSelector
from PackTypeSelection import PackTypeSlotMappingSelector
from EntryWidgets import EntryBase, ShelfSlotEntry
The reason this is not working is because your file is named SlotMapper.pyw. The line
from SlotMapper import SlotMap
is trying to import SlotMap from your current file, hence the error. Try renaming your file to slotmapper_test.pyw or something like that, and everything should work as expected. You don't want your code files to have the same names as any modules you're trying to import, as the import mechanism will try to find the classes/functions there first, instead of searching your modules first.

Categories