Can we have assignment in a condition? - python

Is it possible to have assignment in a condition?
For ex.
if (a=some_func()):
# Use a

Why not try it out?
>>> def some_func():
... return 2
...
>>> if (a = some_func()):
File "<stdin>", line 1
if (a = some_func()):
^
SyntaxError: invalid syntax
So, no.
Update: This is possible (with different syntax) in Python 3.8
if a := some_func():

UPDATE - Original answer is near the bottom
Python 3.8 will bring in PEP572
Abstract
This is a proposal for creating a way to assign to variables
within an expression using the notation NAME := expr. A new exception,
TargetScopeError is added, and there is one change to evaluation
order.
https://lwn.net/Articles/757713/
The "PEP 572 mess" was the topic of a 2018 Python Language Summit
session led by benevolent dictator for life (BDFL) Guido van Rossum.
PEP 572 seeks to add assignment expressions (or "inline assignments")
to the language, but it has seen a prolonged discussion over multiple
huge threads on the python-dev mailing list—even after multiple rounds
on python-ideas. Those threads were often contentious and were clearly
voluminous to the point where many probably just tuned them out. At
the summit, Van Rossum gave an overview of the feature proposal, which
he seems inclined toward accepting, but he also wanted to discuss how
to avoid this kind of thread explosion in the future.
https://www.python.org/dev/peps/pep-0572/#examples-from-the-python-standard-library
Examples from the Python standard library
site.py env_base is only used on these lines, putting its assignment on the if moves it as the "header" of the block.
Current:
env_base = os.environ.get("PYTHONUSERBASE", None)
if env_base:
return env_base
Improved:
if env_base := os.environ.get("PYTHONUSERBASE", None):
return env_base
_pydecimal.py
Avoid nested if and remove one indentation level.
Current:
if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
Improved:
if self._is_special and (ans := self._check_nans(context=context)):
return ans
copy.py Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)
Current:
reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor:
rv = reductor(4)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
raise Error(
"un(deep)copyable object of type %s" % cls)
Improved:
if reductor := dispatch_table.get(cls):
rv = reductor(x)
elif reductor := getattr(x, "__reduce_ex__", None):
rv = reductor(4)
elif reductor := getattr(x, "__reduce__", None):
rv = reductor()
else:
raise Error("un(deep)copyable object of type %s" % cls)
datetime.py
tz is only used for s += tz, moving its assignment inside the if helps
to show its scope.
Current:
s = _format_time(self._hour, self._minute,
self._second, self._microsecond,
timespec)
tz = self._tzstr()
if tz:
s += tz
return s
Improved:
s = _format_time(self._hour, self._minute,
self._second, self._microsecond,
timespec)
if tz := self._tzstr():
s += tz
return s
sysconfig.py Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without
making it harder to understand.
Current:
while True:
line = fp.readline()
if not line:
break
m = define_rx.match(line)
if m:
n, v = m.group(1, 2)
try:
v = int(v)
except ValueError:
pass
vars[n] = v
else:
m = undef_rx.match(line)
if m:
vars[m.group(1)] = 0
Improved:
while line := fp.readline():
if m := define_rx.match(line):
n, v = m.group(1, 2)
try:
v = int(v)
except ValueError:
pass
vars[n] = v
elif m := undef_rx.match(line):
vars[m.group(1)] = 0
Simplifying list comprehensions A list comprehension can map and filter efficiently by capturing the condition:
results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0]
Similarly, a subexpression can be reused within the main expression,
by giving it a name on first use:
stuff = [[y := f(x), x/y] for x in range(5)]
Note that in both cases the variable y is bound in the containing
scope (i.e. at the same level as results or stuff).
Capturing condition values Assignment expressions can be used to good effect in the header of an if or while statement:
# Loop-and-a-half
while (command := input("> ")) != "quit":
print("You entered:", command)
# Capturing regular expression match objects
# See, for instance, Lib/pydoc.py, which uses a multiline spelling
# of this effect
if match := re.search(pat, text):
print("Found:", match.group(0))
# The same syntax chains nicely into 'elif' statements, unlike the
# equivalent using assignment statements.
elif match := re.search(otherpat, text):
print("Alternate found:", match.group(0))
elif match := re.search(third, text):
print("Fallback found:", match.group(0))
# Reading socket data until an empty string is returned
while data := sock.recv(8192):
print("Received data:", data)
Particularly with the while loop, this can remove the need to have an
infinite loop, an assignment, and a condition. It also creates a
smooth parallel between a loop which simply uses a function call as
its condition, and one which uses that as its condition but also uses
the actual value.
Fork An example from the low-level UNIX world:
if pid := os.fork():
# Parent code
else:
# Child code
Original answer
http://docs.python.org/tutorial/datastructures.html
Note that in Python, unlike C,
assignment cannot occur inside
expressions. C programmers may grumble
about this, but it avoids a common
class of problems encountered in C
programs: typing = in an expression
when == was intended.
also see:
http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm

Nope, the BDFL didn't like that feature.
From where I sit, Guido van Rossum, "Benevolent Dictator For Life”, has fought hard to keep Python as simple as it can be. We can quibble with some of the decisions he's made -- I'd have preferred he said 'No' more often. But the fact that there hasn't been a committee designing Python, but instead a trusted "advisory board", based largely on merit, filtering through one designer's sensibilities, has produced one hell of a nice language, IMHO.

Yes, but only from Python 3.8 and onwards.
PEP 572 proposes Assignment Expressions and has already been accepted.
Quoting the Syntax and semantics part of the PEP:
# Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
# A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
process(chunk)
# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
In your specific case, you will be able to write
if a := some_func():
# Use a

Not directly, per this old recipe of mine -- but as the recipe says it's easy to build the semantic equivalent, e.g. if you need to transliterate directly from a C-coded reference algorithm (before refactoring to more-idiomatic Python, of course;-). I.e.:
class DataHolder(object):
def __init__(self, value=None): self.value = value
def set(self, value): self.value = value; return value
def get(self): return self.value
data = DataHolder()
while data.set(somefunc()):
a = data.get()
# use a
BTW, a very idiomatic Pythonic form for your specific case, if you know exactly what falsish value somefunc may return when it does return a falsish value (e.g. 0), is
for a in iter(somefunc, 0):
# use a
so in this specific case the refactoring would be pretty easy;-).
If the return could be any kind of falsish value (0, None, '', ...), one possibility is:
import itertools
for a in itertools.takewhile(lambda x: x, iter(somefunc, object())):
# use a
but you might prefer a simple custom generator:
def getwhile(func, *a, **k):
while True:
x = func(*a, **k)
if not x: break
yield x
for a in getwhile(somefunc):
# use a

No. Assignment in Python is a statement, not an expression.

Thanks to Python 3.8 new feature it will be possible to do such a thing from this version, although not using = but Ada-like assignment operator :=. Example from the docs:
# Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match

You can define a function to do the assigning for you:
def assign(name, value):
import inspect
frame = inspect.currentframe()
try:
locals_ = frame.f_back.f_locals
finally:
del frame
locals_[name] = value
return value
if assign('test', 0):
print("first", test)
elif assign('xyz', 123):
print("second", xyz)

One of the reasons why assignments are illegal in conditions is that it's easier to make a mistake and assign True or False:
some_variable = 5
# This does not work
# if True = some_variable:
# do_something()
# This only works in Python 2.x
True = some_variable
print True # returns 5
In Python 3 True and False are keywords, so no risk anymore.

The assignment operator - also known informally as the the walrus operator - was created at 28-Feb-2018 in PEP572.
For the sake of completeness, I'll post the relevant parts so you can compare the differences between 3.7 and 3.8:
3.7
---
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
test: or_test ['if' or_test 'else' test] | lambdef
test_nocond: or_test | lambdef_nocond
lambdef: 'lambda' [varargslist] ':' test
lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
3.8
---
if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite]
namedexpr_test: test [':=' test] <---- WALRUS OPERATOR!!!
test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*

Related

Using if else statements for switching user path directories [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?
Python 3.10 (2021) introduced the match-case statement which provides a first-class implementation of a "switch" for Python. For example:
def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found
The match-case statement is considerably more powerful than this simple example.
The original answer below was written in 2008, before match-case was available:
You could use a dictionary:
def f(x):
return {
'a': 1,
'b': 2,
}[x]
If you'd like defaults, you could use the dictionary get(key[, default]) function:
def f(x):
return {
'a': 1,
'b': 2
}.get(x, 9) # 9 will be returned default if x is not found
I've always liked doing it this way
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)
From here
In addition to the dictionary methods (which I really like, BTW), you can also use if-elif-else to obtain the switch/case/default functionality:
if x == 'a':
# Do the thing
elif x == 'b':
# Do the other thing
if x in 'bc':
# Fall-through by not using elif, but now the default case includes case 'a'!
elif x in 'xyz':
# Do yet another thing
else:
# Do the default
This of course is not identical to switch/case - you cannot have fall-through as easily as leaving off the break statement, but you can have a more complicated test. Its formatting is nicer than a series of nested ifs, even though functionally that's what it is closer to.
Python >= 3.10
Wow, Python 3.10+ now has a match/case syntax which is like switch/case and more!
PEP 634 -- Structural Pattern Matching
Selected features of match/case
1 - Match values:
Matching values is similar to a simple switch/case in another language:
match something:
case 1 | 2 | 3:
# Match 1-3.
case _:
# Anything else.
#
# Match will throw an error if this is omitted
# and it doesn't match any of the other patterns.
2 - Match structural patterns:
match something:
case str() | bytes():
# Match a string like object.
case [str(), int()]:
# Match a `str` and an `int` sequence
# (`list` or a `tuple` but not a `set` or an iterator).
case [_, _]:
# Match a sequence of 2 variables.
# To prevent a common mistake, sequence patterns don’t match strings.
case {"bandwidth": 100, "latency": 300}:
# Match this dict. Extra keys are ignored.
3 - Capture variables
Parse an object; saving it as variables:
match something:
case [name, count]
# Match a sequence of any two objects and parse them into the two variables.
case [x, y, *rest]:
# Match a sequence of two or more objects,
# binding object #3 and on into the rest variable.
case bytes() | str() as text:
# Match any string like object and save it to the text variable.
Capture variables can be useful when parsing data (such as JSON or HTML) that may come in one of a number of different patterns.
Capture variables is a feature. But it also means that you need to use dotted constants (ex: COLOR.RED) only. Otherwise, the constant will be treated as a capture variable and overwritten.
More sample usage:
match something:
case 0 | 1 | 2:
# Matches 0, 1 or 2 (value).
print("Small number")
case [] | [_]:
# Matches an empty or single value sequence (structure).
# Matches lists and tuples but not sets.
print("A short sequence")
case str() | bytes():
# Something of `str` or `bytes` type (data type).
print("Something string-like")
case _:
# Anything not matched by the above.
print("Something else")
Python <= 3.9
My favorite Python recipe for switch/case was:
choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
Short and simple for simple scenarios.
Compare to 11+ lines of C code:
// C Language version of a simple 'switch/case'.
switch( key )
{
case 'a' :
result = 1;
break;
case 'b' :
result = 2;
break;
default :
result = -1;
}
You can even assign multiple variables by using tuples:
choices = {'a': (1, 2, 3), 'b': (4, 5, 6)}
(result1, result2, result3) = choices.get(key, ('default1', 'default2', 'default3'))
class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
def case(*args):
return any((arg == switch.value for arg in args))
Usage:
while switch(n):
if case(0):
print "You typed zero."
break
if case(1, 4, 9):
print "n is a perfect square."
break
if case(2):
print "n is an even number."
if case(2, 3, 5, 7):
print "n is a prime number."
break
if case(6, 8):
print "n is an even number."
break
print "Only single-digit numbers are allowed."
break
Tests:
n = 2
#Result:
#n is an even number.
#n is a prime number.
n = 11
#Result:
#Only single-digit numbers are allowed.
My favorite one is a really nice recipe. It's the closest one I've seen to actual switch case statements, especially in features.
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
Here's an example:
# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = 'ten'
for case in switch(v):
if case('one'):
print 1
break
if case('two'):
print 2
break
if case('ten'):
print 10
break
if case('eleven'):
print 11
break
if case(): # default, could also just omit condition or 'if True'
print "something else!"
# No need to break here, it'll stop anyway
# break is used here to look as much like the real thing as possible, but
# elif is generally just as good and more concise.
# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain 'pass'
c = 'z'
for case in switch(c):
if case('a'): pass # only necessary if the rest of the suite is empty
if case('b'): pass
# ...
if case('y'): pass
if case('z'):
print "c is lowercase!"
break
if case('A'): pass
# ...
if case('Z'):
print "c is uppercase!"
break
if case(): # default
print "I dunno what c was!"
# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic 'case' statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = 'A'
for case in switch(c):
if case(*string.lowercase): # note the * for unpacking as arguments
print "c is lowercase!"
break
if case(*string.uppercase):
print "c is uppercase!"
break
if case('!', '?', '.'): # normal argument passing style also applies
print "c is a sentence terminator!"
break
if case(): # default
print "I dunno what c was!"
Some of the comments indicated that a context manager solution using with foo as case rather than for case in foo might be cleaner, and for large switch statements the linear rather than quadratic behavior might be a nice touch. Part of the value in this answer with a for loop is the ability to have breaks and fallthrough, and if we're willing to play with our choice of keywords a little bit we can get that in a context manager too:
class Switch:
def __init__(self, value):
self.value = value
self._entered = False
self._broken = False
self._prev = None
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return False # Allows a traceback to occur
def __call__(self, *values):
if self._broken:
return False
if not self._entered:
if values and self.value not in values:
return False
self._entered, self._prev = True, values
return True
if self._prev is None:
self._prev = values
return True
if self._prev != values:
self._broken = True
return False
if self._prev == values:
self._prev = None
return False
#property
def default(self):
return self()
Here's an example:
# Prints 'bar' then 'baz'.
with Switch(2) as case:
while case(0):
print('foo')
while case(1, 2, 3):
print('bar')
while case(4, 5):
print('baz')
break
while case.default:
print('default')
break
class Switch:
def __init__(self, value):
self.value = value
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return False # Allows a traceback to occur
def __call__(self, *values):
return self.value in values
from datetime import datetime
with Switch(datetime.today().weekday()) as case:
if case(0):
# Basic usage of switch
print("I hate mondays so much.")
# Note there is no break needed here
elif case(1,2):
# This switch also supports multiple conditions (in one line)
print("When is the weekend going to be here?")
elif case(3,4):
print("The weekend is near.")
else:
# Default would occur here
print("Let's go have fun!") # Didn't use case for example purposes
There's a pattern that I learned from Twisted Python code.
class SMTP:
def lookupMethod(self, command):
return getattr(self, 'do_' + command.upper(), None)
def do_HELO(self, rest):
return 'Howdy ' + rest
def do_QUIT(self, rest):
return 'Bye'
SMTP().lookupMethod('HELO')('foo.bar.com') # => 'Howdy foo.bar.com'
SMTP().lookupMethod('QUIT')('') # => 'Bye'
You can use it any time you need to dispatch on a token and execute extended piece of code. In a state machine you would have state_ methods, and dispatch on self.state. This switch can be cleanly extended by inheriting from base class and defining your own do_ methods. Often times you won't even have do_ methods in the base class.
Edit: how exactly is that used
In case of SMTP you will receive HELO from the wire. The relevant code (from twisted/mail/smtp.py, modified for our case) looks like this
class SMTP:
# ...
def do_UNKNOWN(self, rest):
raise NotImplementedError, 'received unknown command'
def state_COMMAND(self, line):
line = line.strip()
parts = line.split(None, 1)
if parts:
method = self.lookupMethod(parts[0]) or self.do_UNKNOWN
if len(parts) == 2:
return method(parts[1])
else:
return method('')
else:
raise SyntaxError, 'bad syntax'
SMTP().state_COMMAND(' HELO foo.bar.com ') # => Howdy foo.bar.com
You'll receive ' HELO foo.bar.com ' (or you might get 'QUIT' or 'RCPT TO: foo'). This is tokenized into parts as ['HELO', 'foo.bar.com']. The actual method lookup name is taken from parts[0].
(The original method is also called state_COMMAND, because it uses the same pattern to implement a state machine, i.e. getattr(self, 'state_' + self.mode))
I'm just going to drop my two cents in here. The reason there isn't a case/switch statement in Python is because Python follows the principle of "there's only one right way to do something". So obviously you could come up with various ways of recreating switch/case functionality, but the Pythonic way of accomplishing this is the if/elif construct. I.e.,
if something:
return "first thing"
elif somethingelse:
return "second thing"
elif yetanotherthing:
return "third thing"
else:
return "default thing"
I just felt PEP 8 deserved a nod here. One of the beautiful things about Python is its simplicity and elegance. That is largely derived from principles laid out in PEP 8, including "There's only one right way to do something."
Let's say you don't want to just return a value, but want to use methods that change something on an object. Using the approach stated here would be:
result = {
'a': obj.increment(x),
'b': obj.decrement(x)
}.get(value, obj.default(x))
Here Python evaluates all methods in the dictionary.
So even if your value is 'a', the object will get incremented and decremented by x.
Solution:
func, args = {
'a' : (obj.increment, (x,)),
'b' : (obj.decrement, (x,)),
}.get(value, (obj.default, (x,)))
result = func(*args)
So you get a list containing a function and its arguments. This way, only the function pointer and the argument list get returned, not evaluated. 'result' then evaluates the returned function call.
Solution to run functions:
result = {
'case1': foo1,
'case2': foo2,
'case3': foo3,
}.get(option)(parameters_optional)
where foo1(), foo2() and foo3() are functions
Example 1 (with parameters):
option = number['type']
result = {
'number': value_of_int, # result = value_of_int(number['value'])
'text': value_of_text, # result = value_of_text(number['value'])
'binary': value_of_bin, # result = value_of_bin(number['value'])
}.get(option)(value['value'])
Example 2 (no parameters):
option = number['type']
result = {
'number': func_for_number, # result = func_for_number()
'text': func_for_text, # result = func_for_text()
'binary': func_for_bin, # result = func_for_bin()
}.get(option)()
Example 4 (only values):
option = number['type']
result = {
'number': lambda: 10, # result = 10
'text': lambda: 'ten', # result = 'ten'
'binary': lambda: 0b101111, # result = 47
}.get(option)()
If you have a complicated case block you can consider using a function dictionary lookup table...
If you haven't done this before it's a good idea to step into your debugger and view exactly how the dictionary looks up each function.
NOTE: Do not use "()" inside the case/dictionary lookup or it will call each of your functions as the dictionary / case block is created. Remember this because you only want to call each function once using a hash style lookup.
def first_case():
print "first"
def second_case():
print "second"
def third_case():
print "third"
mycase = {
'first': first_case, #do not use ()
'second': second_case, #do not use ()
'third': third_case #do not use ()
}
myfunc = mycase['first']
myfunc()
If you're searching extra-statement, as "switch", I built a Python module that extends Python. It's called ESPY as "Enhanced Structure for Python" and it's available for both Python 2.x and Python 3.x.
For example, in this case, a switch statement could be performed by the following code:
macro switch(arg1):
while True:
cont=False
val=%arg1%
socket case(arg2):
if val==%arg2% or cont:
cont=True
socket
socket else:
socket
break
That can be used like this:
a=3
switch(a):
case(0):
print("Zero")
case(1):
print("Smaller than 2"):
break
else:
print ("greater than 1")
So espy translate it in Python as:
a=3
while True:
cont=False
if a==0 or cont:
cont=True
print ("Zero")
if a==1 or cont:
cont=True
print ("Smaller than 2")
break
print ("greater than 1")
break
Most of the answers here are pretty old, and especially the accepted ones, so it seems worth updating.
First, the official Python FAQ covers this, and recommends the elif chain for simple cases and the dict for larger or more complex cases. It also suggests a set of visit_ methods (a style used by many server frameworks) for some cases:
def dispatch(self, value):
method_name = 'visit_' + str(value)
method = getattr(self, method_name)
method()
The FAQ also mentions PEP 275, which was written to get an official once-and-for-all decision on adding C-style switch statements. But that PEP was actually deferred to Python 3, and it was only officially rejected as a separate proposal, PEP 3103. The answer was, of course, no—but the two PEPs have links to additional information if you're interested in the reasons or the history.
One thing that came up multiple times (and can be seen in PEP 275, even though it was cut out as an actual recommendation) is that if you're really bothered by having 8 lines of code to handle 4 cases, vs. the 6 lines you'd have in C or Bash, you can always write this:
if x == 1: print('first')
elif x == 2: print('second')
elif x == 3: print('third')
else: print('did not place')
This isn't exactly encouraged by PEP 8, but it's readable and not too unidiomatic.
Over the more than a decade since PEP 3103 was rejected, the issue of C-style case statements, or even the slightly more powerful version in Go, has been considered dead; whenever anyone brings it up on python-ideas or -dev, they're referred to the old decision.
However, the idea of full ML-style pattern matching arises every few years, especially since languages like Swift and Rust have adopted it. The problem is that it's hard to get much use out of pattern matching without algebraic data types. While Guido has been sympathetic to the idea, nobody's come up with a proposal that fits into Python very well. (You can read my 2014 strawman for an example.) This could change with dataclass in 3.7 and some sporadic proposals for a more powerful enum to handle sum types, or with various proposals for different kinds of statement-local bindings (like PEP 3150, or the set of proposals currently being discussed on -ideas). But so far, it hasn't.
There are also occasionally proposals for Perl 6-style matching, which is basically a mishmash of everything from elif to regex to single-dispatch type-switching.
Expanding on the "dict as switch" idea. If you want to use a default value for your switch:
def f(x):
try:
return {
'a': 1,
'b': 2,
}[x]
except KeyError:
return 'default'
I found that a common switch structure:
switch ...parameter...
case p1: v1; break;
case p2: v2; break;
default: v3;
can be expressed in Python as follows:
(lambda x: v1 if p1(x) else v2 if p2(x) else v3)
or formatted in a clearer way:
(lambda x:
v1 if p1(x) else
v2 if p2(x) else
v3)
Instead of being a statement, the Python version is an expression, which evaluates to a value.
The solutions I use:
A combination of 2 of the solutions posted here, which is relatively easy to read and supports defaults.
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}.get(whatToUse, lambda x: x - 22)(value)
where
.get('c', lambda x: x - 22)(23)
looks up "lambda x: x - 2" in the dict and uses it with x=23
.get('xxx', lambda x: x - 22)(44)
doesn't find it in the dict and uses the default "lambda x: x - 22" with x=44.
You can use a dispatched dict:
#!/usr/bin/env python
def case1():
print("This is case 1")
def case2():
print("This is case 2")
def case3():
print("This is case 3")
token_dict = {
"case1" : case1,
"case2" : case2,
"case3" : case3,
}
def main():
cases = ("case1", "case3", "case2", "case1")
for case in cases:
token_dict[case]()
if __name__ == '__main__':
main()
Output:
This is case 1
This is case 3
This is case 2
This is case 1
I didn't find the simple answer I was looking for anywhere on Google search. But I figured it out anyway. It's really quite simple. Decided to post it, and maybe prevent a few less scratches on someone else's head. The key is simply "in" and tuples. Here is the switch statement behavior with fall-through, including RANDOM fall-through.
l = ['Dog', 'Cat', 'Bird', 'Bigfoot',
'Dragonfly', 'Snake', 'Bat', 'Loch Ness Monster']
for x in l:
if x in ('Dog', 'Cat'):
x += " has four legs"
elif x in ('Bat', 'Bird', 'Dragonfly'):
x += " has wings."
elif x in ('Snake',):
x += " has a forked tongue."
else:
x += " is a big mystery by default."
print(x)
print()
for x in range(10):
if x in (0, 1):
x = "Values 0 and 1 caught here."
elif x in (2,):
x = "Value 2 caught here."
elif x in (3, 7, 8):
x = "Values 3, 7, 8 caught here."
elif x in (4, 6):
x = "Values 4 and 6 caught here"
else:
x = "Values 5 and 9 caught in default."
print(x)
Provides:
Dog has four legs
Cat has four legs
Bird has wings.
Bigfoot is a big mystery by default.
Dragonfly has wings.
Snake has a forked tongue.
Bat has wings.
Loch Ness Monster is a big mystery by default.
Values 0 and 1 caught here.
Values 0 and 1 caught here.
Value 2 caught here.
Values 3, 7, 8 caught here.
Values 4 and 6 caught here
Values 5 and 9 caught in default.
Values 4 and 6 caught here
Values 3, 7, 8 caught here.
Values 3, 7, 8 caught here.
Values 5 and 9 caught in default.
# simple case alternative
some_value = 5.0
# this while loop block simulates a case block
# case
while True:
# case 1
if some_value > 5:
print ('Greater than five')
break
# case 2
if some_value == 5:
print ('Equal to five')
break
# else case 3
print ( 'Must be less than 5')
break
I was quite confused after reading the accepted answer, but this cleared it all up:
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
This code is analogous to:
function(argument){
switch(argument) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
default:
return "nothing";
}
}
Check the Source for more about dictionary mapping to functions.
def f(x):
dictionary = {'a':1, 'b':2, 'c':3}
return dictionary.get(x,'Not Found')
##Returns the value for the letter x;returns 'Not Found' if x isn't a key in the dictionary
I liked Mark Bies's answer
Since the x variable must used twice, I modified the lambda functions to parameterless.
I have to run with results[value](value)
In [2]: result = {
...: 'a': lambda x: 'A',
...: 'b': lambda x: 'B',
...: 'c': lambda x: 'C'
...: }
...: result['a']('a')
...:
Out[2]: 'A'
In [3]: result = {
...: 'a': lambda : 'A',
...: 'b': lambda : 'B',
...: 'c': lambda : 'C',
...: None: lambda : 'Nothing else matters'
...: }
...: result['a']()
...:
Out[3]: 'A'
Edit: I noticed that I can use None type with with dictionaries. So this would emulate switch ; case else
def f(x):
return 1 if x == 'a' else\
2 if x in 'bcd' else\
0 #default
Short and easy to read, has a default value and supports expressions in both conditions and return values.
However, it is less efficient than the solution with a dictionary. For example, Python has to scan through all the conditions before returning the default value.
Simple, not tested; each condition is evaluated independently: there is no fall-through, but all cases are evaluated (although the expression to switch on is only evaluated once), unless there is a break statement. For example,
for case in [expression]:
if case == 1:
print(end='Was 1. ')
if case == 2:
print(end='Was 2. ')
break
if case in (1, 2):
print(end='Was 1 or 2. ')
print(end='Was something. ')
prints Was 1. Was 1 or 2. Was something. (Dammit! Why can't I have trailing whitespace in inline code blocks?) if expression evaluates to 1, Was 2. if expression evaluates to 2, or Was something. if expression evaluates to something else.
There have been a lot of answers so far that have said, "we don't have a switch in Python, do it this way". However, I would like to point out that the switch statement itself is an easily-abused construct that can and should be avoided in most cases because they promote lazy programming. Case in point:
def ToUpper(lcChar):
if (lcChar == 'a' or lcChar == 'A'):
return 'A'
elif (lcChar == 'b' or lcChar == 'B'):
return 'B'
...
elif (lcChar == 'z' or lcChar == 'Z'):
return 'Z'
else:
return None # or something
Now, you could do this with a switch-statement (if Python offered one) but you'd be wasting your time because there are methods that do this just fine. Or maybe, you have something less obvious:
def ConvertToReason(code):
if (code == 200):
return 'Okay'
elif (code == 400):
return 'Bad Request'
elif (code == 404):
return 'Not Found'
else:
return None
However, this sort of operation can and should be handled with a dictionary because it will be faster, less complex, less prone to error and more compact.
And the vast majority of "use cases" for switch statements will fall into one of these two cases; there's just very little reason to use one if you've thought about your problem thoroughly.
So, rather than asking "how do I switch in Python?", perhaps we should ask, "why do I want to switch in Python?" because that's often the more interesting question and will often expose flaws in the design of whatever you're building.
Now, that isn't to say that switches should never be used either. State machines, lexers, parsers and automata all use them to some degree and, in general, when you start from a symmetrical input and go to an asymmetrical output they can be useful; you just need to make sure that you don't use the switch as a hammer because you see a bunch of nails in your code.
A solution I tend to use which also makes use of dictionaries is:
def decision_time( key, *args, **kwargs):
def action1()
"""This function is a closure - and has access to all the arguments"""
pass
def action2()
"""This function is a closure - and has access to all the arguments"""
pass
def action3()
"""This function is a closure - and has access to all the arguments"""
pass
return {1:action1, 2:action2, 3:action3}.get(key,default)()
This has the advantage that it doesn't try to evaluate the functions every time, and you just have to ensure that the outer function gets all the information that the inner functions need.
Defining:
def switch1(value, options):
if value in options:
options[value]()
allows you to use a fairly straightforward syntax, with the cases bundled into a map:
def sample1(x):
local = 'betty'
switch1(x, {
'a': lambda: print("hello"),
'b': lambda: (
print("goodbye," + local),
print("!")),
})
I kept trying to redefine switch in a way that would let me get rid of the "lambda:", but gave up. Tweaking the definition:
def switch(value, *maps):
options = {}
for m in maps:
options.update(m)
if value in options:
options[value]()
elif None in options:
options[None]()
Allowed me to map multiple cases to the same code, and to supply a default option:
def sample(x):
switch(x, {
_: lambda: print("other")
for _ in 'cdef'
}, {
'a': lambda: print("hello"),
'b': lambda: (
print("goodbye,"),
print("!")),
None: lambda: print("I dunno")
})
Each replicated case has to be in its own dictionary; switch() consolidates the dictionaries before looking up the value. It's still uglier than I'd like, but it has the basic efficiency of using a hashed lookup on the expression, rather than a loop through all the keys.
Expanding on Greg Hewgill's answer - We can encapsulate the dictionary-solution using a decorator:
def case(callable):
"""switch-case decorator"""
class case_class(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def do_call(self):
return callable(*self.args, **self.kwargs)
return case_class
def switch(key, cases, default=None):
"""switch-statement"""
ret = None
try:
ret = case[key].do_call()
except KeyError:
if default:
ret = default.do_call()
finally:
return ret
This can then be used with the #case-decorator
#case
def case_1(arg1):
print 'case_1: ', arg1
#case
def case_2(arg1, arg2):
print 'case_2'
return arg1, arg2
#case
def default_case(arg1, arg2, arg3):
print 'default_case: ', arg1, arg2, arg3
ret = switch(somearg, {
1: case_1('somestring'),
2: case_2(13, 42)
}, default_case(123, 'astring', 3.14))
print ret
The good news are that this has already been done in NeoPySwitch-module. Simply install using pip:
pip install NeoPySwitch

assign input to variable if input is condition of while loop [duplicate]

Is it possible to have assignment in a condition?
For ex.
if (a=some_func()):
# Use a
Why not try it out?
>>> def some_func():
... return 2
...
>>> if (a = some_func()):
File "<stdin>", line 1
if (a = some_func()):
^
SyntaxError: invalid syntax
So, no.
Update: This is possible (with different syntax) in Python 3.8
if a := some_func():
UPDATE - Original answer is near the bottom
Python 3.8 will bring in PEP572
Abstract
This is a proposal for creating a way to assign to variables
within an expression using the notation NAME := expr. A new exception,
TargetScopeError is added, and there is one change to evaluation
order.
https://lwn.net/Articles/757713/
The "PEP 572 mess" was the topic of a 2018 Python Language Summit
session led by benevolent dictator for life (BDFL) Guido van Rossum.
PEP 572 seeks to add assignment expressions (or "inline assignments")
to the language, but it has seen a prolonged discussion over multiple
huge threads on the python-dev mailing list—even after multiple rounds
on python-ideas. Those threads were often contentious and were clearly
voluminous to the point where many probably just tuned them out. At
the summit, Van Rossum gave an overview of the feature proposal, which
he seems inclined toward accepting, but he also wanted to discuss how
to avoid this kind of thread explosion in the future.
https://www.python.org/dev/peps/pep-0572/#examples-from-the-python-standard-library
Examples from the Python standard library
site.py env_base is only used on these lines, putting its assignment on the if moves it as the "header" of the block.
Current:
env_base = os.environ.get("PYTHONUSERBASE", None)
if env_base:
return env_base
Improved:
if env_base := os.environ.get("PYTHONUSERBASE", None):
return env_base
_pydecimal.py
Avoid nested if and remove one indentation level.
Current:
if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
Improved:
if self._is_special and (ans := self._check_nans(context=context)):
return ans
copy.py Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)
Current:
reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor:
rv = reductor(4)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
raise Error(
"un(deep)copyable object of type %s" % cls)
Improved:
if reductor := dispatch_table.get(cls):
rv = reductor(x)
elif reductor := getattr(x, "__reduce_ex__", None):
rv = reductor(4)
elif reductor := getattr(x, "__reduce__", None):
rv = reductor()
else:
raise Error("un(deep)copyable object of type %s" % cls)
datetime.py
tz is only used for s += tz, moving its assignment inside the if helps
to show its scope.
Current:
s = _format_time(self._hour, self._minute,
self._second, self._microsecond,
timespec)
tz = self._tzstr()
if tz:
s += tz
return s
Improved:
s = _format_time(self._hour, self._minute,
self._second, self._microsecond,
timespec)
if tz := self._tzstr():
s += tz
return s
sysconfig.py Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without
making it harder to understand.
Current:
while True:
line = fp.readline()
if not line:
break
m = define_rx.match(line)
if m:
n, v = m.group(1, 2)
try:
v = int(v)
except ValueError:
pass
vars[n] = v
else:
m = undef_rx.match(line)
if m:
vars[m.group(1)] = 0
Improved:
while line := fp.readline():
if m := define_rx.match(line):
n, v = m.group(1, 2)
try:
v = int(v)
except ValueError:
pass
vars[n] = v
elif m := undef_rx.match(line):
vars[m.group(1)] = 0
Simplifying list comprehensions A list comprehension can map and filter efficiently by capturing the condition:
results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0]
Similarly, a subexpression can be reused within the main expression,
by giving it a name on first use:
stuff = [[y := f(x), x/y] for x in range(5)]
Note that in both cases the variable y is bound in the containing
scope (i.e. at the same level as results or stuff).
Capturing condition values Assignment expressions can be used to good effect in the header of an if or while statement:
# Loop-and-a-half
while (command := input("> ")) != "quit":
print("You entered:", command)
# Capturing regular expression match objects
# See, for instance, Lib/pydoc.py, which uses a multiline spelling
# of this effect
if match := re.search(pat, text):
print("Found:", match.group(0))
# The same syntax chains nicely into 'elif' statements, unlike the
# equivalent using assignment statements.
elif match := re.search(otherpat, text):
print("Alternate found:", match.group(0))
elif match := re.search(third, text):
print("Fallback found:", match.group(0))
# Reading socket data until an empty string is returned
while data := sock.recv(8192):
print("Received data:", data)
Particularly with the while loop, this can remove the need to have an
infinite loop, an assignment, and a condition. It also creates a
smooth parallel between a loop which simply uses a function call as
its condition, and one which uses that as its condition but also uses
the actual value.
Fork An example from the low-level UNIX world:
if pid := os.fork():
# Parent code
else:
# Child code
Original answer
http://docs.python.org/tutorial/datastructures.html
Note that in Python, unlike C,
assignment cannot occur inside
expressions. C programmers may grumble
about this, but it avoids a common
class of problems encountered in C
programs: typing = in an expression
when == was intended.
also see:
http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm
Nope, the BDFL didn't like that feature.
From where I sit, Guido van Rossum, "Benevolent Dictator For Life”, has fought hard to keep Python as simple as it can be. We can quibble with some of the decisions he's made -- I'd have preferred he said 'No' more often. But the fact that there hasn't been a committee designing Python, but instead a trusted "advisory board", based largely on merit, filtering through one designer's sensibilities, has produced one hell of a nice language, IMHO.
Yes, but only from Python 3.8 and onwards.
PEP 572 proposes Assignment Expressions and has already been accepted.
Quoting the Syntax and semantics part of the PEP:
# Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
# A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
process(chunk)
# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
In your specific case, you will be able to write
if a := some_func():
# Use a
Not directly, per this old recipe of mine -- but as the recipe says it's easy to build the semantic equivalent, e.g. if you need to transliterate directly from a C-coded reference algorithm (before refactoring to more-idiomatic Python, of course;-). I.e.:
class DataHolder(object):
def __init__(self, value=None): self.value = value
def set(self, value): self.value = value; return value
def get(self): return self.value
data = DataHolder()
while data.set(somefunc()):
a = data.get()
# use a
BTW, a very idiomatic Pythonic form for your specific case, if you know exactly what falsish value somefunc may return when it does return a falsish value (e.g. 0), is
for a in iter(somefunc, 0):
# use a
so in this specific case the refactoring would be pretty easy;-).
If the return could be any kind of falsish value (0, None, '', ...), one possibility is:
import itertools
for a in itertools.takewhile(lambda x: x, iter(somefunc, object())):
# use a
but you might prefer a simple custom generator:
def getwhile(func, *a, **k):
while True:
x = func(*a, **k)
if not x: break
yield x
for a in getwhile(somefunc):
# use a
No. Assignment in Python is a statement, not an expression.
Thanks to Python 3.8 new feature it will be possible to do such a thing from this version, although not using = but Ada-like assignment operator :=. Example from the docs:
# Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
You can define a function to do the assigning for you:
def assign(name, value):
import inspect
frame = inspect.currentframe()
try:
locals_ = frame.f_back.f_locals
finally:
del frame
locals_[name] = value
return value
if assign('test', 0):
print("first", test)
elif assign('xyz', 123):
print("second", xyz)
One of the reasons why assignments are illegal in conditions is that it's easier to make a mistake and assign True or False:
some_variable = 5
# This does not work
# if True = some_variable:
# do_something()
# This only works in Python 2.x
True = some_variable
print True # returns 5
In Python 3 True and False are keywords, so no risk anymore.
The assignment operator - also known informally as the the walrus operator - was created at 28-Feb-2018 in PEP572.
For the sake of completeness, I'll post the relevant parts so you can compare the differences between 3.7 and 3.8:
3.7
---
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
test: or_test ['if' or_test 'else' test] | lambdef
test_nocond: or_test | lambdef_nocond
lambdef: 'lambda' [varargslist] ':' test
lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
3.8
---
if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite]
namedexpr_test: test [':=' test] <---- WALRUS OPERATOR!!!
test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*

How can an assignment statement "x = y := f(x)" be done when using assignment expressions in Python?

I read in Twitter:
#Python news: Guido accepted PEP 572. Python now has assignment expressions.
if (match := (pattern.search) pattern.search(data)) is not None:
print((match.group) mo.group(1))
filtered_data = [y for x in data if (y := f(x)) is not None]
(correction mine in the 2nd line of code)
As indicated, PEP 572 -- Assignment Expressions describes this to be present in Python 3.8:
This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr.
I've gone through the description and examples and I see this is a convenient way to avoid repetitions of either calls or assignments, so instead of:
match1 = pattern1.match(data)
match2 = pattern2.match(data)
if match1:
return match1.group(1)
elif match2:
return match2.group(2)
or the more efficient:
match1 = pattern1.match(data)
if match1:
return match1.group(1)
else:
match2 = pattern2.match(data)
if match2:
return match2.group(2)
One now can say:
if match1 := pattern1.match(data):
return match1.group(1)
elif match2 := pattern2.match(data):
return match2.group(2)
Similarly, one can now say:
if any(len(longline := line) >= 100 for line in lines):
print("Extremely long line:", longline)
However, I do not understand how this example given in the PEP is not valid:
y0 = y1 := f(x) # INVALID
Will it be correct to say y0 = (y1 := f(x))? How could it be used?
Foot note for those who wonder where will this be available: I already installed Python 3.7 and it does not work there, since the PEP currently shows as "Status: Draft". However, the PEP talks about Proof of concept / reference implementation (https://github.com/Rosuav/cpython/tree/assignment-expressions), so it is a matter of using their Python 3.8 alpha 0 version that includes it.
As explicitly stated in the PEP,
Unparenthesized assignment expressions are prohibited at the top level in the right hand side of an assignment statement; for example, the following is not allowed:
y0 = y1 := f(x) # INVALID
Again, this rule is included to avoid two visually similar ways of saying the same thing.
And later,
As follows from section "Exceptional cases" above, it is never allowed at the same level as =. In case a different grouping is desired, parentheses should be used.
...
# INVALID
x = y := 0
# Valid alternative
x = (y := 0)

":=" syntax and assignment expressions: what and why?

PEP 572 introduces assignment expressions (colloquially known as the Walrus Operator), implemented for Python 3.8. This seems like a really substantial new feature since it will allow this form of assignment within comprehensions and lambda functions.
What exactly are the syntax, semantics, and grammar specification of assignment expressions?
Why is this new (and seemingly quite radical concept) being introduced, when a similar idea in PEP 379 on "Adding an assignment expression" was rejected before?
PEP 572 contains many of the details, especially for the first question. I'll try to summarise/quote concisely arguably some of the most important parts of the PEP:
Rationale
Allowing this form of assignment within comprehensions, such as list comprehensions, and lambda functions where traditional assignments are forbidden. This can also facilitate interactive debugging without the need for code refactoring.
Recommended use-case examples
a) Getting conditional values
for example (in Python 3):
command = input("> ")
while command != "quit":
print("You entered:", command)
command = input("> ")
can become:
while (command := input("> ")) != "quit":
print("You entered:", command)
Similarly, from the docs:
In this example, the assignment expression helps avoid calling len()
twice:
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
b) Simplifying list comprehensions
for example:
stuff = [(lambda y: [y,x/y])(f(x)) for x in range(5)]
can become:
stuff = [[y := f(x), x/y] for x in range(5)]
Syntax and semantics
In any context where arbitrary Python expressions can be used, a named expression can appear. This is of the form name := expr where expr is any valid Python expression, and name is an identifier.
The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value
Differences from regular assignment statements
In addition to being an expression rather than statement, there are several differences mentioned in the PEP: expression assignments go right-to-left, have different priority around commas, and do not support:
Multiple targets
x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
Assignments not to a single name:
# No equivalent
a[i] = x
self.rest = []
Iterable packing/unpacking
# Equivalent needs extra parentheses
loc = x, y # Use (loc := (x, y))
info = name, phone, *rest # Use (info := (name, phone, *rest))
# No equivalent
px, py, pz = position
name, phone, email, *other_info = contact
Inline type annotations:
# Closest equivalent is "p: Optional[int]" as a separate declaration
p: Optional[int] = None
Augmented assignment is not supported:
total += tax # Equivalent: (total := total + tax)
A couple of my favorite examples of where assignment expressions can make code more concise and easier to read:
if statement
Before:
match = pattern.match(line)
if match:
return match.group(1)
After:
if match := pattern.match(line):
return match.group(1)
Infinite while statement
Before:
while True:
data = f.read(1024)
if not data:
break
use(data)
After:
while data := f.read(1024):
use(data)
There are other good examples in the PEP.
A few more examples and rationales now that 3.8 has been officially released.
Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.
Source: LicensedProfessional's reddit comment
Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
process(chunk)
Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
What is := operator?
In simple terms := is a expression + assignment operator.
it executes an expression and assigns the result of that expression in a single variable.
Why is := operator needed?
simple useful case will be to reduce function calls in comprehensions while maintaining the redability.
lets consider a list comprehension to add one and filter if result is grater than 0 without a := operator. Here we need to call the add_one function twice.
[add_one(num) for num in numbers if add_one(num) > 0]
Case 1:
def add_one(num):
return num + 1
numbers = [1,2,3,4,-2,45,6]
result1 = [value for num in numbers if (value := add_one(num)) > 0]
>>> result1
[2, 3, 4, 5, 46, 7]
The result is as expected and we don't need to call the add_one function to call twice which shows the advantage of := operator
be cautious with walarus := operator while using list comprehension
below cases might help you better understand the use of := operator
Case 2:
def add_one(num):
return num + 1
numbers = [1,2,3,4,-2,45,6]
>>> result2 = [(value := add_one(num)) for num in numbers if value > 0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
NameError: name 'value' is not defined
Case 3: when a global variable is set to positive
def add_one(num):
return num + 1
numbers = [1,2,3,4,-2,45,6]
value = 1
result3 = [(value := add_one(num)) for num in numbers if value > 0]
>>> result3
[2, 3, 4, 5, -1]
Case 4: when a global variable is set to negitive
def add_one(num):
return num + 1
numbers = [1,2,3,4,-2,45,6]
value = -1
result4 = [(value := add_one(num)) for num in numbers if value > 0]
>>> result4
[]

How to avoid writing request.GET.get() twice in order to print it?

I come from a PHP background and would like to know if there's a way to do this in Python.
In PHP you can kill 2 birds with one stone like this:
Instead of:
if(getData()){
$data = getData();
echo $data;
}
I can do this:
if($data = getData()){
echo $data;
}
You check to see if getData() exists AND if it does, you assign it to a variable in one statement.
I wanted to know if there's a way to do this in Python? So instead of doing this:
if request.GET.get('q'):
q = request.GET.get('q')
print q
avoid writing request.GET.get('q') twice.
See my 8-year-old recipe here for just this task.
# In Python, you can't code "if x=foo():" -- assignment is a statement, thus
# you can't fit it into an expression, as needed for conditions of if and
# while statements, &c. No problem, if you just structure your code around
# this. But sometimes you're transliterating C, or Perl, or ..., and you'd
# like your transliteration to be structurally close to the original.
#
# No problem, again! One tiny, simple utility class makes it easy...:
class DataHolder:
def __init__(self, value=None): self.value = value
def set(self, value): self.value = value; return value
def get(self): return self.value
# optional but handy, if you use this a lot, either or both of:
setattr(__builtins__,'DataHolder',DataHolder)
setattr(__builtins__,'data',DataHolder())
# and now, assign-and-set to your heart's content: rather than Pythonic
while 1:
line = file.readline()
if not line: break
process(line)
# or better in modern Python, but quite far from C-like idioms:
for line in file.xreadlines():
process(line)
# you CAN have your C-like code-structure intact in transliteration:
while data.set(file.readline()):
process(data.get())
Probably not exactly what you were thinking, but...
q = request.GET.get('q')
if q:
print q
this?
A variation on Alex's answer:
class DataHolder:
def __init__(self, value=None, attr_name='value'):
self._attr_name = attr_name
self.set(value)
def __call__(self, value):
return self.set(value)
def set(self, value):
setattr(self, self._attr_name, value)
return value
def get(self):
return getattr(self, self._attr_name)
save_data = DataHolder()
Usage:
if save_data(get_input()):
print save_data.value
or if you prefer an alternative interface:
if save_data.set(get_input()):
print save_data.get()
I would find this helpful to test a series of regular expressions in an if-elif-elif-elif etc construct, as in this SO question:
import re
input = u'test bar 123'
save_match = DataHolder(attr_name='match')
if save_match(re.search('foo (\d+)', input)):
print "Foo"
print save_match.match.group(1)
elif save_match(re.search('bar (\d+)', input)):
print "Bar"
print save_match.match.group(1)
elif save_match(re.search('baz (\d+)', input)):
print "Baz"
print save_match.match.group(1)
PEP 572 introduces Assignment Expressions. From Python 3.8 and onwards you can write:
if q := request.GET.get('q'):
print q
Here are some more examples from the Syntax and semantics part of the PEP:
# Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
# A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
process(chunk)
# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
q = request.GET.get('q')
if q:
print q
else:
# q is None
...
There's no way of doing assignment and conditionals in one go...
If get() throws an exception when it's not there, you could do
try:
q = request.GET.get('q')
print q
except :
pass
config_hash = {}
tmp_dir = ([config_hash[x] for x in ["tmp_dir"] if config_hash.has_key(x)] or ["tmp"])[0]
print tmp_dir
config_hash["tmp_dir"] = "cat"
tmp_dir = ([config_hash[x] for x in ["tmp_dir"] if config_hash.has_key(x)] or ["tmp"])[0]
print tmp_dir
a possible way to do it, without necessity to set the variable before, could be like:
if (lambda x: globals().update({'q':x}) or True if x else False)(request.GET.get('q')):
print q
.. it's just for fun - this method should not be used, because it is ugly hack, difficult to understand at first sight, and it creates/overwrites a global variable (only if the condition is met, though)
Well, this would be one way
q = request.GET.get('q')
if q:
print q
A briefer (but not superior, due to the call to print of nothing) way would be
print request.GET.get('q') or '',
Simply try:
print(request.GET.get('q', ''))
which basically prints nothing if the first argument is not present (see dict.get).
Alternative solution would be to use a conditional expression in Python:
<expression1> if <condition> else <expression2>
but you'll end up repeating variable twice, for example:
print(request.GET.get('q') if request.GET.get('q') else '')
For variable assignments in loops, check in here.

Categories