3

I'm trying to make a program with a function that only accepts strings. How can I make a python function parameter always be a string and throw an error if it's not?

I'm looking for something like:

def foo(i: int): 
       return i  
foo(5) 
foo('oops')

Except this does not throw an error.

SultanOrazbayev
  • 14,900
  • 3
  • 16
  • 46
Sytze
  • 39
  • 1
  • 10
  • 1
    Does this answer your question? [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python) – luk2302 Mar 20 '22 at 17:24
  • the example I used is from there all it just doesn't give me an error – Sytze Mar 20 '22 at 18:17

1 Answers1

5

A very basic approach could be to check if the parameter is an instance of str:

def f(x):
   assert isinstance(x, str), "x should be a string"
   # rest of the logic

If run-time checking is not required, then another way to implement this is to add type-hinting with subsequent checking using mypy. This would look like this:

def f(x: str) -> str:
   # note: here the output is assumed to be a string also

Once the code with type-hints is ready, one would run it through mypy and inspect for any possible errors.

More advanced ways around this would include defining a specific class that incorporates the assertion (or enforces type by trying to convert the input), or using some third-party libraries: one that comes to mind is param, but surely there are others.

SultanOrazbayev
  • 14,900
  • 3
  • 16
  • 46