1

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?

3
  • 1
    There's no particular reason you can't - unittest has a number of wrappers like assertEqual. It depends what makes your code most readable. Commented May 28, 2012 at 17:19
  • 2
    Faster? Faster to type, sure. Slower to execute, obviously, since there's an extra function call involved. Commented May 28, 2012 at 17:20
  • 3
    I agree with @ThomasK, I see no problem. As for the speed, I think that should be negligible in most cases (in spite of the theoretical difference pointed out by @kindall), depending on how often you execute this code. Commented May 28, 2012 at 17:24

1 Answer 1

2

The last line will raise NameError unless changed to

self.assert_foo('doo')

That aside, I do not think assert should be used in the above code with or without the wrapper. The corrected line only checks that self has .foo_doo set, but not that it is not None.

if self.foo_doo is not None:

does both.

If one wants an abbreviated look-first attribute check, one could write

def has_foo(self, name):
    return hasattr(self, 'foo_'+name)

def foobar(self):
    if has_foo('doo'):

If you also want a non-None check, change the has_foo return to:

return getattr(self, 'foo_'+name, None) is not None 

Beyond this, assert in 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__ sets self.foo_doo to 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.assertXxx methods of unittest are only used for testing, and when they fail, they do more than just wrap a simple assert.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.