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() {
    bar(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:
    bar(foo)

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():
    bar(foo)

as a means to replace:

foo = get_foo()
if not foo:
    bar(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
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to