0

I need to force function inputs to take specific values. Without writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ?

def product(product_type = ['apple','banana']):
    print(product_type)

But the function requires product_type as single string (product('apple') or product('banana')), and gives error when typed different values.

  • 3
    Try [Enum](https://docs.python.org/3/library/enum.html) – Yevhen Kuzmovych Nov 14 '22 at 11:33
  • 2
    "*Without writing if, else blocks inside the function*" Why? (I'm asking in case this is an XY problem and you are trying to solve the wrong problem.) – Gino Mempin Nov 14 '22 at 11:33
  • 2
    Also, does this answer your question? [Pythonic way to have a choice of 2-3 options as an argument to a function](https://stackoverflow.com/questions/9522877/pythonic-way-to-have-a-choice-of-2-3-options-as-an-argument-to-a-function) – Yevhen Kuzmovych Nov 14 '22 at 11:34
  • 1
    Also, not directly related to your question, note that using mutable default arguments may have unexpected behaviour - check ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/q/1132941/4046632) – buran Nov 14 '22 at 11:35
  • @buran I believe this is just a pseudocode (kinda) and `product_type` is not a `list`. So this is unrelated and might confuse the OP. – Yevhen Kuzmovych Nov 14 '22 at 11:36
  • 1
    @YevhenKuzmovych, I agree, but word of caution is warranted in my opinion, I edited my comment to be more clear in that respect – buran Nov 14 '22 at 11:38
  • You can specify this via type annotations, using `Enum` or `Literal`. Then you run https://mypy.readthedocs.io/en/stable/ to check the annotations. It's a lot like using a compiled language - pretend that mypy is your compiler and pretend that any errors it raises means your code "didn't compile" and therefore you shouldn't run it. – Anentropic Nov 14 '22 at 11:39

1 Answers1

1

Without writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ?

Not really.

You can use typing with an Enum or a Literal but that assumes a type checker is actually being run on the codebase in all cases.

Python is otherwise dynamically, it will not normally validate parameters, if you need that you must do it internally. Though you do not need an if: else: block inside the function, you can just use an assertion:

def product(product_type: Literal['apple', 'banana']):
    assert product_type in ['apple','banana']
    print(product_type)

This way the input will be

  1. actually checked at runtime
  2. documented for IDEs and friends
  3. optionally checked at compile-time
Masklinn
  • 34,759
  • 3
  • 38
  • 57