M. Kostas M. Kostas - 1 year ago 85
Python Question

Initialize variable depending on another variables type

In Python 2.7 I want to intialize a variables type depending on another variable.

For example I want to do something like:

var_1 = type(var_2)

Is there a simple/fast way to do that?

Answer Source

Just create another instance

var_1 = type(var_2)()

Note that if you're not sure whether the object has a non-default constructor, you cannot rely on the above, but you can use copy (you get a "non-empty" object.

import copy
var_1 = copy.copy(var_2)

You could use both combined with the latter as a fallback mechanism

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download