All possible types of a variable in python

262 Views Asked by At

How can we know all possible type of a variable? Consider the following example,

n = int(raw_input())

if n<50:
        a = 5
elif n<100:
         a = 6.8
else:
         a = 'abc'

print type(a)

But, It will give output as either 'int' or 'float' or 'str', depending on value of n...

Can't we have all possible types of a variable? For example the above should give an output something like :

{int,float,str}

4

There are 4 best solutions below

0
On

Can't we have all possible types of a variable?

No, because variables in Python don't have type; values do.

When you write type(a), you're not checking the type of a variable named a; you're checking the type of a thing that the name a refers to (which might happen to have other names as well).

0
On

You can't determine this at runtime since the type of the variable depends on the execution path. As far as I know, there is no static analysis tool that can do this either.

0
On

You would have to enumerate all types known to the Python interpreter. I guess that would be possible but it would be essentially meaningless since there are so many types.

Python is a dynamically typed language and as such it does not have variables in the same sense as statically typed languages like C. In your snippet, a is simply a name which is bound to an object. That object could be of any type known to the Python interpreter.

There is a fundamental difference in mindset when programming in a dynamically typed language and asking questions like, what type is this object? should be avoided. Instead it is preferable to ask questions of the form, what operations does this object support? This approach to programming is known as duck typing.

0
On

I think that the bottom line here should be that variables in python don't have any type at all. Variables are just tags that reference to the object they have been assigned to. What really holds the type is the object itself.

In addition to this, given that any kind of object can be assigned to a variable, the amount of possible types for objects being referenced by a variable is the same as the amount of possible types you can create in the language which should be almost an unbound number depending on hardware contrains.