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.

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

is it also possible to do it in the rule that defines the function
as far as I understand, it's possible, but requires advanced syntax, so the link posted by @luk2302 is a good start.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.