Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

11
  • For now, this is the best approach in my experience. However, Mypy also supports structural subtyping via protocols since Python 3.8 (with backports to older versions available as a separate package). Commented Jul 5, 2020 at 19:44
  • @amon I'm not very familiar with mypy. may I ask what would it do in practice? could one simply use duck typing instead of defining interfaces left and right? Commented Jul 5, 2020 at 19:52
  • 1
    Duck typing is the classic “Pythonic” way but then you can't use type annotations. ABCs as in your answer is a common approach to make this type-checkable with mypy, and I have used exactly that strategy in the past. But since this in nominative typing, it is necessary to inherit from those ABCs. Protocols make it possible to do structural typing, i.e. something like static duck typing as in Typescript or Go. It's like defining an ABC, except that you don't have to inherit from it and only describe a type signature. Commented Jul 5, 2020 at 21:40
  • Hi @PedroRodrigues, thanks for your post! Since all my rules are completely different, I would define an separate interface for them, which kind of loses the meaning right? Also I don't really know how I can make the code which calls the rules feed the correct arguments (I can only think of if else statements) Commented Jul 6, 2020 at 7:23
  • 1
    My solution is exactly equal to what you are doing right now, the only difference is explicity (is that a word. In other words, I'm beeing explicit by declaring an interface, you are being implicit by using duck typing. Does interface segration result in more code than duck typing? Yes. Is that boilerplate code? maybe, in your case I would argue it is not. Python is not statically typing, so to fix the issue of devs using the wrong attributes from the parameters, you would need tests. Are tests boilerplate? I don't think so, so neither are my interfaces since they serve the exact same porpuse. Commented Jul 6, 2020 at 10:37