|
|
|
|
|
by bad_user
5632 days ago
|
|
First, even in Java you don't know the return type / invariants ... int n = func_that_returns_positive_even_number()
What you need is to document the thing: def func_that_returns_positive_even_number():
"""Returns positive even number."""
This comment will be available when typing "help(func_that_returns_positive_even_number)" in the Python console btw.Or if you're paranoid and that function can totally break your code: n = func_that_returns_positive_even_number()
assert isinstance(n, int) and n % 2 == 0 and n >= 0
Or to make extra sure this will hold in the future (i.e. protecting from code-changes done by other people) ... import unittest
class TestMyFunc(unittest.TestCase):
def test_is_positive_and_even(self):
n = func_that_returns_positive_even_number()
self.assertTrue( n % 2 == 0 and n >= 0 )
|
|
This is a classic type system straw man. The language doesn't support encoding integer ranges in the type system, ergo, the type system is not ever a significant advantage and all invariants must be documented. You fool!
What you need is to document the thing:
Some invariants require further documentation. The more you can express concisely in code via the type system, the more time you and your API clients save in both development and maintenance.
More succinctly: By expressing them in code you let the compiler automate the work of enforcing them.
Or if you're paranoid and that function can totally break your code:
An assert doesn't "protect" your code from future changes (better phrasing would be: make your code adaptable to change, loosely coupled with its dependencies as to allow iteration of your code and its dependencies independently).
An assert simply causes your code to fail in an obvious way. It's still up to you to track them down (at runtime) and figure out where you went wrong.