What is the correct way for python to write methods that accept only a specific type?

I have a function that should take a string, if necessary add things there and return the result.

My natural incline is simply returning a result related to string concatenation, and if that fails, let the exception pop up to the caller. However, this function has a default value, which I simply return unchanged.

My question is: what if someone passed something unexpected to the method and it returns something that the user does not expect? The method should fail, but how to do it?

+5
source share
4 answers

, , TypeError, , , . - , , , .

:

>>> [] + 1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate list (not "int") to list
+5

, .

.

+2

Python , , . , , , :

def foo(arg):
    try:
        return arg + "asdf"
    except TypeError:
        return arg
+1

? , , ? :

def yourFunc( foo ):
    try:
        return foo + " some stuff"
    except TypeError:
        return "default stuff"

Space_C0wb0y , arg unmodified, , - :

def yourFunc2( bar ):
    return str(bar) + " some stuff"

.

0

All Articles