Non-idempotent Python
def method():
if 'a' not in vars():a=0
a+=1
if 'a' not in vars():a=0
a+=1
print(a)
Initializes the variable a
to 0
only if it's not already initialized in the variables table. Then, increments it.
More briefly (thanks to histocrat for len
):
def method():
a=len(vars())+1
a=len(vars())+1
print(a)
If the two copies of X
could be on the same line, we could do
a=0;a+=1;a
which doubles to
a=0;a+=1;aa=0;a+=1;a
with the "sacrificial lamb" aa
eating up the second variable assignment.
Python
Thought of this solution, since try
and except
was the first way I thought of to determine if a variable existed yet or not.
def method():
try:a+=1
except:a=1
print(a)
Python 2
def method():
exec'';locals()['a']=locals().get('a',0)+1
exec'';locals()['a']=locals().get('a',0)+1
print a
method()
Basically, when exec
is encountered in Python 2, it causes a special flag (0x01
) to be removed from method.func_code.co_flags
, which makes locals
assignments have an effect. I exploited this to implement nonlocal
support in Python 2 (see line 43 for the xor that modifies the flag).