Python Forum
[split] Creating a variable as a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] Creating a variable as a function
#11
For the "select...case" enthousiasts we have now 1 direct solution
and 2 workarounds, that should satisfy 90% of the needs.
Of course if you need a mix of the 3 , you'll need to be creative.

Great help, appreciate it,
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'.
Reply
#12
note that these are jut sample implementations, e.g. in certain cases bisect module can be useful and allow for different implementation, see Other examples section.
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

Reply
#13
You can create an array of functions and call the selected one based on a calculation, but if you are looking at 50 different functions to select from I would suspect there is a better approach.
Reply
#14
Also, if you want to dispatch to a function based on type of argument, there's singledispatch in the functools module: https://docs.python.org/3/library/functo...ledispatch
Reply
#15
After having tested the proposed solutions, i have to curb my
"90%" enthousiasm a little.

All solutions work if you provide an argument that has been "foreseen",
like in a menu system.

But all select...case constructs end with the "case else.." , the alternative for the non-explicitely mentioned values.
I don't see any other solution then a try...except clause, with the risk of not being able to differentiate
between a genuine "bug" or an unexpected value.

All this puzzels me, and there must be some site when you can recommend "improvements" to python.
I'm interested in the historical records, to see if some form of select case has been proposed, and why it's absent.
Maybe it's in the "pipeline" :-)
Paul

"PEP" is what i was looking for, but i did not get any wiser.
Anyway:

There seems to be a solution for the "switch case" or "select case" construction that provides a
"case else" or a "default:
https://data-flair.training/blogs/python-switch-case/

Does not take away that you always find "partial" solutions, and not a generic python solution,
so you can mix single, multiple and range arguments;

I immediately add that single and multiple arguments, such as posts #3 and #8 are possible
because you can use #8 with just 1 value in the tuple. Looks a bit strange, but it works.

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'.
Reply
#16
It is in fact in the pipeline for consideration. The currently open version is PEP 622.

Rejected proposals from the past include PEP 3103 and PEP 275.
Reply
#17
(Sep-07-2020, 07:54 AM)bowlofred Wrote: It is in fact in the pipeline for consideration. The currently open version is PEP 622.

Rejected proposals from the past include PEP 3103 and PEP 275.
Thanks for the info!

Wow, just a few weeks ago !
Output:
This general idea has been floating around for a pretty long time, and many back and forth decisions were made.
Looks like a lot of work !
I keep thinking of my signature buddy, "Better is the enemy of good". Smile

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'.
Reply
#18
One more,just using some pre-made code for a rage dict.
Then use it in a way i like do switch case stuff in Python,so i think a reasonable clean and readable solution.
from range_key_dict import RangeKeyDict

def low():
    return 'Low range'

def med():
    return 'Medium range'

def high():
    return 'High range'

def switch_case(number):
    r_dict =  RangeKeyDict({
        (0, 332): low(),
        (333, 665): med(),
        (666, 1000): high(),
    })
    return r_dict.get(number, f'<{number}> Not in any range')

number = int(input("Enter a number between 1 and 1000: "))
print(switch_case(number))
Output:
Enter a number between 1 and 1000: 50 Low range Enter a number between 1 and 1000: 700 High range Enter a number between 1 and 1000: 5000 <5000> Not in any range
Reply
#19
With thanks to all the contributers, i made an overview of
some alternatives for a switch or select case construction.
This includes the "case else" or "default" option.
Note that alt 1 is in fact a simple case of alt 2.
Note that alternative 3 requires a pip install.
#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))
Can somebody write to PEP622 that they can save the time & effort. Cool

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'.
Reply
#20
I am afraid you don't understand the concept completly.
you must not execute all functions, when adding them to dict. note the difference between adding function as value in dict and adding the return value of the function. same for the default value/function
you want to return a function, not the result of it (which may well be None). @snippsat example may be misleading in that respect
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

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable for the value element in the index function?? Learner1 8 655 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 589 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,306 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  Function parameter not writing to variable Karp 5 948 Aug-07-2023, 05:58 PM
Last Post: Karp
  Split string using variable found in a list japo85 2 1,304 Jul-11-2022, 08:52 AM
Last Post: japo85
  Retrieve variable from function labgoggles 2 1,053 Jul-01-2022, 07:23 PM
Last Post: labgoggles
  Cant transfer a variable onto another function KEIKAS 5 1,902 Feb-09-2022, 10:17 PM
Last Post: deanhystad
  Please explain uncommon way of declaring and using variable [function.variable] esphi 4 2,341 Nov-07-2020, 08:59 AM
Last Post: buran
  Spyder Quirk? global variable does not increment when function called in console rrace001 1 2,231 Sep-18-2020, 02:50 PM
Last Post: deanhystad
  passing variable to function Rejoice 4 2,883 Sep-11-2020, 03:27 AM
Last Post: Pleiades

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020