0

Problem

Imagine I have a base class, e.g. TreeNode with several subclasses deriving from it, possibly with more instance fields (like children for inner nodes). What are current best practices to check against the concrete class Type. I may have something like NumericNode and CharacterNode and a function that accepts both.

Solutions

One possibility would be of course to use isinstance() but I think this is rather unpythonic. Another solution (which I would like to avoid as much as possible) is to use something like a class constant per subclass and then check against it. This would be similar to the first solution. Or should I encapsulate the isinstance() solution into a dedicated function that hides the real typechecking?

Community
  • 1
  • 1
teekay
  • 183
  • 1
  • 12
  • 1
    Why does your function need to care which it gets? Python generally used *"duck typing"*, relying on the *interface* to be correct (assuming it is and throwing an error if it isn't) rather than explicit, up-front checking of types. – jonrsharpe Jun 06 '16 at 20:49
  • Seems like you're designing your classes wrong. It sounds like you need common method names with each subclass overriding to implement however is appropriate for that type. – Two-Bit Alchemist Jun 06 '16 at 20:52
  • if you really want to enforce the type without lots of explicit checking in your function you could always use [this recipe for enforcing types in annotations](http://stackoverflow.com/a/21806460/5827215) – Tadhg McDonald-Jensen Jun 06 '16 at 21:19

0 Answers0