write a loopin one line; process file paths

bonono at gmail.com bonono at gmail.com
Wed Oct 19 01:54:30 EDT 2005


it will be added in 2.5 I beleve. At the moment, you can:

predicate and <true expression> or <false expression>

like :
>>> os.paths.exists(something) and "print it is there" or "file not found"

I am practicing FP in python and it is in general doable with the help
of itertools and add the needed functions as needed, like scanl/scanl1
etc.

A few things I don't like about python for FP is that it relies heavily
on exception which make these one liners not possible in many case.

Example:

a=[]
a[0] would raise exception

I usually prefer None as a special value which can be handled in normal
flow(filter out, may be "x is None and something or otherthing"). But
the liberal use of Exception force you to structure the program either
in a very odd way(test with hasattr/haskey etc. before use) or needs
lots of try/except blocks. I am using a python XHTML template Kid which
relies on one-liner and found it very difficult.

However, if you don't really need one-liner but just FP style to
shorten the program, it is fine but I just find the try/except block
quite ugly.

Then there is the side effect of iterators/generators which unless you
know can burn you badly(especially when you are chaining these objects
in these multiple map/filter calls), as mentioned in another post.

Xah Lee wrote:
> Thanks. Here's how the inner loop should be:
>
> imgPaths2=map(lambda x: (x, re.sub( r"^(.+?)-s(\.[^.]+)$",r"\1\2", x)),
> imgPaths)
>
> though, now i just need something like
>
> map( lambda x: os.path.exists(s)? x[1]:x[0],impPaths2)
>
> but Pyhton doesn't support the
> test ? trueResult : falseResult
> construct.
>
> (the semantic of this construct, of a conditional that RETURNS A
> EXPRESSION, all in one line, is important in functional programing.
> Perl supports it. In Mathematica, it's simply the form If[testExpr,
> trueExpr, falseExpr]. In lisp, similar: (if testExpr trueExpr
> falseExpr) )
>
> is there a way to similate it?
>
>  Xah
>  xah at xahlee.org
>http://xahlee.org/
>
> bonono at gmail.com wrote:
> > what do you mean by one line ? Using map/filter, I believe it is
> > possible.
> >
> > Somthing like:
> >
> > map(lambda (s,f): os.path.exists(f) and f or s,
> >     map(lambda x: (x, re.replace(x, "-s","")), imgPaths)
> >
> > My regex is a bit rusty but I hope you got the idea of what I am trying
> > to do. If there is a way to make the re return without destroying x,
> > the outer map is not needed I believe(that is run it twice, once for
> > getting the filename to do the testing, then again based on the testing
> > result).
> >




More information about the Python-list mailing list