Sep-07-2020, 03:36 PM
Not least because in reality, those function calls may be expensive or have some side effect somewhere (writing to a database for example) that you only really want to do when you need to.
|
[split] Creating a variable as a function
|
|
Sep-07-2020, 03:36 PM
Not least because in reality, those function calls may be expensive or have some side effect somewhere (writing to a database for example) that you only really want to do when you need to.
Sep-07-2020, 03:55 PM
You prefer it like i implemented it in post # 1 ?
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Sep-07-2020, 04:57 PM
it's not a matter of preference. the point is to NOT execute all functions while creating the dict
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link Create MCV example Debug small programs
Sep-07-2020, 05:20 PM
Like so:
#the functions
def AAA():
return 'AAA'
def BBB():
return 'BBB'
def ELSE():
return 'UNKNOWN'
# ---------------------------
#(1)single key dict with default
def switcher1(k):
myDict = {100:AAA,200:BBB}
return myDict.get(k, ELSE)
print(switcher1(200)())
print(switcher1(502)())
# -----------------------------
#(2)tuple with (optional) multiple keys and default
def switcher2(k):
myDict2 = {('a'):AAA, ('x', 'y', 'z'):BBB}
myDict2 = {key:value for item, value in myDict2.items() for key in item}
return myDict2.get(k, ELSE)
print(switcher2('z')())
print(switcher2('M')())
# --------------------------------
#(3) range dict with default
from range_key_dict import RangeKeyDict
def switcher3(k):
myDict3 = RangeKeyDict({(0,100): AAA,(101,200): BBB})
return myDict3.get(k, ELSE)
print(switcher3(152)())
print(switcher3(5210)())Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'. |
|
|