tags:

views:

82

answers:

2

I'm using Python 2.5.4 and trying to use the decimal module. When I use it in the interpreter, I don't have a problem. For example, this works:

>>> from decimal import *

>>> Decimal('1.2')+ Decimal('2.3')
Decimal("3.5")

But, when I put the following code:

from decimal import *
print Decimal('1.2')+Decimal('2.3')

in a separate file and run it as a module, the interpreter complains:

NameError: name 'Decimal' is not defined

I also tried putting this code in a separate file:

import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3') 

When I run it as a module, the interpreter says

AttributeError: 'module' object has no attribute 'Decimal'

What's going on?

+2  A: 

This works fine as is for me on Python 2.5.2

from decimal import *
print Decimal('1.2')+Decimal('2.3')

I would encourage you to specify what you want to use from decimal

from decimal import Decimal
print Decimal('1.2')+Decimal('2.3')

In your other example you should use

import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3') 
gnibbler
Thanks for pointing out my typo. I ran: import decimalprint decimal.Decimal('1.2')+decimal.Decimal('2.3')and still got the error of AttributeError: 'module' object has no attribute 'Decimal'
jack
I've edited my post that originally read "import decimalprint decimal.Decimal('1.2')+Decimal('2.3')" to now read:"import decimalprint decimal.Decimal('1.2')+decimal.Decimal('2.3')"
jack
+7  A: 

You named your script decimal.py, as the directory the script is in is the first in the path the modules are looked up your script is found and imported. You don't have anything named Decimal in your module which causes this exception to be raised.

To solve this problem simply rename the script, as long as you are just playing around something like foo.py, bar.py, baz.py, spam.py or eggs.py is a good choice for a name.

DasIch
+1 Although the OP hasn't answered yet, my money is on this too. This is an issue that happens too often.
ΤΖΩΤΖΙΟΥ
Thank you gnibbler and Daslch.
jack