Backtick expressions work exactly like lambdas, except that they are bound to 
the instance they are created in every time that class is used to create one. 
To illustrate, this “percent” property is bound to the instance, not to the 
class.
class Example:
percent = property(`self.v*self.v2/100`)

And a few more examples for clarity.

def example():
locals()['a'] = 1
expr = `a+1`
return expr() # error: one variable is required

Any variable names that exist when the backtick expression is created are bound 
to the expression, and the reference to the expression is stored within the 
expression. Names that do not exist when the expresssion is created must be 
passed in as parameters. Such names can also be passed in as keyword arguments. 
Backtick expressions are created when their scope is created.

Variable names that are declared but have not been assigned to will be 
considered to exist for the purposes of the backtick expression.

Directly calling a backtick expression as soon as it’s created is forbidden:

`v+1`(a)

But this is technically allowed but discouraged, like how := works:
(`v+1`)(a)

Use Cases

This can be used anywhere a lambda would feel “heavy” or long. Here are a few 
use cases where using a backtick expression would allow code to be 
significantly mote readable:

If/else chains that would be switch statements.
Creating decorators.
Passing in logging hooks.
Writing design-by-contract contracts. (See icontract on GitHub for an example 
of what DBC looks like in Python.)
Tests and assertions.

Additionally, the instance binding enables:

A shorthand way to create a class that wraps an API to a better or more uniform 
code interface. Previously you’d need to make defs and @property, now each 
wrapped property and method is a single, readable line of code.

Appendix

I propose syntax highlighters show a backtick expression on a different 
background color, a lighter shade of black for a dark theme; dirty white for a 
light thing.

I also propose the following attributes on the backtick expression.

__str__(): the string [parameter names separated by commas] => [the string of 
the backtick expression]
__repr__(): the original string of the backtick expression, surrounded by 
backticks.

I secondarily propose that backtick expressions are only bound to their 
instances when defined within a class when the following syntax is used:

def a = <expression>

—
Now, let’s bikeshed.
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to