I am working with Python's decimal module, but when I do:
>>>from decimal import Decimal
>>>d = Decimal('3.14')
>>>d.__slots__
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'decimal.Decimal' object has no attribute '__slots__'
>>>Decimal.__slots__
raceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: type object 'decimal.Decimal' has no attribute '__slots__'
But when I inspect Decimal class in PyCharm (_pydecimal.py), I see:
class Decimal(object):
"""Floating point class for decimal arithmetic."""
__slots__ = ('_exp','_int','_sign', '_is_special')
...
Supposedly, I should be able to get __slots__ from class/instance, but I didn't. What am I missing here? (This kinda behaves like Python's built-in int class.)
If you look at decimal.py, you'll see this:
try:
from _decimal import *
from _decimal import __doc__
from _decimal import __version__
from _decimal import __libmpdec_version__
except ImportError:
from _pydecimal import *
from _pydecimal import __doc__
from _pydecimal import __version__
from _pydecimal import __libmpdec_version__
It first tries to import from _decimal, which is a precompiled shared library on my system. The code you found via PyCharm is instead in the fallback _pydecimal implementation. I suspect your code is in fact loading the _decimal version of Decimal, which simply doesn't use __slots__.
Related
This question already has answers here:
Use 'import module' or 'from module import'?
(23 answers)
Closed 8 years ago.
I'm wondering if there's any difference between the code fragment
from urllib import request
and the fragment
import urllib.request
or if they are interchangeable. If they are interchangeable, which is the "standard"/"preferred" syntax (if there is one)?
It depends on how you want to access the import when you refer to it.
from urllib import request
# access request directly.
mine = request()
import urllib.request
# used as urllib.request
mine = urllib.request()
You can also alias things yourself when you import for simplicity or to avoid masking built ins:
from os import open as open_
# lets you use os.open without destroying the
# built in open() which returns file handles.
Many people have already explained about import vs from, so I want to try to explain a bit more under the hood, where the actual difference lies.
First of all, let me explain exactly what the basic import statements do.
import X
Imports the module X, and creates a reference to that module in the
current namespace. Then you need to define completed module path to
access a particular attribute or method from inside the module (e.g.:
X.name or X.attribute)
from X import *
Imports the module X, and creates references to all public objects
defined by that module in the current namespace (that is, everything
that doesn’t have a name starting with _) or whatever name
you mentioned.
Or, in other words, after you've run this statement, you can simply
use a plain (unqualified) name to refer to things defined in module X.
But X itself is not defined, so X.name doesn't work. And if name
was already defined, it is replaced by the new version. And if name in X is
changed to point to some other object, your module won’t notice.
This makes all names from the module available in the local namespace.
Now let's see what happens when we do import X.Y:
>>> import sys
>>> import os.path
Check sys.modules with name os and os.path:
>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
Check globals() and locals() namespace dict with name os and os.path:
>>> globals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> locals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> globals()['os.path']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'os.path'
>>>
From the above example, we found that only os is added to the local and global namespaces.
So, we should be able to use os:
>>> os
<module 'os' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> os.path
<module 'posixpath' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>
…but not path:
>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>
Once you delete the os from locals() namespace, you won't be able to access either os or os.path, even though they do exist in sys.modules:
>>> del locals()['os']
>>> os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> os.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
Now let's look at from.
from
>>> import sys
>>> from os import path
Check sys.modules with name os and os.path:
>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
So sys.modules looks the same as it did when we imported using import name.
Okay. Let's check what it the locals() and globals() namespace dicts look like:
>>> globals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> locals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['os']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'os'
>>>
You can access by using path, but not by os.path:
>>> path
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> os.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
Let's delete 'path' from locals():
>>> del locals()['path']
>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>
One final example using aliasing:
>>> from os import path as HELL_BOY
>>> locals()['HELL_BOY']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['HELL_BOY']
<module 'posixpath' from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>
And no path defined:
>>> globals()['path']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'path'
>>>
One pitfall about using from
When you import the same name from two different modules:
>>> import sys
>>> from os import stat
>>> locals()['stat']
<built-in function stat>
>>>
>>> stat
<built-in function stat>
Import stat from shutil again:
>>>
>>> from shutil import stat
>>> locals()['stat']
<module 'stat' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc'>
>>> stat
<module 'stat' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc'>
>>>
THE LAST IMPORT WILL WIN
There is a difference. In some cases, one of those will work and the other won't. Here is an example: say we have the following structure:
foo.py
mylib\
a.py
b.py
Now, I want to import b.py into a.py. And I want to import a.py to foo. How do I do this? Two statements, in a I write:
import b
In foo.py I write:
import mylib.a
Well, this will generate an ImportError when trying to run foo.py. The interpreter will complain about the import statement in a.py (import b) saying there is no module b. So how can one fix this? In such a situation, changing the import statement in a to import mylib.b
will not work since a and b are both in mylib. The solution here (or at least one solution) is to use absolute import:
from mylib import b
Source: Python: importing a module that imports a module
You are using Python3 were urllib in the package. Both forms are acceptable and no one form of import is preferred over the other. Sometimes when there are multiple package directories involved you may to use the former from x.y.z.a import s
In this particular case with urllib package, the second way import urllib.request and use of urllib.request is how standard library uniformly uses it.
In python 2.x at least you cannot do import urllib2.urlopen
You have to do from urllib2 import urlopen
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2.urlopen
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named urlopen
>>> import urllib.request
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named request
>>>
My main complaint with import urllib.request is that you can still reference urllib.parse even though it isn't imported.
>>> import urllib3.request
>>> urllib3.logging
<module 'logging' from '/usr/lib/python2.7/logging/__init__.pyc'>
Also request for me is under urllib3. Python 2.7.4 ubuntu
I think I'm having troubles importing pylab. A similar error occurs when I import numpy.
Here is my code
from math import radians, sin, cos
from pylab import plot, xlabel, ylabel, title, show
v0=input("Enter v0 (m/s)...")
alpha0=input("enter alpha0 (degrees)...")
g=input("Enter g (m/s^2)..")
radalpha0=radians(alpha0)
t_inc=0.01
t=0
i=0
x=[]
y=[]
x.append(v0*cos(radalpha0)*t)
y.append(v0*sin(radalpha0)*t-0.5*g*t*t)
while y[i]>=0:
i=i+1
t=t+t_inc
x.append(v0*cos(radalpha0)*t)
y.append(v0*sin(radalpha0)*t-0.5*g*t*t)
xlabel('x')
ylabel('x')
plot(x,y)
title('Motion in two dimensions')
show()
I get this output
Traceback (most recent call last):
File "2d_motion.py", line 2, in <module>
from pylab import plot, xlabel, ylabel, title, show
File "/usr/lib64/python2.7/site-packages/pylab.py", line 1, in <module>
from matplotlib.pylab import *
File "/usr/lib64/python2.7/site-packages/matplotlib/__init__.py", line 151, in <module>
from matplotlib.rcsetup import (defaultParams,
File "/usr/lib64/python2.7/site-packages/matplotlib/rcsetup.py", line 19, in <module>
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
File "/usr/lib64/python2.7/site-packages/matplotlib/fontconfig_pattern.py", line 28, in <module>
from pyparsing import Literal, ZeroOrMore, \
File "/usr/lib/python2.7/site-packages/pyparsing.py", line 109, in <module>
alphas = string.lowercase + string.uppercase
AttributeError: 'module' object has no attribute 'lowercase'
Is there any problem with the syntax?
I'm using python2.7 on fedora18.
2020 addendum: Note string.lowercase was for Python 2 only.
In Python 3, use string.ascii_lowercase instead of string.lowercase
Python 3.6.8
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)] on darwin
>>> import string
>>> string.lowercase
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'string' has no attribute 'lowercase'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
After some discussion in the comments, it turned out (as it usually does when builtin modules suddenly seem to give AttributeErrors) that the problem was that another module named string was shadowing the builtin one.
One way to check this is to look at the __file__ attribute of the module, or just look at the repr itself:
>>> print string
<module 'string' from '/usr/lib/python2.7/string.pyc'>
if the from doesn't point to the right place, you've got the wrong module being read.
Solution: delete/rename the offending string.py/string.pyc files.
Let's say A is a package directory, B is a module within the directory, and X is a function or variable written in B. How can I import X using the __import__() syntax? Using scipy as an example:
What I want:
from scipy.constants.constants import yotta
What doesn't work:
>>> __import__("yotta", fromlist="scipy.constants.constants")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("yotta", fromlist=["scipy.constants.constants"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("yotta", fromlist=["scipy","constants","constants"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("scipy.constants.constants.yotta", fromlist=["scipy.constants.constats"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
Any suggestions would be much appreciated.
The python import statement performs two tasks: loading the module and makeing it available in the namespace.
import foo.bar.baz
will provide the name foo in the namespace, not baz, so __import__ will give you foo
foo = __import__('foo.bar.baz')
On the other hand
from foo.bar.baz import a, b
does not make a module available, but what the import statement needs to perform the assignmaents is baz. this corresponds to
_tmp_baz = __import__('foo.bar.baz', fromlist=['a', 'b'])
a = _tmp_baz.a
b = _tmp_baz.b
without making the temporary visible, of course.
the __import__ function does not enforce the presence of a and b, so when you want baz you can just give anything in the fromlist argument to put __import__ in the "from input" mode.
So the solution is the following. Assuming 'yotta' is given as a string variable, I have used getattr for attribute access.
yotta = getattr(__import__('scipy.constants.constants',
fromlist=['yotta']),
'yotta')
__import__("scipy.constants.constants", fromlist=["yotta"])
The argument fromlist is equivalent to the right hand side of from LHS import RHS.
From the docs:
__import__(name[, globals[, locals[, fromlist[, level]]]])
[...]
The fromlist gives the names of objects or submodules that should be imported from the module given by name.
[...]
On the other hand, the statement from spam.ham import eggs, sausage as saus results in
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage
(Emphasis mine.)
This question already has answers here:
Use 'import module' or 'from module import'?
(23 answers)
Closed 8 years ago.
I'm wondering if there's any difference between the code fragment
from urllib import request
and the fragment
import urllib.request
or if they are interchangeable. If they are interchangeable, which is the "standard"/"preferred" syntax (if there is one)?
It depends on how you want to access the import when you refer to it.
from urllib import request
# access request directly.
mine = request()
import urllib.request
# used as urllib.request
mine = urllib.request()
You can also alias things yourself when you import for simplicity or to avoid masking built ins:
from os import open as open_
# lets you use os.open without destroying the
# built in open() which returns file handles.
Many people have already explained about import vs from, so I want to try to explain a bit more under the hood, where the actual difference lies.
First of all, let me explain exactly what the basic import statements do.
import X
Imports the module X, and creates a reference to that module in the
current namespace. Then you need to define completed module path to
access a particular attribute or method from inside the module (e.g.:
X.name or X.attribute)
from X import *
Imports the module X, and creates references to all public objects
defined by that module in the current namespace (that is, everything
that doesn’t have a name starting with _) or whatever name
you mentioned.
Or, in other words, after you've run this statement, you can simply
use a plain (unqualified) name to refer to things defined in module X.
But X itself is not defined, so X.name doesn't work. And if name
was already defined, it is replaced by the new version. And if name in X is
changed to point to some other object, your module won’t notice.
This makes all names from the module available in the local namespace.
Now let's see what happens when we do import X.Y:
>>> import sys
>>> import os.path
Check sys.modules with name os and os.path:
>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
Check globals() and locals() namespace dict with name os and os.path:
>>> globals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> locals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> globals()['os.path']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'os.path'
>>>
From the above example, we found that only os is added to the local and global namespaces.
So, we should be able to use os:
>>> os
<module 'os' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> os.path
<module 'posixpath' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>
…but not path:
>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>
Once you delete the os from locals() namespace, you won't be able to access either os or os.path, even though they do exist in sys.modules:
>>> del locals()['os']
>>> os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> os.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
Now let's look at from.
from
>>> import sys
>>> from os import path
Check sys.modules with name os and os.path:
>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
So sys.modules looks the same as it did when we imported using import name.
Okay. Let's check what it the locals() and globals() namespace dicts look like:
>>> globals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> locals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['os']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'os'
>>>
You can access by using path, but not by os.path:
>>> path
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> os.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
Let's delete 'path' from locals():
>>> del locals()['path']
>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>
One final example using aliasing:
>>> from os import path as HELL_BOY
>>> locals()['HELL_BOY']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['HELL_BOY']
<module 'posixpath' from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>
And no path defined:
>>> globals()['path']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'path'
>>>
One pitfall about using from
When you import the same name from two different modules:
>>> import sys
>>> from os import stat
>>> locals()['stat']
<built-in function stat>
>>>
>>> stat
<built-in function stat>
Import stat from shutil again:
>>>
>>> from shutil import stat
>>> locals()['stat']
<module 'stat' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc'>
>>> stat
<module 'stat' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc'>
>>>
THE LAST IMPORT WILL WIN
There is a difference. In some cases, one of those will work and the other won't. Here is an example: say we have the following structure:
foo.py
mylib\
a.py
b.py
Now, I want to import b.py into a.py. And I want to import a.py to foo. How do I do this? Two statements, in a I write:
import b
In foo.py I write:
import mylib.a
Well, this will generate an ImportError when trying to run foo.py. The interpreter will complain about the import statement in a.py (import b) saying there is no module b. So how can one fix this? In such a situation, changing the import statement in a to import mylib.b
will not work since a and b are both in mylib. The solution here (or at least one solution) is to use absolute import:
from mylib import b
Source: Python: importing a module that imports a module
You are using Python3 were urllib in the package. Both forms are acceptable and no one form of import is preferred over the other. Sometimes when there are multiple package directories involved you may to use the former from x.y.z.a import s
In this particular case with urllib package, the second way import urllib.request and use of urllib.request is how standard library uniformly uses it.
In python 2.x at least you cannot do import urllib2.urlopen
You have to do from urllib2 import urlopen
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2.urlopen
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named urlopen
>>> import urllib.request
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named request
>>>
My main complaint with import urllib.request is that you can still reference urllib.parse even though it isn't imported.
>>> import urllib3.request
>>> urllib3.logging
<module 'logging' from '/usr/lib/python2.7/logging/__init__.pyc'>
Also request for me is under urllib3. Python 2.7.4 ubuntu
Suppose I do this
import cmath
del cmath
cmath.sqrt(-1)
I get this
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cmath' is not defined
But when I import cmath again, I am able to use sqrt again
import cmath
cmath.sqrt(-1)
1j
But when I do the following
import cmath
del cmath.sqrt
cmath.sqrt(-1)
I get this
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'sqrt'
Even when I import cmath again, I get the same error.
Is it possible to get cmath.sqrt back?
Thanks!
You'd need reload
reload(cmath)
... will reload definitions from the module.
import cmath
del cmath.sqrt
reload(cmath)
cmath.sqrt(-1)
... will correctly print ..
1j