Search code examples
pythonvalidationanti-patterns

How to avoid circular dependencies in validation module


I recently refactored my code to put input validation methods that are shared among several classes in their own module, validate.py. Some of these validation methods check if their input is an instance of a class, e.g. MyClass. Therefore validate.py must import MyClass so it's method is_MyClass can check if isinstance(input, MyClass). But, I want to use some validation methods from validate.py in MyClass to sanitize input to MyClass.my_method, so MyClass must import validate.py.

Something tells me I just casually refactored my way into an anti-pattern. If what I'm trying to do implies circular dependencies, then I must be Doing It Wrong™.

But, code reuse is a good idea. So what's the best practice for sharing validation methods in this way?


Solution

  • I think the parts of the validation code that are specific to one of the classes should probably be put into the class itself - maybe as a classmethod? That way the 'generic' validation code can just call obj.validate() at the appropriate time. You then don't need to import the classes from the generic validation code.