3

Why doesn't Python have switch-case or overloading??

Comments
  • 2
    A switch in Python is a function with values mapped to a function.
  • 4
    Overloading: This is a little bit "inconvenient" in a dynamic typed language.

    But you can build it yourself by using *args or **kwargs or by setting default values.
  • 3
    Two reasons:
    1. Dynamic languages have problem with overloading since you have no way to actually know if you want to overload or override.
    2. Its part of the python philosophy of "explicit is better than implicit"- if you want 2 functions you can go the extra mile and describe the difference between them (though I do not 100% agree with this specific part)
  • 1
    A switch case would be a dict of cases and functions to be called... It is not so elegant, but may look better than if-elif-else sometimes.
    Example:

    def foo():
    ...

    def bar():
    ...

    def default():
    ...

    {1:foo, 2:bar}.get(some_value, default)()
Add Comment