Two syntax questions (newbie)

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Apr 23 04:55:10 EDT 2007


En Mon, 23 Apr 2007 05:15:26 -0300, Szabolcs <szhorvat at gmail.com> escribió:

> Mathematica allows writing
> result = processData at Reverse@Sort at data
> or even
> result = data//Sort//Reverse//processData
> instead of
> result = processData[Reverse[Sort[data]]]
>
> In Python this would be something like
> result = processData(list(reversed(sorted(data))))
>
> The first two Mma alternatives are both easier to read (especially
> when part of a bigger expression) and easier to type (an re-type, if
> working interactively) because I don't have to jump with the cursor to
> the beginning and end of the expression to insert the brackets when
> adding another function call.
>
> Is there a way to avoid typing all the parentheses in Python? Is it
> possible to define a different syntax for function calls

Not a different syntax.

> or define a
> function composition operator for functions that take a single
> argument?

You could use this:

def chain(*args):
   """Compose functions (assoc right).
   last argument (args[-1]): argument to last function
   args[0] .. args[-2]: functions taking a single argument
   Returns args[0](args[1](...(args[-2]))(args[-1])
   """
   args = list(args)
   data = args.pop(-1)
   while args:
     fn = args.pop(-1)
     data = fn(data)
   return data

import random
items = [random.randrange(100) for _ in range(20)]
print chain(list, reversed, sorted, items)


> Of course Python is not Mathematica and not as friendly with this
> style as Mma is. Sometimes it forces me to use some temporary
> variables (e.g. because lines get too long and breaking lines with a
> backslash is ugly).

I almost never use backslashes for line continuation. If you have an open  
(,[,{ continuation is implicit. If not, usually adding a heading ( is  
enough.
That is, instead of

x = a + b + \
     c - d

I'd use:

x = (a + b +
      c - d)

> I like to get rid of these variables as soon as
> they aren't needed, e.g.:
>
> temp = data[:]
> temp.sort()
> temp.reverse()
> result = processData(temp)
> del temp
>
> Is it possible to avoid the explicit del temp? In C/C++ I would simply
> enclose the piece of code in curly brackets. Is it possible to somehow
> separate a block of code from the rest of the program and make
> variables local to it?

Python does not have block scope; use a function instead. (It's hard to  
define block scopes without variable declarations). Anyway that would make  
any difference if you are using huge structures.

-- 
Gabriel Genellina



More information about the Python-list mailing list