In the spirit of borrowing from other languages, there’s a particular bit of 
functionality from Swift that I’ve really wanted to have in Python.

To preface, Swift uses var and let (static) when variables are created. It also 
supports optionals which allows a variable to be either some value or nil 
(Swift’s version of None). This enables the following syntax:

if let foo = get_foo() {

In words: if the value returned by get_foo() is not nil, assign it to foo and 
enter the if block. The variable foo is static and only available within the 
scope of the if block. The closest thing we have in Python is:

foo = get_foo()
if foo is not None:

However, foo is still available outside the scope of the if block presumably 
never to be referenced again. We could add “del foo” to remove it from our 
outer scope, but this is extra code.

What does everyone think about:

if foo = get_foo():

as a means to replace:

foo = get_foo()
if not foo:
del foo

Might there be some better syntax or a different keyword? I constantly run into 
this sort of use case.

Michael duPont
Python-ideas mailing list
Code of Conduct:

Reply via email to