In Javascript, I can assign a value like this so:
var i = p || 4
Obviously if p isn't defined it will resort to 4. Is there a more elegant version of this operation in Python than a try:
/ except:
combo?
try:
i = p
except:
i = 4
People sometime use Python's or-operator for this purpose:
def f(p=None):
i = p or 4
...
The relies on a "unique to Python" aspect of the or-operator to return the value that makes the expression true (rather than just returning True or False).
Another option that affords more flexibility is to use a conditional expression:
def f(p=None):
i = p if p is not None else 4
...
If you just want to check to see if a variable is already defined, a try/except is the cleanest approach:
try:
i = p
except NameError:
pass
That being said, this would be atypical for Python and may be a hint that there is something wrong with the program design.
It is better to simply initialize a variable to a place-holder value such as None. In this regard, Python's style is somewhat different from Javascript.
You could use i = locals().get('p', 4)
, but I strongly recommend against it. Structure your code so you don't need to refer to variables that might or might not be there.
The only instance where I use this pattern in Javascript is to fake namespaces with global objects when I don't want to depend on my script files being included in the right order. Since Python has a proper module system, I can't imagine where this would be necessary.
You could ensure that p
is initialized to a sentinel value (usually None
) and then test for its presence:
p = None
...
i = p if p is not None else 4
This is necessary because Python has no way to define variables without assigning to them first. In Javascript, a variable can be declared with e.g. var p;
and until it is assigned to, it will evaluate to the special value undefined
.
So with Javascript, a sentinel value can be implicitly created, whilst with Python it must always be explicitly created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With