pytoolz / pytoolz/toolz

A shortcut to create Lambdas?

Open
#461 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.2k
Forks
280
Avg merge
6d 17h
Merged PRs (30d)
4

Description

Hey, I love toolz, but the one thin I've been missing is a possibility to create lambdas in a less verbose way.
At some point I had installed a library (which I can't seem to find anymore) that created lambdas through the use of _. Eg _ == x was translated to: lambda x: x == 3 but it had it's limits as something like len(_) would not work.

I wrote a function that takes a string, replaces percent signs by arguments and evals it:

import re

def _f_single_arg(function):
    body = (function.replace('%%', '<!>')
                    .replace('%', '_0')
                    .replace('<!>', '%'))
    return eval('lambda _0: ' + body)

def f(function):
    """Translates the provided expression in string form into a lambda. 
    Any %<n> where <n> is a int will be used as nth
    argument (starting with 0). If only one argument is required,
    a % can be used. To escape a % sign use %%."""
    single_percent_match = re.search(r"%[^\d]|%$", function)
    if single_percent_match:
        return _f_single_arg(function)
    
    matches = re.findall(r"%(?P<n>\d+)", function)
    n_args = 0 if len(matches) == 0 else\
        max(int(match) for match in matches) + 1
    replace_tuples = [(f'%{n}', f'_{n}') for n in range(n_args)]
    new_body = function
    # Not very functional, but since this is python
    # I think it's pragmatic
    for tup in replace_tuples:
        new_body = new_body.replace(*tup)
    head = 'lambda ' + ', '.join(pluck(1, replace_tuples)) + ': ' \
        if n_args > 0 else 'lambda *_0: '
    return eval(head + new_body)

Trying it out:

>>> f("%1")(0, "Hey")
"Hey"

>>> f('%')('Hey')
"Hey"

>>> f('"Hey"')(0, 1, 2)
"Hey"

I found this would fit one of my favorite libraries perfectly, what do you think about this?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No target files or tests are named. Start by reviewing the proposed string-to-lambda behavior in issue #461, including its percent-argument examples and eval-based implementation, then confirm the feature scope and safety expectations with maintainers; done means an agreed design and tests for the documented examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.