Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python || backup statement

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
like image 503
Artur Sapek Avatar asked Oct 23 '11 22:10

Artur Sapek


3 Answers

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.

like image 198
Raymond Hettinger Avatar answered Nov 07 '22 22:11

Raymond Hettinger


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.

like image 33
millimoose Avatar answered Nov 07 '22 20:11

millimoose


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.

like image 38
ekhumoro Avatar answered Nov 07 '22 21:11

ekhumoro