Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of in ""? Membership testing empty string literal

Tags:

python

I stumbled upon this apparently horrific piece of code:

def determine_db_name():
    if wallet_name in "":
        return "wallet.dat"
    else:
        return wallet_name

What is supposed if xx in "": to mean? Doesn't it always evaluates to False?

like image 906
o0'. Avatar asked Apr 04 '13 13:04

o0'.


2 Answers

It'll return True if wallet_name is itself empty:

>>> foo = ''
>>> foo in ''
True

It is horrific though. Just use if not wallet_name: instead, or use or and do away with the if statement altogether:

def determine_db_name():
    return wallet_name or "wallet.dat"

which works because or short-circuits, returning wallet_name if it is not the empty string, otherwise "wallet.dat" is returned.

like image 190
Martijn Pieters Avatar answered Nov 15 '22 17:11

Martijn Pieters


That expression is true if wallet_name is the empty string.

It would probably be clearer if the code had been written as follows:

if wallet_name == '':

Or just:

if not wallet_name:
like image 25
Mark Byers Avatar answered Nov 15 '22 18:11

Mark Byers