Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper python way to write methods that only take a particular type?

Tags:

python

I have a function that is supposed to take a string, append things to it where necessary, and return the result.

My natural inclination is to just return the result, which involved string concatenation, and if it failed, let the exception float up to the caller. However, this function has a default value, which I just return unmodified.

My question is: What if someone passed something unexpected to the method, and it returns something the user doesn't expect? The method should fail, but how to enforce that?

like image 949
alexgolec Avatar asked Nov 14 '10 21:11

alexgolec


2 Answers

It's not necessary to do so, but if you want you can have your method raise a TypeError if you know that the object is of a type that you cannot handle. One reason to do this is to help people to understand why the method call is failing and to give them some help fixing it, rather than giving them obscure error from the internals of your function.

Some methods in the standard library do this:

>>> [] + 1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate list (not "int") to list
like image 67
Mark Byers Avatar answered Oct 06 '22 12:10

Mark Byers


You can use decorators for this kind of thing, you can see an example here.

But forcing parameters to be of a specific type isn't very pythonic.

like image 43
Vincent Savard Avatar answered Oct 06 '22 13:10

Vincent Savard