Is there a Python equivalent for C #? and?? operators?

For example, in C # (starting with v6) I can say:

mass = (vehicle?.Mass / 10) ?? 150; 

to set the mass to a tenth of the mass of the vehicle if there is a vehicle, but 150 if the vehicle has a zero value (or has zero mass if the Mass property is of type with a zero value).

Is there an equivalent construct in Python (specifically IronPython) that I can use in scripts for my C # application?

This would be especially useful for displaying default values ​​for values ​​that can be changed by other values ​​- for example, I can have an armored component defined in a script for my starship that always consumes 10% of the space available on put it on and others its attributes, but I want to display the default values ​​for armor size, hitpoints, cost, etc., so that you can compare it with other components of the ship. Otherwise, I may have to write a convoluted expression that does a null check or two, as I should have in C # before v6.

+7
python ironpython
source share
1 answer

No, Python does not yet have NULL-coalescing statements.

There is a proposal ( PEP 505 - Non-Key Operators ) to add such operators, but consensus does not exist or not. They should be added to the language in everything, and if so, in what form they will be.

In the "Implementation" section:

Given that the need for None -aware statements is doubtful, and writing these statements is almost incendiary, implementation details for CPython will be deferred until we get a clearer idea that one (or more) of the proposed operators will be approved.

Note that Python really has no null concept. Python names and attributes always refer to something; they are never a null reference. None is another Python object, and the community is reluctant to make this object so special that it needs its own operators.

Until this is implemented (if ever, and IronPython catches up with this version of Python), you can use the Python conditional expression to achieve the same:

 mass = 150 if vehicle is None or vehicle.Mass is None else vehicle.Mass / 10 
+11
source share

All Articles