0

Often times I find myself having to run different sections of functions depending on what custom type was passed in etc.

I regularly then use a string and test the current entity for it.

if type =='A':
    do_this
elif type = 'B':
    do_that

but that doesnt seem natural. What is the canonical way in Python to distinguish execution paths depending on the identity of entities? It does not feature a constexpr_if like C++ does

CD86
  • 979
  • 10
  • 27
  • are you looking something similar to switch case? – Debdut Goswami Dec 03 '19 at 13:34
  • "but that doesnt seem natural" -- why not? Python lacks a `switch` so an `if ... elif` structure is natural enough. In any event, perhaps this will help: [What's the canonical way to check for type in Python?](https://stackoverflow.com/q/152580/4996248) – John Coleman Dec 03 '19 at 13:35
  • 1
    You could use a mapping of the different functions according to the type of the input: `my_func = { int: do_this, float: do_that}` then `my_func[int](1)` – Jacques Gaudin Dec 03 '19 at 13:37
  • let me rephrase my problem. I have a custom class which implementation varies slightly (by means of if conditions within member functions) depending on its identity. Currently, I solve this by passing a string as one of its arguments to the classes__init__ function and check this string on several occasions. Is there a better way to do this? – CD86 Dec 03 '19 at 13:40
  • It's hard to give you an answer without a [mcve]. I was pointing out that although Python doesn't have switch cases, mappings (like `dict`) are the preferred way to achieve the same thing. – Jacques Gaudin Dec 03 '19 at 13:45
  • 1
    The question is somewhat vague and also opinion-based. What you could maybe do is write a short but non-trivial program which illustrates the pattern you are currently using, and then post it to [codereview.se]. That should get you the sort of feedback you are looking for. – John Coleman Dec 03 '19 at 13:45

0 Answers0