syntax for code blocks

Kiuhnm kiuhnm03.4t.yahoo.it
Sat Apr 28 06:34:50 EDT 2012


On 4/27/2012 18:07, Steven D'Aprano wrote:
> On Fri, 27 Apr 2012 17:03:19 +0200, Kiuhnm wrote:
> 
>> On 4/27/2012 16:09, Steven D'Aprano wrote:
>>> On Fri, 27 Apr 2012 13:24:35 +0200, Kiuhnm wrote:
>>>
>>>> I'd like to change the syntax of my module 'codeblocks' to make it
>>>> more pythonic.
>>>>
>>>> Current Syntax:
>>>>
>>>>        with res<<  func(arg1)<<  'x, y':
>>>>            print(x, y)
>>>>
>>>>        with res<<  func(arg1)<<  block_name<<  'x, y':
>>>>            print(x, y)
>>>
>>>
>>> I'm sorry, I don't see how this is a code block. Where is the code in
>>> the block, and how can you pass it to another object to execute it?
>>
>> Maybe if you read the entire post...
> 
> No, I read the entire post. It made no sense to me. Let me give one
> example. You state:
> 
>      The full form is equivalent to
>           def anon_func(x, y):
>               print(x, y)
>           res = func(arg1, block_name = anon_func)
> 
> but this doesn't mean anything to me. What's func? Where does it come
> from? What's arg1? Why does something called block_NAME have a default
> value of a function instead of a NAME?
> 
> How about you give an actual working example of what you mean by a code
> block and how you use it?

The rewriting rules are the following, where X ---> Y means that X is rewritten as Y on the fly:

1)
  with res << func(args) << 'x, y':
      <code>

  --->

  def anon_func(x, y):
      <code>
  res = func(args, anon_func)

2)
  with res << func(args) << block_name << 'x, y':
      <code>

  --->

  def anon_func(x, y):
      <code>
  res = func(args, block_name = anon_func)

That's all.
func is some function which takes a function as a positional argument or as a keyword parameter neamed block_name.

Some examples:

1)
  text = "Anyone should be able to read this message!"
  with ris << re.sub(r'(\w)(\w+)(\w)', string = text) << repl << 'm':
      inner_word = list(m.group(2))
      random.shuffle(inner_word)
      _return (m.group(1) + "".join(inner_word) + m.group(3))
  print(ris)

which prints (something like):

  Aynnoe shluod be albe to read tihs msgseae!

2)
  numbers = [random.randint(1, 100) for i in range(30)]

  with sorted1 << sorted(numbers) << key << 'x':
      if x <= 50:
          _return(-x)
      else:
          _return(x)

  print(sorted1)

which prints (something like):
  [50, 47, 46, 28, 28, 25, 24, 23, 21, 19, 16, 15, 14, 3, 52, 52, 53, 54, 58, 62,
63, 69, 70, 72, 74, 78, 84, 86, 90, 97]

Kiuhnm



More information about the Python-list mailing list