[Python-ideas] Backtick expression: similar to a shorter lambda syntax
Steven D'Aprano
steve at pearwood.info
Wed Jan 23 01:43:14 EST 2019
On Mon, Jan 21, 2019 at 05:56:17PM +1100, Steven D'Aprano wrote:
[...]
> > Variable names that are declared but have not been assigned to will be
> > considered to exist for the purposes of the backtick expression.
>
> Python doesn't have variable declarations, so I don't know what this
> means.
Somebody emailed me off-list, and reminded me about type hints:
var: int
but that's not a declaration in the usual sense of the word. It is
officially an annotation. As PEP 526 states:
"Type annotations should not be confused with variable
declarations in statically typed languages."
https://www.python.org/dev/peps/pep-0526/#non-goals
At a global level, such type hints have no effect beyond recording the
annotation for introspection purposes. Inside a function, they don't do
that, but do instruct the compiler to treat the name as a local rather
than global. What they certainly don't do is create the variable.
If people want to argue that such variable annotations are declarations
"but not the same as in statically typed languages", that becomes a
matter of argument over definitions.
In any case, whether they are declarations or annotations, at least now
I think that I understand the intent of the quoted paragraph. As I
understand it:
- backtick objects raise at creation-time if they refer to a
variable that doesn't exist at that moment;
- but if the variable has been annotated using the "var: int"
syntax, it will be deemed to exist even if it doesn't.
To be precise, by "variable" I mean specifically a name-binding.
In the interactive interpreter I frequently create functions that refer
to a global variable or another function, before I've created that
variable or other function. Sometimes this happens in code in modules
as well.
def spam():
return eggs() + 1 # But eggs doesn't exist yet!
def eggs():
return 999
If I change ``spam`` to a backtick object, it is (I presume) an error,
because ``eggs`` doesn't exist. What a drag.
Especially since (unlike statically typed languages) this inconvenience
doesn't even buy me any runtime efficiency. The name lookup for eggs
will still have to be done at runtime every time I call spam().
--
Steve
More information about the Python-ideas
mailing list