[Python-Dev] python -O weirdness

Guido van Rossum guido@python.org
Thu, 06 Apr 2000 22:23:11 -0400


> Strange. Can somebody confirm/refute, explain this behavior?
> 
> -------------[ bug.py ]------------
> def f():
> 	pass
> 
> def g():
> 	a = 1
> 	b = 2
> 
> def h(): pass
> 
> def show(func):
> 	c = func.func_code
> 	print "(%d) %s: %d -> %s" % \
> 		(c.co_firstlineno, c.co_name, len(c.co_lnotab), repr(c.co_lnotab))
> 
> show(f)
> show(g)
> show(h)
> -----------------------------------
> 
> ~> python bug.py
> (1) f: 2 -> '\003\001'
> (4) g: 4 -> '\003\001\011\001'
> (8) h: 2 -> '\003\000'
> 
> ~> python -O bug.py
> (1) f: 2 -> '\000\001'
> (4) g: 4 -> '\000\001\006\001'
> (1) f: 2 -> '\000\001'                   <=== ???
> 
> -- 

Yes.  I can confirm and explain it.

The functions f and h are sufficiently similar that their code objects
actually compare equal.  A little-known optimization is that two
constants in a const array that compare equal (and have the same
type!) are replaced by a single copy.  This happens in the module's
code object: f's and h's code are the same, so only one copy is kept.

The function name is not taken into account for the comparison.  Maybe
it should?  On the other hand, the name is a pretty inessential part
of the function, and it's not going to change the semantics of the
program...

--Guido van Rossum (home page: http://www.python.org/~guido/)