Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python equivalent to the C# ?. and ?? operators?

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

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

to set mass to a tenth of the vehicle's mass if there is a vehicle, but 150 if the vehicle is null (or has a null mass, if the Mass property is of a nullable type).

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

This would be particularly useful for displaying defaults for values that can be modified by other values - for instance, I might have an armor component defined in script for my starship that is always consumes 10% of the space available on the ship it's installed on, and its other attributes scale as well, but I want to display defaults for the armor's size, hitpoints, cost, etc. so you can compare it with other ship components. Otherwise I might have to write a convoluted expression that does a null check or two, like I had to in C# before v6.

like image 656
ekolis Avatar asked Sep 16 '16 15:09

ekolis


People also ask

Can Python be used instead of C?

Difference Between C and Python. The main difference between C and Python is that, C is a structure oriented programming language while Python is an object oriented programming language. In general, C is used for developing hardware operable applications, and python is used as a general purpose programming language.

What is C in Python?

The C function always has two arguments, conventionally named self and args. The self argument points to the module object for module-level functions; for a method it would point to the object instance. The args argument will be a pointer to a Python tuple object containing the arguments.


1 Answers

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
like image 108
Martijn Pieters Avatar answered Sep 28 '22 05:09

Martijn Pieters