alexgolec
alexgolec

Reputation: 28262

Is it good form to have an __init__ method that checks the type of its input?

I have a class that wants to be initialized from a few possible inputs. However a combination of no function overloading and my relative inexperience with the language makes me unsure of how to proceed. Any advice?

Upvotes: 1

Views: 3404

Answers (4)

Steven Rumbalski
Steven Rumbalski

Reputation: 45552

Contrary to what others have answered, it's not rare to check for types in __init__. For example the array.array class in the Python Standard library accepts an optional initializer argument, which may be a list, string, or iterable. The documentation explicitly states different actions take place based on the type. For another example of the same treatment by argument type see decimal.Decimal. Or see zipfile.Zipfile, which accepts a file argument "where file can be either a path to a file (a string) or a file-like object." (Here we see both explicit type checking (a string) and duck typing (a file-like object) all in one!)

If you find explicit type checking in __init__ is getting messy, try a different approach. Use factory functions instead. For example, let's say you have a triangle module with a Triangle class. There are many ways to construct a triangle. Rather than having __init__ handle all these ways, you could add factory methods to your module:

  • triangle.from_sas(side1, angle, side2)
  • triangle.from_asa(angle1, side, angle2)
  • triangle.from_sss(side1, side2, side3)
  • triangle.from_aas(angle1, angle2, side)

These factory methods could also be rolled into the Triangle class, using the @classmethod decorator. For an excellent example of this technique see Thomas Wouter's fine answer to stackoverflow question overloading init in python.

Upvotes: 2

Zeke
Zeke

Reputation: 2042

Check out this question asked earlier.

In short, the recommendation is that you use classmethods or isinstance(), with classmethods being heavily favored.

Upvotes: 4

user225312
user225312

Reputation: 131747

No, don't check for types explicitly. Python is a duck typed language. If the wrong type is passed, a TypeError will be raised. That's it. You need not bother about the type, that is the responsibility of the programmer.

Upvotes: 1

Chris Morgan
Chris Morgan

Reputation: 90852

With Python, you should use duck typing. Wikipedia has a good section on its use in Python at http://en.wikipedia.org/wiki/Duck_typing#In_Python

Upvotes: 3

Related Questions