Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #82437

Re: is_<whatever_you_are_testing_for> as method or property?

References <CABUeae-rNeN_dGgkgauNr+-qChXvkgenBmgLbFioe+JDqiT+Hg@mail.gmail.com> <CAPTjJmojWeyB_bv-6Rjzkno6Cb7NiUKo7rt4Th6fvNPOsGv_jQ@mail.gmail.com>
From Mateusz Loskot <mateusz@loskot.net>
Date 2014-12-12 12:21 +0100
Subject Re: is_<whatever_you_are_testing_for> as method or property?
Newsgroups comp.lang.python
Message-ID <mailman.16903.1418383298.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 11 December 2014 at 19:20, Chris Angelico <rosuav@gmail.com> wrote:
> On Fri, Dec 12, 2014 at 4:34 AM, Mateusz Loskot <mateusz@loskot.net> wrote:
>> If a class member function simply tests something and
>> returns a b::oolean call it
>>
>> def is_<whatever_you_are_testing_for>():
>>  pass
>>
>> like 'is_even'.
>>
>> Should I define it as a classic method
>>
>> def is_even(self):
>>     pass
>>
>> or as a property
>>
>> @property
>> def is_even(self):
>>     pass
>
> A property should be used if what you're creating is "virtually an
> attribute". If it would make sense to have an attribute is_even, then
> a property is_even makes sense. If in doubt, go with a method.

Thanks for the advise.

I've got several cases which are not obvious to me.
For instance, class Foo has a boolean attribute, read-write,
which I see a couple of realisations for possible:

1) properties only
class Foo:
  @property
  def is_default(self):
    pass

  @is_default.setter
  def is_default(self, current):
    pass

2) property + method mix
class Foo:
  @property
  def is_default(self):
    pass

  def make_default(self, current):
    pass

3) methods only
class Foo:
  def is_default(self):
    pass

  def make_default(self, current):
    pass

>From one angle, that is is_default is known and does not need to be
calculated upon every query, the option 1) fits well.
It is aligned with Ethan's suggestion in the other post.

>From other point, let's assume updating it takes a little bit of changes of
state of Foo instance, then perhaps methods-only option 3) fits best.

Looks like "if in doubt, go with a method" is the safest bet.
'Statistics' from Python codebase also seem to suggest that.

Best regards,
-- 
Mateusz  Loskot, http://mateusz.loskot.net

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: is_<whatever_you_are_testing_for> as method or property? Mateusz Loskot <mateusz@loskot.net> - 2014-12-12 12:21 +0100

csiph-web