Time we switched to unicode? (was Explanation of this Python language feature?)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Mar 25 20:12:46 EDT 2014


On Tue, 25 Mar 2014 19:55:39 -0400, Terry Reedy wrote:

> On 3/25/2014 11:18 AM, Steven D'Aprano wrote:
> 
>> The thing is, we can't just create a ∑ function, because it doesn't
>> work the way the summation operator works. The problem is that we would
>> want syntactic support, so we could write something like this:
>>
>>      p = 2
>>      ∑(n, 1, 10, n**p)
> 
> Of course we can. If we do not insist on separating the dummy name from
> the expression that contains it. this works.
> 
> def sigma(low, high, func):
>      sum = 0
>      for i in range(low, high+1):
>          sum += func(i)
>      return sum

There is no expression there. There is a function.

You cannot pass an expression to a function in Python, not in the sense I 
am talking about, because expressions are not first-class objects. When 
you pass:

sigma(1, 10, n**p)

the n**p gets evaluated immediately. Only with support of the compiler 
does evaluation of the expression get delayed, e.g.:

it = (n**p for n in range(1, 11))
result = (-100)**p if isinstance(p, int) else float('nan')
first = items and items[0]

If we tried to write an "and" function like this:

def and_(a, b):
    if a: return a
    return b


it wouldn't work the same as the `and` operator, because the `and` 
operator is lazy and only evaluates the right hand operator when needed, 
whereas the function call is greedy and evaluates the right hand operator 
up front, whether it is needed or not.

Passing a *function* is not the same as writing an expression. It is a 
work-around for lack of first-class expressions. Now perhaps it is an 
acceptable work-around, for some purposes at least. But if you want to 
match mathematical syntax, it's not enough.


-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list