So I came across this interesting problem while reviewing code:
class Foo:
def __init__(self, foo_name):
self.foo_doo = getattr(foo_name, 'foo_lists', None)
def assert_foo(self, varname):
assert hasattr(self, 'foo_%s' % varname)
def foobar(self):
assert_foo('doo')
Wonder if wrapping assert to a customized version of your own is faster/better solution then using assert hasattr(...) everytime you need to make sure the attribute is present and not None?
The last line will raise
NameErrorunless changed toThat aside, I do not think
assertshould be used in the above code with or without the wrapper. The corrected line only checks thatselfhas.foo_dooset, but not that it is notNone.does both.
If one wants an abbreviated look-first attribute check, one could write
If you also want a non-
Nonecheck, change thehas_fooreturn to:Beyond this,
assertin production code should only be used to check internal logic and not runtime conditions affected by users of the code. Users can delete or disable assertions, so code should not depend on assert for its proper operation once released.In the code above,
__init__setsself.foo_dooto something, but the caller can subsequently delete the attribute. So both the existence and value of the attribute are user-determined run time conditions and not appropriate subjects for assertions.The
TestCase.assertXxxmethods ofunittestare only used for testing, and when they fail, they do more than just wrap a simpleassert.