I would like to know if it is possible in Python to "extract" the constructor type (metaclass?) from a variable in order to use it to type-cast another variable to the same type, programatically, without having to have any "prior expectation" regarding the types we can encounter.
If it is more meaningful that way, the implementation would be something in the realm of:
def copyType(destination_var,source_var):
try:
type_class = way_to_get_the_type_metaclass(source_var)
return typeclass(destination_var)
# as if we did str(destination_var) or int(destination_var) or
# any other class, but without having to have expectation and being forced to check
# if isinstance(var, str) : elif isinstance(var,int) : .... and so on
except :
raise TypeError
variable1 = "157"
variable2 = 34
print(type(variable1))
print(type(variable2))
variable2 = copyType(variable2 ,variable1)
print(type(variable2))
>>> Out : <str>
<int>
<str>
As answered by tobias and Alex Waygood in the comments, the solution is as simple as:
type(variable1)(variable2)
or
variable1.__class__(variable2)