16

Is there some way I could make decimal.Decimal the default type for all numerical values in Python? I would like to be able to use Python in a manner similar to the bc and dc programs without having to call decimal.Decimal(...) for every number.

EDIT: For the uninitiated: bc.

EDIT 2: Thank you tokenize module..

Eric Pruitt
  • 1,825
  • 3
  • 21
  • 34
  • Are you talking about ensuring the python does floating point arithmetic instead of integer arithmetic? – seggy Jan 18 '11 at 17:26
  • Perhaps you could hack the interpreter to do this, with a lot of effort. But why? When you write a Python program that needs decimal in some place, just use it there - way easier. If you need abritary precision decimals, use something that provides it. (And @seggy: float != decimal !!) –  Jan 18 '11 at 17:29
  • Yeah, I realized that after I posted. You're right, there doesn't seem to be a way that doesn't involve some serious mucking with python internals. Way more effort than the payoff would be worth, IMO. – seggy Jan 18 '11 at 17:31
  • I will probably end up using the module that allows you to make your own interpreter. See [code module.](http://docs.python.org/library/code.html) – Eric Pruitt Jan 18 '11 at 17:36
  • 3
    Where does the "numerical input" comes from in your program? It would probably be easier to force a conversion there rather than making your own interpreter... – unode Jan 18 '11 at 17:40
  • The numerical input comes from me. I want to be able to use Python like bc and dc which are arbitrary precision calculators that support a scripting language. – Eric Pruitt Jan 19 '11 at 00:10

2 Answers2

8

At the bottom of the tokenize module's documentation, there is a function that does exactly what I need:

Eric Pruitt
  • 1,825
  • 3
  • 21
  • 34
6

You cannot really do what you ask without some serious magic, which I won't try to touch upon in my answer, but there is at least a slightly easier way than doing decimal.Decimal(...)

from decimal import Decimal as D
num = D("1") + D("2.3")

Edit: use the shorter form from the comment.

porgarmingduod
  • 7,668
  • 10
  • 50
  • 83
  • 1
    Well yes, I _could_ do it that way, but I was looking for something that didn't require explicit action for every number. – Eric Pruitt Jan 18 '11 at 17:32
  • 2
    Also, It'd be more like `D("2.3")` so I don't lose precision. – Eric Pruitt Jan 18 '11 at 17:35
  • 10
    The problem is that Python is a generic programming language, and is notable for not wanting magic stuff to happen. As the python saying goes: "Explicit is better than implicit." Which is why any answer you get to this question that does exactly what you want will be hackish. – porgarmingduod Jan 18 '11 at 17:40