braintree / braintree_python

Braintree Python library
https://developer.paypal.com/braintree/docs/start/overview
MIT License
242 stars 115 forks source link

Create transaction error - RuntimeError: Unexpected XML node type: <class 'float'> #84

Closed ittus closed 7 years ago

ittus commented 7 years ago

Description:

I created a transaction with following code:

braintree.Transaction.sale({
            "amount": 9.9,
            "payment_method_token": payment_method_token,
            "options": {
                "submit_for_settlement": True
            }
        }
)

or

from decimal import Decimal
braintree.Transaction.sale({
            "amount": Decimal(9.9),
            "payment_method_token": payment_method_token,
            "options": {
                "submit_for_settlement": True
            }
        }
)

and got error:

../python3.4/site-packages/braintree/util/generator.py", line 70, in __generate_node
    raise RuntimeError("Unexpected XML node type: " + str(type(value)))
RuntimeError: Unexpected XML node type: <class 'float'>

If I do

braintree.Transaction.sale({
            "amount": str(9.9), # convert to string
            "payment_method_token": payment_method_token,
            "options": {
                "submit_for_settlement": True
            }
        }
)

or

braintree.Transaction.sale({
            "amount": 9, # integer value
            "payment_method_token": payment_method_token,
            "options": {
                "submit_for_settlement": True
            }
        }
)

then it's ok.

Why doesn't braintree/util/generator.py check for float type?

Enviroment: braintree==3.35.0 python3.4

EvanHahn commented 7 years ago

The main reason comes from a lack of precision. 1.1 + 2.2 in Python is 3.3000000000000003. Floating point imprecision may be acceptable in some cases, but not with money. That's the biggest reason why we don't support them.

In any case, the amount property is only documented as a string or a Decimal, so we'd recommend sticking to those. It happens to be "smart" enough to convert ints, but that's undocumented and therefore unsupported.

EvanHahn commented 7 years ago

We're going to close this issue. Feel free to open a new issue if you run into other problems!