Q:

How to convert numpy.int32 to decimal.Decimal

I'm using a library which use some decimal type args in a function call. But I have numpy.int32 type variable. When I pass it to the function call, I get following error:

TypeError: conversion from numpy.float32 to Decimal is not supported

Which means library try to convert my passed args to decimal.Decimal but failed. Please let me know, how I can convert my variables before passing to the library.
Thanks

A:

Decimal accepts native Python types.
numpyType.item() returns corresponding native type.
Here is an example:
import decimal
import numpy as np

# other library function
# will raise exception if passed argument is not Decimal
def library(decimal_arg):
    if type(decimal_arg) is not decimal.Decimal:
        raise TypeError('Not a decimal.Decimal')
    return decimal_arg

# wrapper with try block
def try_library(arg):
    try:
        print(library(arg))
    except TypeError as e:
        print(e)

def main():
    # we have some numpy types
    a = np.float32(1.1)
    b = np.int32(2)
    c = np.uint64(3000)

    # passing the numpy type does not work
    try_library(a)

    # Decimal's constructor doesn't know conversion from numpy types
    try:
        try_library(decimal.Decimal(a))
    except TypeError as e:
        print(e)

    # calling a.item() will return native Python type
    # constructor of Decimal accepts a native type
    # so it will work
    try_library(decimal.Decimal(a.item()))
    try_library(decimal.Decimal(b.item()))
    try_library(decimal.Decimal(c.item()))

main()
# output:

# Not a decimal.Decimal
# Cannot convert 1.1 to Decimal
# 1.10000002384185791015625
# 2
# 3000

