[Python-ideas] Backtick expression: similar to a shorter lambda syntax

James Lu jamtlu at gmail.com
Tue Jan 22 08:43:16 EST 2019

I’m a little busy recently, so I’ll reply to as much as I can now and reply to the rest later.

Scratch the stuff I said about scope. Backtick expressions should inherit the scope normally like any other nested function.

> That's different behaviour from regular functions, where names are only 
> resolved when the function is called.

What benefits are there to the late name lookup of normal functions? I’m looking to have backtick expressions raise early, not late. 

We can relax the names to be optional if a ternary expression is used within the backtick expression.

I realized that the behavior of Backtick Expressions can be silently affected by global variables. Example:

x = 1 
def increment_each(l):
 return map(`x+1`, l)

## Explicit expression, implicit usage
Explicit backtick expressions are ones that, for all parameters that the created function produces, it uses a caret before the name of the parameter. The other names must exist when the backtick expression is evaluated. Example:

parameter = 0
is_integer = `int(^parameter) == ^parameter` # arity: 1 despite the global definition

self = 'James'
str = `^self.__class__.__str__(^self)` # arity: 1 despite the global definition
str(type(lambda: 1)) # use our custom str function on the function type; output: <type 'function' at 0x84910>

## Implicitly Created Backtick Expression
Implicit baktick expressions, ones that mention undefined parameters without using the caret mark are generally discouraged. However they create UncastBacktickExpression, which must be cast using the .to_safe(*names) method to be used, which takes in a list of parameter names and outputs a normal backtick expression.

Even if the variable is defined on a global level, it can be explicitly overridden in to_safe.

Example 1
`x+1`.to_safe('x')(1)  # output: 2

Example 2
x = 0
`x+1`.to_safe('x')(1)  # output: 2

If a backtick expression has no unspecified names and has no carets, it is an implicit backtick expression.

This allows developers to safely omit the ^ when the code that is using the resulting backtick expression is aware of the parameters to be used, given that it's obvious to the developer which names are parameters.

> On Jan 21, 2019, at 1:56 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> That's different behaviour from regular functions, where names are only 
> resolved when the function is called.

More information about the Python-ideas mailing list