code blocks

Ben Bacarisse ben.usenet at bsb.me.uk
Sun May 3 06:56:42 EDT 2015


"Dr. John Q. Hacker" <zondervanz at gmail.com> writes:

> I'm thinking how interesting it would be to add code blocks to Python,
> so that arbitrary strings of code can be passed around. It would open
> up some interesting possibilities for self-modifying code and generic
> programming.
>
> Since Python has already a plethora of ambiguous string designations,
> one of them could be set aside specificially for code blocks:
>
> """for i in n: print i"""
>
> For any variables, like "n", it would access the scope in which it was
> running. When you tried to print a triple-double-quoted code block,
> perhaps it could invoke the code.
>
> My suggestion would be to use triple double-quoted strings. 
>
> You probably already know that Ruby has code blocks.

What Ruby calls code blocks, Python calls lambdas:

  Ruby:  [1,2,3].map { |x| x*x }
  Python: map(lambda x: x*x, [1,2,3])

In some cases, the lambda is implicit.  For example, the above can be
written as

  [x*x for x in [1,2,3]]

You can use strings (if you really must), using eval() at the
appropriate place eval() but that opens up all sorts of cans of worms.

-- 
Ben.



More information about the Python-list mailing list