3

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?

2
  • How many different types are we talking about? isinstance() is usually a better solution than type() (usually, not always). Commented Oct 13, 2016 at 7:12
  • Working on a function that takes an iterable object as argument and defines a variable of the same type Commented Oct 13, 2016 at 7:14

2 Answers 2

4

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 or deepcopy (you get a "non-empty" object.

import copy
var_1 = copy.copy(var_2)  # or copy.deepcopy

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

Note: deepcopy will ensure that your second object is completely independent from the first (If there are lists of lists, for instance)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! One more question regarding the copy library. By reading the docs it seems like copy.deepcopy() is more suitable for this purpose, or am I wrong?
2
a = 1              # a is an int
a_type = type(a)   # a_type now contains the int-type
b = '1'            # '1' is a string
c = a_type(b)      # c is now an int with the value 1

So you can get the type of a variable using type(). You can then store this type in a variable and you can then use that variable just like you would use int(b), str(b), float(b) etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.