I was looking at a repo and came across a somewhat weird line
from flask.ext.testing import TestCase as Base, Twill
What does it mean to import like this? I have not seen it before and unfortunately it's rather hard to google.
That line tells Python to import TestCase and Twill from the package flask.ext.testing, but to import TestCase under the name of Base.
From the docs:
If the module name is followed by as, then the name following as is
bound directly to the imported module.
Below is a demonstration with the search and match functions from the re module:
>>> from re import search as other, match
>>> match # The name match refers to re.match
<function match at 0x02039780>
>>> other # The name other refers to re.search
<function search at 0x02048A98>
>>> search # The name search is not defined because it was imported as other
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'search' is not defined
>>>
Related
I need help interpreting the following error message and possibly troubleshooting what steps to take next as my google searching hasn't gotten me anywhere.
>>> from typing import asyncgenerator
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
from typing import asyncgenerator
ImportError: cannot import name 'asyncgenerator' from 'typing' (C:\Program Files\Python39\lib\typing.py) ```
It should be:
from typing import AsyncGenerator
AsyncGenerator uses capital letters. Technically, asyncgenerator does not exist because the name does not match exactly.
It looks like the name is not supposed to be all lowercase. Try the command
from typing import AsyncGenerator
I'm using this code.
from azlyrics import artists
print(artists("O"))
In the module named 'azlyrics' the function 'artists' is well defined. But I get this error.
Traceback (most recent call last):
File "C:\Users\user\Desktop\python\eminem\New folder\azlyrics-master\examples\get_artists.py", line 1, in <module>
from azlyrics import artists
ImportError: cannot import name 'artists' from 'azlyrics' (C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\azlyrics\__init__.py)
What could be the problem?
There must be a bug in the azlyrics documentation or packaging.
This works:
>>> from azlyrics.azlyrics import artists
>>> artists("O")
'["Oakenfold, Paul", "Oakes, Ryan", "Oak Ridge Boys,
The", "Oak, Winona", "O.A.R. (Of A Revolution)", "Oasis", "Obel, Agnes", "Oberst, ...]'
There is a mistake in azlyrics v1.3.2, relative import should be used in azlyrics/__init__.py:
instead of:
from azlyrics import *
we should have:
from .azlyrics import *
This is fixed but a release is not done.
I have a script that does the following:
import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
Later on, I call a class of the this module with the same name:
config = storage_configuration_reader()
If I import it like the above I get the following NameError NameError: global name 'storage_configuration_reader' is not defined but if I use the following code:
import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
import storage_configuration_reader
config = storage_configuration_reader()
Then I get this error TypeError: 'module' object is not callable
Changing the name of the imp.load_source doesn't help to import the object:
import imp
imp.load_source("storage_configuration","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
<module 'storage_configuration' from '/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.pyc'>
import storage_configuration
config = storage_configuration_reader()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'storage_configuration_reader' is not defined
Which is the best way (AKA working way) to import an object like this?
Info: The storage_configuration_reader definition:
class storage_configuration_reader(object):
"""
Class configuration_reader: this object read the config file and return the
different configuration values
"""
...
imp.load_source loads the module using the given path and name it using the new name, it's not like from your_module_at_path import your_class_by_name, it's just like import your_module_at_path as new_name (not exactly the same).
Besides, you need to assign the name to a variable to use it:
wtf=imp.load_source("new_module_name", your_path)
#wtf is the name you could use directly:
config = wtf.storage_configuration_reader()
the name new_module_name is stored as a key in dictionary sys.modules, you can use it like this:
sys.modules['new_module_name'].storage_configuration_reader()
A simpler way to import a module from some other directory is adding the module's path to sys.path:
import sys
sys.path.append("/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao")
import storage_configuration_reader
config = storage_configuration_reader.storage_configuration_reader()
FIXED: turns out there is a module already called parser. Renamed it and its working fine! Thanks all.
I got a python NameError I can't figure out, got it after AttributeError. I've tried what I know, can't come up with anything.
main.py:
from random import *
from xml.dom import minidom
import parser
from parser import *
print("+---+ Roleplay Stat Reader +---+")
print("Load previous DAT file, or create new one (new/load file)")
IN=input()
splt = IN.split(' ')
if splt[0]=="new":
xmlwrite(splt[1])
else:
if len(splt[1])<2:
print("err")
else:
xmlread(splt[1])
ex=input("Press ENTER to Exit...")
parser.py:
from xml.dom import minidom
from random import *
def xmlread(doc):
xmldoc = minidom.parse(doc)
itemlist = xmldoc.getElementsByTagName('item')
for s in itemlist:
print(s.attributes['name'].value,":",s.attributes['value'].value)
def xmlwrite(doc):
print("no")
And no matter what I get the error:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 10, in <module>
xmlwrite.xmlwrite(splt[1])
NameError: name 'xmlread' is not defined
The same error occurs when trying to access xmlwrite.
When I change xmlread and xmlwrite to parser.xmlread and parser.xmlwrite I get:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 15, in <module>
parser.xmlread(splt[1])
AttributeError: 'module' object has no attribute 'xmlread'
The drive is K:\ because it's my personal drive at my school.
If your file is really called parser.xml, that's your problem. It needs to be parser.py in order to work.
EDIT: Okay, since that wasn't your issue, it looks like you have a namespacing issue. You import your parser module twice when you use import parser and then from parser import *. The first form of it makes "parser" the namespace and the second form directly imports it, so in theory, you should have both parser.xmlwrite and xmlwrite in scope. It's also clearly not useful to import minidom in main.py since you don't use any minidom functionality in there.
If you clear up those and still have the issue, I would suggest looking at __ init __.py. If that still does nothing, it could just plain be a conflict with Python's parser module, you could substitute a name like myxmlparser.
Assume the following code structure:
#### 1/hhh/__init__.py: empty
#### 1/hhh/foo/__init__.py:
from hhh.foo.baz import *
#### 1/hhh/foo/bar.py:
xyzzy = 4
#### 1/hhh/foo/baz.py:
import hhh.foo.bar as bar
qux = bar.xyzzy + 10
I run python inside 1/ and do import hhh.foo.baz. It fails:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "hhh/foo/__init__.py", line 1, in <module>
from hhh.foo.baz import *
File "hhh/foo/baz.py", line 1, in <module>
import hhh.foo.bar as bar
AttributeError: 'module' object has no attribute 'foo'
Now I replace baz.py with:
# 1/hhh/foo/baz.py:
from hhh.foo.bar import xyzzy
qux = xyzzy + 10
and again do import hhh.foo.baz. Now it works, although I’m loading the same module, only binding a different name.
Does this mean that the distinction between import module and from module import name goes beyond just identifiers? What exactly is going on here?
(I know I can use relative imports to work around all this, but still I’d like to understand the mechanics. Plus I don’t like relative imports, and neither does PEP 8.)
When you write from hhh.foo.bar import xyzzy Python interpreter will try to load xyzzy from module hhh.foo.bar. But if you write import hhh.foo.bar as bar it will try first to find bar in hhh.foo module. So it evaluates hhh.foo, doing from hhh.foo.baz import *
. hhh.foo.baz tries to evaluate hhh.foo, hhh.footries to evaluate hhh.foo.baz, cyclic imports, exception.
in 1/hhh/foo/__init__.py you need to set the __all__ list with the names of what you want to export. i.e. __all__ = ["xyzzy"]
Why do you import from hhh.foo.bar in hhh.foo? import bar should suffice there.