Bharath K
Bharath K

Reputation: 2119

Generic Type conversion in Python

How can I perform a generic type conversion in python similar to the following mechanism that I use in C# .NET:

string typetoConvertTo = "System.String";
string value = (string)Convert.ChangeType( "1", Type.GetType( typetoConvertTo ));

typetoConvertTo = "System.Int32";
int value1 = (int)Convert.ChangeType( "1", Type.GetType(typetoConvertTo));

Python has type conversion for individual types, but I need something more generic like the above method in .NET since I am storing the type and need to perform a generic conversion later.

value = str(100)
value1 = int("100")

Upvotes: 3

Views: 5367

Answers (4)

Zoltán Fekete
Zoltán Fekete

Reputation: 604

I was just looking to solve the same problem, then I tried this, and it works. If you still didn't find the solution, this just worked for me:

from typing import TypeVar, Type

T = TypeVar("T")

def my_method(input, cast_type: Type[T]) -> T:
    print(type(input))
    print(input)

    casted_value = cast_type(input)

    print(type(casted_value))
    print(casted_value)

    return casted_value

my_method(12)

This prints me out the following:

<class 'int'>
12
<class 'float'>
12.0

Upvotes: 0

Lucas
Lucas

Reputation: 2709

You don't need a type-mapping dict and can instead use eval, but that's almost like cheating:

>>> t = "int"
>>> v = "3"
>>> eval(t)(v)
3

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

Classes are first-class objects in Python.

>>> t = str
>>> t(123)
'123'
>>> d = {'str': str}
>>> d['str'](123)
'123'

Upvotes: 6

gfortune
gfortune

Reputation: 2629

If you're wanting to delay type conversions for some reason, just store the value and the type conversion as a pair.

>>> entry = (int, '123')
>>> entry[0](entry[1])
123

If you had a whole batch of them to do, you could have something like

conversions_to_do = {}
conversions_to_do[int] = []
conversions_to_do[str] = []
conversions_to_do[int].append('123')
conversions_to_do[int].append('456')
conversions_to_do[str].append(1.86)

Unwrapping it is similar to the first example.

I have to ask though, why not just convert it directly? There may be a simpler and more straightforward way to tackle the actual problem you're trying to solve.

Upvotes: 1

Related Questions