Python ensure function parameter is always a string

Question:

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.

Asked By: Sytze

||

Answers:

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.

Answered By: SultanOrazbayev