FAQ
I get sick and tired of doing this!!!

if maxlength == UNLIMITED:
allow_passage()
elif len(string) > maxlength:
deny_passage()

What Python needs is some constant that can be compared to ANY numeric
type and that constant will ALWAYS be larger!

Search Discussions

  • Mark Lawrence at Feb 24, 2012 at 1:55 pm

    On 24/02/2012 13:37, Rick Johnson wrote:
    I get sick and tired of doing this!!!

    if maxlength == UNLIMITED:
    allow_passage()
    elif len(string)> maxlength:
    deny_passage()

    What Python needs is some constant that can be compared to ANY numeric
    type and that constant will ALWAYS be larger!

    Do you want to test for something that is larger than infinity?

    --
    Cheers.

    Mark Lawrence.
  • Rick Johnson at Feb 24, 2012 at 2:14 pm

    On Feb 24, 7:55?am, Mark Lawrence wrote:
    Do you want to test for something that is larger than infinity?
    Not exactly. I want to set a constant that has a value of infinity and
    then do comparisons against the constant.

    ##################
    # Hypothetical 1 #
    ##################

    def confine(string, maxlength=INFINITY):
    return string[:maxlength]

    py> confine('123')
    '123'
    py> confine('123', 1)
    '1'

    ##################
    # Hypothetical 2 #
    ##################

    def confine(string, maxlength=INFINITY):
    if len(string) < maxlength:
    do_something()
    else:
    twiddle_thumbs()
  • Neil Cerutti at Feb 24, 2012 at 2:25 pm

    On 2012-02-24, Rick Johnson wrote:
    I get sick and tired of doing this!!!

    if maxlength == UNLIMITED:
    allow_passage()
    elif len(string) > maxlength:
    deny_passage()

    What Python needs is some constant that can be compared to ANY
    numeric type and that constant will ALWAYS be larger!
    What's the point of that?

    The only time I've naively pined for such a thing is when
    misapplying C idioms for finding a minimum value.

    Python provides an excellent min implementation to use instead.

    --
    Neil Cerutti
  • Rick Johnson at Feb 24, 2012 at 3:25 pm

    On Feb 24, 8:25?am, Neil Cerutti wrote:

    What Python needs is some constant that can be compared to ANY
    numeric type and that constant will ALWAYS be larger!
    What's the point of that?

    The only time I've naively pined for such a thing is when
    misapplying C idioms for finding a minimum value.
    The best use case is for default arguments to constructors or func/
    meths. If you set the argument to INFINITY instead of -1 (or some
    other dumb string value to mean "unlimited") you can omit a useless
    conditional block later. Observe:

    if maxlength == -1 # unlimited length:
    keep_going()
    elif len(object) < maxlength:
    stop() # because we reached the limit

    I see tons and tons of old Python code that uses -1 as an "unlimited"
    value, where positive numbers are meant to constrain dome value. I
    have always found that to be intuitive; hence my question.
  • Devin Jeanpierre at Feb 24, 2012 at 5:32 pm

    On Fri, Feb 24, 2012 at 9:25 AM, Neil Cerutti wrote:
    The only time I've naively pined for such a thing is when
    misapplying C idioms for finding a minimum value.

    Python provides an excellent min implementation to use instead.
    min can be a little inconvenient. As soon as anything complicated has
    to be done during the min expression, you need to switch to using
    something else for sanity's sake. In that vein, I do actually
    sometimes use float('inf') (for numbers), or a custom max/min object.

    ----

    Silly and completely nonserious addendum:

    Forgive me, I have spoken in error! min is the one true way, for you
    can still do it with a little wrangling, as follows:

    @operator.itemgetter(1)
    @min
    @apply
    def closest_object():
    for x in xrange(board_width)
    for y in xrange(board_height):
    try:
    entity = board.get_entity(x, y)
    except EntityNotFound:
    pass
    else:
    yield distance(player.pos, entity.pos), entity


    Please don't kill me.

    -- Devin
  • Ian Kelly at Feb 25, 2012 at 1:26 am

    On Fri, Feb 24, 2012 at 10:32 AM, Devin Jeanpierre wrote:
    On Fri, Feb 24, 2012 at 9:25 AM, Neil Cerutti wrote:
    The only time I've naively pined for such a thing is when
    misapplying C idioms for finding a minimum value.

    Python provides an excellent min implementation to use instead.
    min can be a little inconvenient. As soon as anything complicated has
    to be done during the min expression, you need to switch to using
    something else for sanity's sake. In that vein, I do actually
    sometimes use float('inf') (for numbers), or a custom max/min object.

    ----

    Silly and completely nonserious addendum:

    Forgive me, I have spoken in error! min is the one true way, for you
    can still do it with a little wrangling, as follows:

    ? ?@operator.itemgetter(1)
    ? ?@min
    ? ?@apply
    ? ?def closest_object():
    ? ? ? ?for x in xrange(board_width)
    ? ? ? ? ? ?for y in xrange(board_height):
    ? ? ? ? ? ? ? ?try:
    ? ? ? ? ? ? ? ? ? ?entity = board.get_entity(x, y)
    ? ? ? ? ? ? ? ?except EntityNotFound:
    ? ? ? ? ? ? ? ? ? ?pass
    ? ? ? ? ? ? ? ?else:
    ? ? ? ? ? ? ? ? ? ?yield distance(player.pos, entity.pos), entity
    Cute, but what's so terrible about:

    def all_entities():
    for x in xrange(board_width):
    for y in xrange(board_height):
    try:
    yield board.get_entity(x, y)
    except EntityNotFound:
    pass

    closest_object = min(all_entities,
    key=lambda e: distance(player.pos, e.pos))

    Especially given that all_entities should be reusable in other contexts.

    Cheers,
    Ian
  • Miki Tebeka at Feb 24, 2012 at 2:39 pm
    float('infinity') should be good enough.
  • Rick Johnson at Feb 24, 2012 at 3:18 pm

    On Feb 24, 8:39?am, Miki Tebeka wrote:
    float('infinity') should be good enough.
    Yes, that is the answer however the implementation is inconsistent.

    py> float("inf")
    inf
    py> float("infinity")
    inf
    py> int("inf")
    Traceback (most recent call last):
    File "<pyshell#2>", line 1, in <module>
    int("inf")
    ValueError: invalid literal for int() with base 10: 'inf'
    py> int("infinity")
    Traceback (most recent call last):
    File "<pyshell#3>", line 1, in <module>
    int("infinity")
    ValueError: invalid literal for int() with base 10: 'infinity'

    The best place for INFINITY is a constant of the math module.

    # Hypothetical #
    py> from math import INFINITY
    py> 1 < INFINITY
    True
    py> 99999999999999999 < INFINITY
    True
  • Mel Wilson at Feb 24, 2012 at 3:21 pm

    Rick Johnson wrote:

    I get sick and tired of doing this!!!

    if maxlength == UNLIMITED:
    allow_passage()
    elif len(string) > maxlength:
    deny_passage()

    What Python needs is some constant that can be compared to ANY numeric
    type and that constant will ALWAYS be larger!
    Easily fixed:



    class Greatest (object):
    def __cmp__ (self, other):
    if isinstance (other, Greatest):
    return 0
    return 1

    def __hash__ (self):
    return id (Greatest)

    class Least (object):
    def __cmp__ (self, other):
    if isinstance (other, Least):
    return 0
    return -1

    def __hash__ (self):
    return id (Least)



    Mel.
  • Steven D'Aprano at Feb 24, 2012 at 3:31 pm

    On Fri, 24 Feb 2012 10:21:45 -0500, Mel Wilson wrote:

    Rick Johnson wrote:
    I get sick and tired of doing this!!!

    if maxlength == UNLIMITED:
    allow_passage()
    elif len(string) > maxlength:
    deny_passage()

    What Python needs is some constant that can be compared to ANY numeric
    type and that constant will ALWAYS be larger!
    Easily fixed:



    class Greatest (object):
    def __cmp__ (self, other):
    if isinstance (other, Greatest):
    return 0
    return 1

    def __hash__ (self):
    return id (Greatest)
    __cmp__ no longer exists in Python 3, so this solution could only work in
    Python 2.

    Here's a version using rich comparisons:

    class Greatest:
    __eq__ = __le__ = lambda self, other: isinstance(other, type(self))
    __ne__ = __gt__ = lambda self, othr: not isinstance(othr, type(self))
    __lt__ = lambda self, other: False
    __ge__ = lambda self, other: True
    __hash__ = lambda self: 42


    --
    Steven
  • Rick Johnson at Feb 24, 2012 at 3:34 pm

    On Feb 24, 9:21?am, Mel Wilson wrote:

    Easily fixed:

    [...snip code...]
    Yes i could write my own implementation of INFINITY if i wanted,
    although i would have returned True and False as apposed to 1 and 0
    AND used the identifiers Infinity and Infinitesimal, but i digress :-
    P.

    However, INFINITY is something i believe a language should provide;
    which python does, albeit inconsistently.
  • Michael Torrie at Feb 24, 2012 at 4:23 pm

    On 02/24/2012 08:34 AM, Rick Johnson wrote:
    Yes i could write my own implementation of INFINITY if i wanted,
    although i would have returned True and False as apposed to 1 and 0
    AND used the identifiers Infinity and Infinitesimal, but i digress :-
    P.

    However, INFINITY is something i believe a language should provide;
    which python does, albeit inconsistently.
    How do you represent infinity as an binary integer number? Or are you
    suggesting that the integer type (class) be modified to allow an
    "infinity" state that really isn't a number at all (could not be stored
    as a integer in C)?

    Float is a different story because IEEE does define a binary
    representation of infinity in the floating-point specification.

    I know of no language that has any form of representation of infinity
    for integers mainly because there's no way to represent infinity as a
    standard twos-compliment binary number. In a language that deals
    directly with types in memory such as C, having an infinity
    representation would be possible but would make simple math really hard,
    and much slower.

    All this reminds me of the original cray supercomputers. They didn't
    use twos compliment for integers so they had two representations of zero
    (+0 and -0). Made programming a bit tricky. When asked why the cray
    didn't just do two's compliment like everyone else, Seymour Cray
    responded that when the computer was designed he simply didn't know
    about twos compliment.
  • Mark Lawrence at Feb 24, 2012 at 4:59 pm

    On 24/02/2012 16:23, Michael Torrie wrote:
    On 02/24/2012 08:34 AM, Rick Johnson wrote:
    Yes i could write my own implementation of INFINITY if i wanted,
    although i would have returned True and False as apposed to 1 and 0
    AND used the identifiers Infinity and Infinitesimal, but i digress :-
    P.

    However, INFINITY is something i believe a language should provide;
    which python does, albeit inconsistently.
    How do you represent infinity as an binary integer number? Or are you
    suggesting that the integer type (class) be modified to allow an
    "infinity" state that really isn't a number at all (could not be stored
    as a integer in C)?
    The C integer bit doesn't matter since e.g.
    >>>
    a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    a
    10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

    And no, I'm not going to calculate how much memory I'd need to store a
    string that's this long :)
    Float is a different story because IEEE does define a binary
    representation of infinity in the floating-point specification.

    I know of no language that has any form of representation of infinity
    for integers mainly because there's no way to represent infinity as a
    standard twos-compliment binary number. In a language that deals
    directly with types in memory such as C, having an infinity
    representation would be possible but would make simple math really hard,
    and much slower.

    All this reminds me of the original cray supercomputers. They didn't
    use twos compliment for integers so they had two representations of zero
    (+0 and -0). Made programming a bit tricky. When asked why the cray
    didn't just do two's compliment like everyone else, Seymour Cray
    responded that when the computer was designed he simply didn't know
    about twos compliment.
    --
    Cheers.

    Mark Lawrence.
  • Michael Torrie at Feb 24, 2012 at 11:16 pm

    On 02/24/2012 09:59 AM, Mark Lawrence wrote:
    The C integer bit doesn't matter since e.g.
    a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    a
    10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

    And no, I'm not going to calculate how much memory I'd need to store a
    string that's this long :)
    Sure but that doesn't answer the question posed. How does Rick plan to
    represent an infinite integer? Obviously you've shown that with an
    infinite amount of memory we could do it quite easily. But baring that,
    how does Rick suggest we should represent an infinite integer?
  • Chris Angelico at Feb 25, 2012 at 12:09 am

    On Sat, Feb 25, 2012 at 10:16 AM, Michael Torrie wrote:
    Sure but that doesn't answer the question posed. ?How does Rick plan to
    represent an infinite integer? Obviously you've shown that with an
    infinite amount of memory we could do it quite easily. ?But baring that,
    how does Rick suggest we should represent an infinite integer?
    Barring a suggestion from Rick, I think we should define the number 8
    to be greater than all other integers. After all, Rick's very much in
    favour of evolution, and what would better depict the evolution of
    this glorious language than this notation, showing that the infinity
    symbol is now walking erect!

    ChrisA
  • Mark Lawrence at Feb 25, 2012 at 12:35 am

    On 24/02/2012 23:16, Michael Torrie wrote:
    On 02/24/2012 09:59 AM, Mark Lawrence wrote:
    The C integer bit doesn't matter since e.g.
    a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    a
    10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

    And no, I'm not going to calculate how much memory I'd need to store a
    string that's this long :)
    Sure but that doesn't answer the question posed. How does Rick plan to
    represent an infinite integer? Obviously you've shown that with an
    infinite amount of memory we could do it quite easily. But baring that,
    how does Rick suggest we should represent an infinite integer?
    I understand that a Python integer can run to infinity. Quite how the
    illustrious rr manages to test for the length of a string that's already
    used all of the memory on his system has baffled me, but I'm sure that
    all the people who frequent this list with their Phds, MScs or whatever
    will soon correct me.

    --
    Cheers.

    Mark Lawrence.
  • MRAB at Feb 25, 2012 at 12:37 am

    On 24/02/2012 23:16, Michael Torrie wrote:
    On 02/24/2012 09:59 AM, Mark Lawrence wrote:
    The C integer bit doesn't matter since e.g.
    a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    a
    10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

    And no, I'm not going to calculate how much memory I'd need to store a
    string that's this long :)
    Sure but that doesn't answer the question posed. How does Rick plan to
    represent an infinite integer? Obviously you've shown that with an
    infinite amount of memory we could do it quite easily. But baring that,
    how does Rick suggest we should represent an infinite integer?
    We already have arbitrarily long ints, so there could be a special
    infinite int singleton (actually, 2 of them, one positive, the other
    negative).
  • Fayaz Yusuf Khan at Feb 25, 2012 at 1:22 am

    On Saturday 25 Feb 2012 12:37:58 AM MRAB wrote:
    We already have arbitrarily long ints, so there could be a special
    infinite int singleton (actually, 2 of them, one positive, the other
    negative).
    Seconded. Although would a wish request to bugs.python.org saying "Allow
    storage of the integer infinity" make any sense to the developers? :P
    --
    Fayaz Yusuf Khan
    Cloud developer and architect
    Dexetra SS, Bangalore, India
    fayaz.yusuf.khan_AT_gmail_DOT_com
    fayaz_AT_dexetra_DOT_com
    +91-9746-830-823
    -------------- next part --------------
    A non-text attachment was scrubbed...
    Name: signature.asc
    Type: application/pgp-signature
    Size: 490 bytes
    Desc: This is a digitally signed message part.
    URL: <http://mail.python.org/pipermail/python-list/attachments/20120225/69d1e97a/attachment.pgp>
  • Steven D'Aprano at Feb 25, 2012 at 1:50 am

    On Sat, 25 Feb 2012 06:52:09 +0530, Fayaz Yusuf Khan wrote:
    On Saturday 25 Feb 2012 12:37:58 AM MRAB wrote:
    We already have arbitrarily long ints, so there could be a special
    infinite int singleton (actually, 2 of them, one positive, the other
    negative).
    Seconded. Although would a wish request to bugs.python.org saying "Allow
    storage of the integer infinity" make any sense to the developers? :P
    If you explained it as a pair of special int values, INF and -INF, rather
    than the storage of an infinite-sized integer, it would make perfect
    sense.

    But it would also be rejected, and rightly so, as unnecessary complexity
    for the int type. There are already Decimal and float infinities, just
    use one of them. Or make your own, it's not difficult. Publish it on
    ActiveState, and if people flock to use it, then you will have a good
    argument that this is useful and should be part of the Python built-ins.



    --
    Steven
  • Rick Johnson at Feb 25, 2012 at 8:29 pm

    On Feb 24, 7:50?pm, Steven D'Aprano <steve +comp.lang.pyt... at pearwood.info> wrote:

    But it would also be rejected, and rightly so, as unnecessary complexity
    for the int type. There are already Decimal and float infinities, just
    use one of them.
    Sure there are float INFINITIES that work fine for ints and floats,
    but where is the consistency? INFINITY need not be a int or a float or
    a str, or whatever. All it need be is a an object who always returns
    itself as being larger in any comparison.
    Or make your own, it's not difficult.
    INFINITY should be at the very least a constant of the math module.
  • Alex23 at Feb 27, 2012 at 2:32 am

    On Feb 26, 6:29?am, Rick Johnson wrote:
    Sure there are float INFINITIES that work fine for ints and floats,
    but where is the consistency?
    Sure, there are all of the COMPLEXITIES of floating point arithmetic
    but I want to ignore all of that and demand ridiculous consistencies.
    Why should I have to do float(some_int) < float('inf') when it's a far
    better use of my time to spend days if not weeks bemoaning yet another
    language wart? Why should I be expected to know what float('inf')
    actually represents before making stupid demands like:
    INFINITY need not be a int or a float or
    a str, or whatever.
    Please provide a non-contrived use case of an "infinite string".
    INFINITY should be at the very least a constant of the math module.
    Why? This isn't a mathematical concept of 'infinite' when you're
    talking about comparing against "str, or whatever". We need a more
    appropriate location; please initiate a PEP to add the namespace
    shit.rick.wants into the stdlib.
  • Steven D'Aprano at Feb 27, 2012 at 3:51 am

    On Sun, 26 Feb 2012 18:32:27 -0800, alex23 wrote:
    On Feb 26, 6:29?am, Rick Johnson wrote:
    Sure there are float INFINITIES that work fine for ints and floats, but
    where is the consistency?
    Sure, there are all of the COMPLEXITIES of floating point arithmetic but
    I want to ignore all of that and demand ridiculous consistencies. Why
    should I have to do float(some_int) < float('inf')
    Ints and floats can be compared directly, no need to convert the int to a
    float first:
    INF = float('inf')
    23 < INF
    True


    Likewise Fractions and Decimals, at least in Python 3.2 (possibly not in
    older versions):
    from fractions import Fraction
    from decimal import Decimal
    Fraction(33, 5) < INF
    True
    Decimal("42.1568") < INF
    True


    when it's a far
    better use of my time to spend days if not weeks bemoaning yet another
    language wart? Why should I be expected to know what float('inf')
    actually represents before making stupid demands like:
    INFINITY need not be a int or a float or a str, or whatever.
    Please provide a non-contrived use case of an "infinite string".
    Any lazy stream of characters that potentially goes on forever could be
    considered an infinite string. But that's not what Rick is talking about.

    He's talking about having a pair of special values, say, BIGGEST and
    SMALLEST, which compare larger and smaller to any other value, regardless
    of type and including strings, not literally a string with an infinite
    number of characters.

    I can see some value for this as a convenience, but not enough to make it
    a built-in language feature. Every developer should have at least one
    utility module with all the trivial code snippets they frequently use.
    This belongs in there.


    --
    Steven
  • Chris Angelico at Feb 27, 2012 at 3:59 am

    On Mon, Feb 27, 2012 at 2:51 PM, Steven D'Aprano wrote:
    I can see some value for this as a convenience, but not enough to make it
    a built-in language feature. Every developer should have at least one
    utility module with all the trivial code snippets they frequently use.
    +1. I used to call mine "oddsends" - it nicely fitted into eight
    characters (yeah, was important then - I was on DOS), and I had quite
    a few odds and ends in there.

    ChrisA
  • Alex23 at Feb 27, 2012 at 6:49 am

    On Feb 27, 1:51?pm, Steven D'Aprano <steve +comp.lang.pyt... at pearwood.info> wrote:
    Ints and floats can be compared directly, no need to convert the int to a
    float first
    Ah, cheers. You can see how often I use the two interchangeably :)
    Please provide a non-contrived use case of an "infinite string".
    Any lazy stream of characters that potentially goes on forever could be
    considered an infinite string. But that's not what Rick is talking about.

    He's talking about having a pair of special values, say, BIGGEST and
    SMALLEST, which compare larger and smaller to any other value, regardless
    of type and including strings, not literally a string with an infinite
    number of characters.
    Yeah, my point was more to highlight Rick's laziness in co-opting a
    defined term - INFINITE - and trying to use it to mean something else
    that he couldn't express clearly. His original post stressed numeric
    comparison, the feature creep to include all other types happened
    later. Not the sort of thing we've come to expect from the resident
    linguist extraordinaire :)
    I can see some value for this as a convenience, but not enough to make it
    a built-in language feature.
    For me, it feels like a step backwards to comparing different types:
    1 < INFINITE
    True
    'string' < INFINITE
    True
    1 < 'string'
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unorderable types: int() < str()
    Every developer should have at least one
    utility module with all the trivial code snippets they frequently use.
    This belongs in there.
    Agreed. Especially when it's so trivial:

    class Bound(object):
    def __init__(self, value=None, always_greater=False):
    self.value = value
    self.always_greater = always_greater

    def __cmp__(self, other):
    return True if self.always_greater else self.value.__cmp__(other)
    upper = Bound(100)
    101 > upper
    True
    101 < upper
    False
    infinite = Bound(always_greater=True)
    101 > infinite
    False
    101 < infinite
    True
    upper < 101 < infinite
    True
  • Serhiy Storchaka at Feb 25, 2012 at 3:32 pm

    25.02.12 02:37, MRAB ???????(??):
    We already have arbitrarily long ints, so there could be a special
    infinite int singleton (actually, 2 of them, one positive, the other
    negative).
    float('inf') and float('-inf').
  • Rick Johnson at Feb 25, 2012 at 8:25 pm

    On Feb 24, 6:35?pm, Mark Lawrence wrote:

    I understand that a Python integer can run to infinity. ?Quite how the
    illustrious rr manages to test for the length of a string that's already
    used all of the memory on his system has baffled me,
    When did i ever say that i would need a string who's length is
    INFINITY? In fact, i don't. My example was just that, as SIMPLIFIED
    example of the problem that was the genesis of my question. In my
    "real world" problem, i don't expect the string to EVER be more than
    double digits in length. But as any good programmer knows, you never
    want to solve problems as globally as possible. I need to do
    comparisons on strings now, but maybe integers later, or who knows.
    INFINITY comparisons are useful in many places.
    but I'm sure that
    all the people who frequent this list with their Phds, MScs or whatever
    will soon correct me.
    I don't believe you'd need a Phd to understand my problem.
  • Steven D'Aprano at Feb 24, 2012 at 10:45 pm

    On Fri, 24 Feb 2012 09:23:08 -0700, Michael Torrie wrote:

    All this reminds me of the original cray supercomputers. They didn't
    use twos compliment for integers so they had two representations of zero
    (+0 and -0). Made programming a bit tricky.
    While there is only one integer zero, I would like to point out that in
    floating point, there are usually two zeroes, -0.0 and +0.0, and that
    this is by design and a feature, not an accident or a bug.

    Well-written floating point functions should keep the sign when they
    underflow, e.g.:

    py> 1e-200 * 1e-200
    0.0
    py> 1e-200 * -1e-200
    -0.0

    and well-written functions should honour those separate zeroes because
    sometimes it makes a difference.



    --
    Steven
  • Wolfgang Meiners at Feb 25, 2012 at 8:18 am

    Am 24.02.12 14:37, schrieb Rick Johnson:
    I get sick and tired of doing this!!!

    if maxlength == UNLIMITED:
    allow_passage()
    elif len(string) > maxlength:
    deny_passage()

    What Python needs is some constant that can be compared to ANY numeric
    type and that constant will ALWAYS be larger!

    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()

    Wolfgang
  • MRAB at Feb 25, 2012 at 5:54 pm

    On 25/02/2012 08:18, Wolfgang Meiners wrote:
    Am 24.02.12 14:37, schrieb Rick Johnson:
    I get sick and tired of doing this!!!

    if maxlength == UNLIMITED:
    allow_passage()
    elif len(string)> maxlength:
    deny_passage()

    What Python needs is some constant that can be compared to ANY numeric
    type and that constant will ALWAYS be larger!

    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:
  • Rick Johnson at Feb 25, 2012 at 8:35 pm

    On Feb 25, 11:54?am, MRAB wrote:
    [...]
    That should be:
    if maxlength is not None and len(string) <= maxlength:
    Using "imaginary" infinity values defiles the intuitive nature of your
    code. What is more intuitive?

    def confine_length(string, maxlength=INFINITY):
    if string.length < maxlength:
    do_something()

    def confine_length(string, maxlength=None):
    if maxlength is not None and len(string) <= maxlength:
    do_something()
  • Wolfgang Meiners at Feb 26, 2012 at 1:16 pm

    Am 25.02.12 21:35, schrieb Rick Johnson:
    On Feb 25, 11:54 am, MRAB wrote:
    [...]
    That should be:
    if maxlength is not None and len(string) <= maxlength:
    Using "imaginary" infinity values defiles the intuitive nature of your
    code. What is more intuitive?

    def confine_length(string, maxlength=INFINITY):
    if string.length < maxlength:
    do_something()

    def confine_length(string, maxlength=None):
    if maxlength is not None and len(string) <= maxlength:
    do_something()
    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()

    you migth also write

    def confine_length(str, maxlength=None):
    do_it = (len(str) <= maxlength) if maxlength else True
    if do_it:
    do_something()

    but it really does not look intuitive. Hmm. My idea was that None is a
    perfect Value for infinity since there is no infinitely large number.
    But as i see it, you must have two comparisons then. Maybe someone has a
    better idea?

    Wolfgang
  • Wolfgang Meiners at Feb 26, 2012 at 1:38 pm

    Am 26.02.12 14:16, schrieb Wolfgang Meiners:
    I just had a closer look at it. It seems to be more complicated than i
    thougth: You will have to write
    Obviously not close enough, as i just learned.
    def confine_length(string, maxlength=None):
    if maxlength: # maxlength exists, comparison possible
    if maxlength is not None: # maxlength exists, comparison possible
    if len(string) <= maxlength:
    do_something()
    else: # maxlength does not exist, so always do something
    do_something()

    you migth also write

    def confine_length(str, maxlength=None):
    do_it = (len(str) <= maxlength) if maxlength else True
    do_it = (len(str) <= maxlength) if maxlength is not None else True
    if do_it:
    do_something()
    I hope, it's correct now.
    Wolfgang
  • Arnaud Delobelle at Feb 26, 2012 at 1:44 pm

    On 26 February 2012 13:38, Wolfgang Meiners wrote:
    ? ? ?do_it = (len(str) <= maxlength) if maxlength is not None else True
    That's a funny way to spell:

    do_it = maxlength is None or len(str) <= maxlength

    --
    Arnaud
  • Steven D'Aprano at Feb 26, 2012 at 1:50 pm

    On Sun, 26 Feb 2012 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
  • Neil Cerutti at Feb 27, 2012 at 12:25 pm

    On 2012-02-26, Wolfgang Meiners wrote:
    but it really does not look intuitive. Hmm. My idea was that
    None is a perfect Value for infinity since there is no
    infinitely large number. But as i see it, you must have two
    comparisons then. Maybe someone has a better idea?
    I do. A truncated string with a maxlength of INFINITY is just a
    string.

    --
    Neil Cerutti
  • Jean-Michel Pichavant at Feb 27, 2012 at 11:55 am

    Rick Johnson wrote:
    On Feb 25, 11:54 am, MRAB wrote:

    [...]
    That should be:
    if maxlength is not None and len(string) <= maxlength:
    Using "imaginary" infinity values defiles the intuitive nature of your
    code. What is more intuitive?

    def confine_length(string, maxlength=INFINITY):
    if string.length < maxlength:
    do_something()

    def confine_length(string, maxlength=None):
    if maxlength is not None and len(string) <= maxlength:
    do_something()
    This one:

    def confine_length(string, maxlength=None):
    """Confine the length.

    @param maxlength: the maximum length allowed, set it to None to allow any length.
    """
    if maxlength is not None and len(string) <= maxlength:
    do_something()


    I'm just feeding the troll, I know ... :-/

    JM
  • Wolfgang Meiners at Feb 26, 2012 at 11:56 am

    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
  • Chris Angelico at Feb 26, 2012 at 12:52 pm

    On Sun, Feb 26, 2012 at 10:56 PM, Wolfgang Meiners wrote:
    That means:
    if maxlength and (len(string) <= maxlength):

    is equivalent to
    if (maxlength is not None) and (len(string) <= maxlength):
    On the contrary, it means they are distinctly NOT equivalent. The
    shorter form would treat a maximum length of 0 as meaning "unlimited".
    Now, that's an understandable notation, but it's not what's given
    here; if None means unlimited, then 0 should enforce that string ==
    "".

    ChrisA
  • Steven D'Aprano at Feb 26, 2012 at 1:19 pm

    On Sun, 26 Feb 2012 12:56:46 +0100, Wolfgang Meiners wrote:

    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.
    Incorrect. The two are *not* equivalent.


    def test(maxlength, string):
    flag1 = maxlength and (len(string) <= maxlength)
    flag2 = (maxlength is not None) and (len(string) <= maxlength)
    return bool(flag1), bool(flag2) # normalise to booleans

    test(0, '')
    (False, True)


    So the two forms will take opposite branches of the if statement when
    maxlength is 0 and string is the empty string.



    --
    Steven
  • Wolfgang Meiners at Feb 26, 2012 at 1:32 pm

    Am 26.02.12 13:52, schrieb Chris Angelico:
    On Sun, Feb 26, 2012 at 10:56 PM, Wolfgang Meiners
    wrote:
    That means:
    if maxlength and (len(string) <= maxlength):

    is equivalent to
    if (maxlength is not None) and (len(string) <= maxlength):
    On the contrary, it means they are distinctly NOT equivalent. The
    shorter form would treat a maximum length of 0 as meaning "unlimited".
    Now, that's an understandable notation, but it's not what's given
    here; if None means unlimited, then 0 should enforce that string ==
    "".

    ChrisA
    You are right. It seems I did not get the line
    zero of any numeric type, for example, 0, 0L, 0.0, 0j.
    right.

    Wolfgang

Related Discussions

People

Translate

site design / logo © 2022 Grokbase