7

I am unable to import decimal in the terminal for Python 2.7 or 3.3.

Here are the errors I get:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/decimal.py", line 3849, in <module>
    _numbers.Number.register(Decimal)
AttributeError: 'module' object has no attribute 'Number'

or Python 2.7

Python 2.7.2 (default, Oct 11 2012, 20:14:37) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 141, in <module>
    import numbers as _numbers
  File "numbers.py", line 34, in <module>
    assert x / y == 2.5 # true division of x by y
AssertionError

How to I import decimal?

falsetru
  • 357,413
  • 63
  • 732
  • 636
ubersquared
  • 73
  • 1
  • 4
  • for any future readers, a more comprehensive solution can be found at [Importing installed package from script raises “AttributeError: module has no attribute” or “ImportError: cannot import name”](http://stackoverflow.com/questions/36250353/importing-installed-package-from-script-raises-attributeerror-module-has-no-at) – Tadhg McDonald-Jensen Oct 31 '16 at 00:27

3 Answers3

13

Is there numbers.py in current working directory?

That could be the reason of the problem, because that prevent import of standard library module numbers.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    It's amazing how obvious the right answer is to people who actually know what the heck they're talking about! You nailed it, I had named a file numbers.py and gotten rid of it while debugging this but there was still a numbers.pyc file that I ignored. Thank you! – ubersquared Aug 04 '13 at 17:28
5

How to import decimal in Python3:

from decimal import Decimal
a = Decimal(25)
print(type(a))

//prints <class 'decimal.Decimal'>
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
0

I know I'm late to the game, I ran into this issue too until I realized what I did wrong.

If you have named one your own files "decimal.py", your project will have two modules with the same name "decimal", which would confuse your IDE.

Change the name of your file and try again.

Lavande
  • 744
  • 8
  • 20