PyWart: Language missing maximum constant of numeric types!

Wolfgang Meiners WolfgangMeiners01 at web.de
Sun Feb 26 06:56:46 EST 2012


Am 25.02.12 18:54, schrieb MRAB:
>> If there is no limit for len(string), why not simply use
>>
>> # get_limit() returns None if there is no limit
>> maxlength = get_limit()
>> if maxlength and (len(string)<= maxlength):
>>      allow_passage()
>> else:
>>      deny_passage()
>>
> That should be:
> 
> if maxlength is not None and len(string) <= maxlength:

Take a look at

http://docs.python.org/library/stdtypes.html

where  you can read:
=========================================================================
Any object can be tested for truth value, for use in an if or while
condition or as operand of the Boolean operations below. The following
values are considered false:


      None

      False

      zero of any numeric type, for example, 0, 0L, 0.0, 0j.

      any empty sequence, for example, '', (), [].

      any empty mapping, for example, {}.

      instances of user-defined classes, if the class defines
      __nonzero__() or __len__() method, when that method returns the
      integer zero or bool value False. [1]

All other values are considered true — so objects of many types are
always true.
==========================================================================

That means:
if maxlength and (len(string) <= maxlength):

is equivalent to
if (maxlength is not None) and (len(string) <= maxlength):

which is more complicated to type and -in my opinion- not so intuitive.
But because it is equivalent, it is a matter of taste, what to use.

Wolfgang



More information about the Python-list mailing list