-
Piotr Maślanka authored5f43d423
decorators.rst 2.22 KiB
Decorators
A functools.wraps()
equivalent, but for classes
Preconditions and postconditions
Sometimes you need to specify conditions that parameter to your function will need to obey. You can use the following decorator for this:
And here are some helper functions for it:
has_keys asserts that a dictionary has all the keys necessary.
Use it like this:
>>> @precondition(has_keys(['a', 'b'])) >>> def function(keys): >>> ... >>> function({'a': 5, 'b': 3}) >>> self.assertRaises(PreconditionError, lambda: function({'a': 5}))
short_none is particularly useful with preconditions, or functions that accept a None value as well.
Example:
>>> @precondition(short_none('x == 2')) >>> def expect_two(x): >>> ... >>> expect_two(None) >>> expect_two(2) >>> self.assertRaises(PreconditionError, lambda: expect_two(3))
You can also check the return value with