Why does this (not) work?

Amit Patel amitp at theory.stanford.edu
Wed Aug 20 01:34:17 CEST 2003


"Michael C. Neel" <neel at mediapulse.com> writes:

> > try this:
> > >>> "%s - %s - %s" % (("test",)*3)
> > 
> > why else would
> > >>> 3 % 1 * 2
> > print 0 instead of 1?
> > 
> > Jeff
> 
> Hmmm, can't say I like what this implies.  In one case % is shorthand
> for a sprintf function, the other it's a mathematical expression at the
> same level of precedence of * and /.  But the sprintf version is
> "granted" the precedence of the mathematical version?  What's the logic
> behind that? 

I think the logic behind that is that the operator precedence is
assigned before we know what the types of the operands are.  You could
argue that since we can see it's a string, we should change the
precedence.  But then we'd get weird situations like 

  print "..." % (x,)*3

not being the same as

  s = "..."
  print s % (x,)*3

You could argue that a flow analyzer could figure out that s is a
string, etc., but that's going down a dangerous path -- the semantics
start depending on how sophisticated your Python compiler is.  Aieee! :)

Some of the 'cute' syntax features of Python (% for strings, `` for
repr) have bitten me more than once.  :(

- Amit

-- 
Amit J Patel, Computer Science Department, Stanford University 
        http://www-cs-students.stanford.edu/~amitp/
	``Parkinson's Other Law:  Perfection is achieved only
				  at the point of collapse.''




More information about the Python-list mailing list