user3909208
user3909208

Reputation: 71

How does Python language know about the type of identifiers?

I recently faced this question..

How does python identifies the type of an identifier?

For example

a=5
b=6
c=a+b

the value of c is 11

Where as

x="hello"
y="world"
z=x+y

the value of z is "helloworld"

How does Python distinguishes these two cases?

Upvotes: 1

Views: 80

Answers (3)

cgsdfc
cgsdfc

Reputation: 630

The python interpreter does not identify the types of identifier. Rather, it identifies the types of the objects referred to by the identifiers. The identifiers or names you declare does not hold the objects but rather refer to the objects and these objects, as pointed out by the previous answers, holds type information about themselves. These python objects are implemented as PyObject structure in C, which has a field PyObject *ob_type pointing to their types (being PyObject as well).

With the background above, now here is what happens when python runs your script.

  1. i = 1: it creates an object for the numeric 1 from the int type.
  2. A name i is bound to the int object created just now. By "bound to" I means inserting an entry into the global dictionary (you can see it by globals()).
  3. Whatever operations you perform on i is forwarded to the object it refers to (being int(1) currently) as @valjeanval42 has explained.

Since the objects always know their types, which are the main source of information about what operations they support, python can correctly handle the i variable not whether it is assigned to 1 or '1' (being a str).

Static language like C++ or Java do things vastly differently than a dynamic language like python, as you would have expected. In short, they manage matter of types at compile time while python does it at run time.

Upvotes: 0

haael
haael

Reputation: 1057

In Python, types are not associated with variable names, but with values. The name 'a' does not hold any type information, it's the value '1' that holds that information (namely that it's an 'int' class).

This is a contract to C and Java, where types are associated with variable names.

This is exactly the difference between the Curry-style typing system and Church-style system.

http://en.wikipedia.org/wiki/Simply_typed_lambda_calculus#Intrinsic_vs._extrinsic_interpretations

C and Java use Church typing (variable name has a type) while Python and JavaScript use Curry typing (value has a type).

Upvotes: 1

valjeanval42
valjeanval42

Reputation: 132

Check the __add__ method for classes.

What really happens is that the __add__ method of the object is called:

a + b is really a.__add__(b)

Check also diveintopython for special method names.

From the doc:

The int type implements the numbers.Integral abstract base class.

Likewise, strings are instances of the str class.

Upvotes: 0

Related Questions