PyWart: Language missing maximum constant of numeric types!

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 26 08:50:01 EST 2012


On 2012年2月26日 14:16:24 +0100, Wolfgang Meiners wrote:
> I just had a closer look at it. It seems to be more complicated than i
> thougth: You will have to write
>> def confine_length(string, maxlength=None):
> if maxlength: # maxlength exists, comparison possible
> if len(string) <= maxlength:
> do_something()
> else: # maxlength does not exist, so always do something
> do_something()

No, that still takes the wrong branch for maxlength = 0.
Be explicit in your code. If you want maxlength=None to be a sentinel for 
"avoid the length test", then explicitly test for maxlength is None, 
don't be tempted to take short-cuts that can fail.
def confine_length(string, maxlength=None):
 if maxlength is None: # no length comparison needed
 do_something()
 elif len(string) <= maxlength:
 do_something()
This can be simplified to:
def confine_length(string, maxlength=None):
 if maxlength is None or len(string) <= maxlength:
 do_something()
Or even simpler:
def confine_length(string, maxlength=float('inf')):
 if len(string) <= maxlength:
 do_something()
-- 
Steven


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /