Is there a Python equivalent of the C# null-coalescing operator?
other = s or "some default value"
Ok, it must be clarified how the or
operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.
Note that the or
operator does not return only True
or False
. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.
In this case, the expression x or y
returns x
if it is True
or evaluates to true when converted to boolean. Otherwise, it returns y
. For most cases, this will serve for the very same purpose of C♯'s null-coalescing operator, but keep in mind:
42 or "something" # returns 42
0 or "something" # returns "something"
None or "something" # returns "something"
False or "something" # returns "something"
"" or "something" # returns "something"
If you use your variable s
to hold something that is either a reference to the instance of a class or None
(as long as your class does not define members __nonzero__()
and __len__()
), it is secure to use the same semantics as the null-coalescing operator.
In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None
specifically (an error object, for example).
In some languages this behavior is referred to as the Elvis operator.
Python's equivalent to null-conditional operator introduced in C# 6
How about:
s = sb and sb.ToString()
The short circuited Boolean stops if sb is Falsy, else returns the next expression.
Btw, if getting None is important...
sb = ""
#we wont proceed to sb.toString, but the OR will return None here...
s = (sb or None) and sb.toString()
print s, type(s)
output:
None <type 'NoneType'>
Python's equivalent to PHP's null coalesce operator and shorthand ternary operator?
The or
operator returns the first truth-y value.
a = 0
b = None
c = 'yep'
print(a or 'nope')
print(b or 'nope')
print(c or 'nope')
print(b or c or 'nope')
> nope
> nope
> yep
> yep
Is there a Python equivalent to the C# ?. and ?? operators?
No, Python does not (yet) have NULL-coalescing operators.
There is a proposal (PEP 505 – None-aware operators) to add such operators, but no consensus exists wether or not these should be added to the language at all and if so, what form these would take.
From the Implementation section:
Given that the need for None -aware operators is questionable and the spelling of said operators is almost incendiary, the implementation details for CPython will be deferred unless and until we have a clearer idea that one (or more) of the proposed operators will be approved.
Note that Python doesn't really have a concept of null
. Python names and attributes always reference something, they are never a null
reference. None
is just another object in Python, and the community is reluctant to make that one object so special as to need its own operators.
Until such time this gets implemented (if ever, and IronPython catches up to that Python release), you can use Python's conditional expression to achieve the same:
mass = 150 if vehicle is None or vehicle.Mass is None else vehicle.Mass / 10
None propagation in Python chained attribute access
No. There is a PEP proposing the addition of such operators but it has not (yet) been accepted.
In particular, one of the operators proposed in PEP 505 is
The "
None
-aware attribute access" operator?.
("maybe dot") evaluates the complete expression if the left hand side evaluates to a value that is notNone
Python version of C#'s conditional operator (?)
Yes, you can write:
trait = self.trait if self.trait == self.spouse.trait else defaultTrait
This is called a Conditional Expression in Python.
Ignore IndexError in python (Something like null coalescing operator on list subscription)
Unsure whether this is really pythonic, but you could extend sys.argv
with an array containing None
and slice it. Then you just have to test the values against None
:
input, output = (sys.argv + [None] * 2)[:2]
if input is None: input = defaultValue1
if output is None: output = defaultValue2
Or in a one liner:
defaultValues = [defaultValue1, defaultValue2]
input, output = (val if val is not None else defaultValues[i]
for i, val in enumerate((sys.argv + [None] * 2)[:2]))
Close to a matter of taste...
The null-coalescing operator and throw
According to https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.0/throw-expression
a throw expression consists of the throw keyword followed by a null_coalescing_expression where the null_coalescing_expression
must denote a value of the class type System.Exception, of a class
type that derives from System.Exception or of a type parameter type
that has System.Exception (or a subclass thereof) as its effective
base class. If evaluation of the expression produces null, a
System.NullReferenceException is thrown instead
return name ?? throw;
does not satisfy this condition as only the throw expression would be allowed here, not a throw statement.
At least that's how I read this.
Related Topics
How to Install Pil with Pip on MAC Os
Tensorflow Different Ways to Export and Run Graph in C++
Display a 'Loading' Message While a Time Consuming Function Is Executed in Flask
Scrape Multiple Pages with Beautifulsoup and Python
How to Generate an HTML Directory List Using Python
Python Beautifulsoup Iframe Document HTML Extract
Django: How to Serve Media/Stylesheets and Link to Them Within Templates
Is This Bad Programming Practice in Tkinter
How to Rotate the Sprite and Shoot the Bullets Towards the Mouse Position
How to Check If Any Value Is Nan in a Pandas Dataframe
Styling Multi-Line Conditions in 'If' Statements
Python Locale Error: Unsupported Locale Setting
Asynchronous Method Call in Python
How to Serve Multiple Clients Using Just Flask App.Run() as Standalone