Why doesn’t Python have a “with” statement for attribute assignments?


Python definitely has a with statement. It wraps the execution of a block, calling code on the entrance and exit from the block. Some languages have a construct like the below −

with obj: a = 1 total = total + 1

The above a = 1 is equivalent to the following 

obj.a = 1

And, total = total + 1 is equivalent to 

obj.total = obj.total + 1

Programming Languages use static or dynamic types.

Static Type

Static refers to the execution of a program where type of object is determined/known at compile time i.e. when compiler executes the code it knows the type of object or class to which object belongs.

Programming languages, like Object Pascal, Delphi, and C++, use static types, so it’s possible to know, in an unambiguous way, what member is being assigned to. This is the main point of static typing – the compiler always knows the scope of every variable at compile time.

Dynamic Type

In Dynamic, the type of object is determined at runtime. Python uses dynamic types. It is impossible to know in advance which attribute will be referenced at runtime.

Let’s see an example −

def demo(x): with k: print(x)

The snippet assumes that k must have a member attribute called x. However, there is nothing in Python that tells the interpreter this.

The key benefit of with can easily be achieved in Python by assignment −

function(args).mydict[index][index].k = 21 function(args).mydict[index][index].l = 42 function(args).mydict[index][index].m = 63

The above can also be achieved with −

ref = function(args).mydict[index][index] ref.k = 21 ref.l = 42 ref.m = 63

Updated on: 20-Sep-2022

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements