FAQ
Hi Everyone,


I'm Mr. Noobie here, I've just started easing into Python (2.7.4) and am
enjoying working along to some youtube tutorials. I've done a little
programming in the past.


I've just got a few thoughts I'd like to share and ask about:


* Why not allow floater=float(int1/int2) - rather than floater=float
(int1)/float(int2)?


Give me a float (or an error message) from evaluating everything in the
brackets. Don't make me explicitly convert everything myself (unless I
want to)


* No sign of a select .. case statement


Another useful tool in the programmer's toolbox


Select DayofWeek


  case "mon"


  ...


end select


* Call me pedantic by why do we need a trailing comma for a list of one
item? Keep it intuitive and allow lstShopping=[] or ["Bread"] or
["Bread", "Milk","Hot Chocolate"] I don't like ["Bread",]. It bugs me.


Just some initial thoughts. I just wanted to know the reasoning behind
the above, be shown the shortcomings of my ignorance, pointed in the
right direction. Let the High Priests of Python come forth and speak wise
words and show me the ignorance of thy ways. Let my cup be filled to
overflowing with your kind knowledge and wisdom.


Is everyone happy with the way things are? Could anyone recommend a good,
high level language for CGI work? Not sure if I'm going to be happy with
Perl (ahhh, get him, he's mentioned Perl and is a heretic!) or Python. I
would very much value any constructive criticism or insights.


And a "thank you", ["sirs","madams"] but pls, not just ["sirs",]


JvH

Search Discussions

  • Ned Batchelder at Nov 9, 2013 at 1:22 pm

    On Saturday, November 9, 2013 8:08:25 AM UTC-5, John von Horn wrote:
    Hi Everyone,

    I'm Mr. Noobie here, I've just started easing into Python (2.7.4) and am
    enjoying working along to some youtube tutorials. I've done a little
    programming in the past.

    I've just got a few thoughts I'd like to share and ask about:

    * Why not allow floater=float(int1/int2) - rather than floater=float
    (int1)/float(int2)?

    Give me a float (or an error message) from evaluating everything in the
    brackets. Don't make me explicitly convert everything myself (unless I
    want to)

    The language has to specify what int1/int2 should evaluate to. Python 2 says it is an int. Once that computation is done, passing that int to float() can't bring back the lost information. Python 3 says that int1/int2 produces a float, and you can get that behavior if you use "from __future__ import division" at the top of your Python 2.7 file.

    * No sign of a select .. case statement

    Another useful tool in the programmer's toolbox

    Select DayofWeek

    case "mon"

    ...

    end select

    This is a bit more controversial. Python has no select statement because it has very little advantage over simply using an if/elif/elif/else ladder. In languages like C, a switch compiles to a table lookup. In Python, all the actual comparisons would have to be done anyway, so it would simply be an alternate syntax for a number of if statements. In the interest of not cluttering the language, the switch statement doesn't exist.

    * Call me pedantic by why do we need a trailing comma for a list of one
    item? Keep it intuitive and allow lstShopping=[] or ["Bread"] or
    ["Bread", "Milk","Hot Chocolate"] I don't like ["Bread",]. It bugs me.

    You're mistaken: One-element lists are written without a trailing comma, though you are allowed to include them. One-element tuples, though, require the trailing comma, since ("hello") is just the same as "hello".


    Welcome to Python!

    JvH
  • Joshua Landau at Nov 9, 2013 at 1:27 pm

    On 9 November 2013 13:08, John von Horn wrote:
    I'm Mr. Noobie here, I've just started easing into Python (2.7.4) and am
    enjoying working along to some youtube tutorials. I've done a little
    programming in the past.

    I've just got a few thoughts I'd like to share and ask about:

    * Why not allow floater=float(int1/int2) - rather than floater=float
    (int1)/float(int2)?

    Give me a float (or an error message) from evaluating everything in the
    brackets. Don't make me explicitly convert everything myself (unless I
    want to)

    In Python 2, `int1/int2` does integer division. So
    `float(that_result)` gives a truncated float.
    `int1/float(int2)` obviously avoids this by dividing by a float.


    If `float(int1/int2)` were to return the same value, `float` could not
    be a normal function, and would have to be magic. Magic is bad.
    Fortunately, Python 3 does the sane thing and just does floating-point
    division by default. Great, eh?

    * No sign of a select .. case statement

    Another useful tool in the programmer's toolbox

    Select DayofWeek

    case "mon"

    ...

    end select

    `select` is quite an odd statement, in that in most cases it's just a
    weaker variant of `if`. By the time you're at the point where a
    `select` is actually more readable you're also at the point where a
    different control flow is probably a better idea. Things like
    dictionaries or a variables pointing to functions are really useful
    and can be encapsulated in a class quite well. This is a bit more
    advanced but largely more rigorous.


    But most of the time the idea is just that an `if` is more explicit,
    and it's not like a `case` statement can be optimised as it can in
    lower-level languages with simpler datatypes.

    * Call me pedantic by why do we need a trailing comma for a list of one
    item? Keep it intuitive and allow lstShopping=[] or ["Bread"] or
    ["Bread", "Milk","Hot Chocolate"] I don't like ["Bread",]. It bugs me.

    You don't.


    You might be confused because you need to write `("hello",)`, but
    that's because the *comma* makes a *tuple*, not the brackets. Imagine
    if `2 * (1/2)` gave you `(0.5, 0.5)`!

    Is everyone happy with the way things are? Could anyone recommend a good,
    high level language for CGI work? Not sure if I'm going to be happy with
    Perl (ahhh, get him, he's mentioned Perl and is a heretic!) or Python. I
    would very much value any constructive criticism or insights.

    I don't know squat about CGI, but I think Python can grow on anyone
    open to the idea of programming at a high level. Not "high level" as
    in "expert" but as in "using higher-level constructs", if you get the
    meaning. Python implements these quite well. Your first two complaints
    are not new, though.
  • Mark Lawrence at Nov 9, 2013 at 1:41 pm

    On 09/11/2013 13:08, John von Horn wrote:
    Hi Everyone,

    I'm Mr. Noobie here, I've just started easing into Python (2.7.4) and am
    enjoying working along to some youtube tutorials. I've done a little
    programming in the past.

    If it's possible I'd strongly recommend Python 3.3, there's lots of
    goodies in there like vastly improved unicode handling.

    I've just got a few thoughts I'd like to share and ask about:

    * Why not allow floater=float(int1/int2) - rather than floater=float
    (int1)/float(int2)?

    Surely this depends on the outcome that you actually want or am I
    missing the obvious? Also note that integer division has been changed
    in Python 3.

    Give me a float (or an error message) from evaluating everything in the
    brackets. Don't make me explicitly convert everything myself (unless I
    want to)

    You usually have to in Python, it's down to strong typing.

    * No sign of a select .. case statement

    Loads of recipes online for this, ranging from specialised classes to my
    favourite which is spelt "dict".

    Another useful tool in the programmer's toolbox

    Select DayofWeek

    case "mon"

    ...

    end select

    * Call me pedantic by why do we need a trailing comma for a list of one
    item? Keep it intuitive and allow lstShopping=[] or ["Bread"] or
    ["Bread", "Milk","Hot Chocolate"] I don't like ["Bread",]. It bugs me.

    It should as it's not needed. I'd guess you're confusing a tuple of one
    item with a list of one item?

    Just some initial thoughts. I just wanted to know the reasoning behind
    the above, be shown the shortcomings of my ignorance, pointed in the
    right direction. Let the High Priests of Python come forth and speak wise
    words and show me the ignorance of thy ways. Let my cup be filled to
    overflowing with your kind knowledge and wisdom.

    Try "import this" from the Python interactive prompt for the Zen of Python.

    Is everyone happy with the way things are?

    Yes thank you.

    Could anyone recommend a good,
    high level language for CGI work?

    I can't comment as to whether or not Python is suitable for CGI work,
    I'll leave that to the experts.

    Not sure if I'm going to be happy with
    Perl (ahhh, get him, he's mentioned Perl and is a heretic!) or Python. I
    would very much value any constructive criticism or insights.

    Fair enough, Python isn't for everybody. I love it simply because it
    suits my mind set, hence I have www.python.org bookmarked as "Home Sweet
    Home". I therefore believe it's safe to say that others hate it as it
    doesn't suit their mind sets.

    And a "thank you", ["sirs","madams"] but pls, not just ["sirs",]

    Reread what I wrote above :)

    JvH

    And check out my signature!!!


    --
    Python is the second best programming language in the world.
    But the best has yet to be invented. Christian Tismer


    Mark Lawrence
  • Jussi Piitulainen at Nov 9, 2013 at 2:24 pm

    John von Horn writes:


    Hi Everyone,

    I'm Mr. Noobie here, I've just started easing into Python (2.7.4)
    and am enjoying working along to some youtube tutorials. I've done a
    little programming in the past.

    I've just got a few thoughts I'd like to share and ask about:

    * Why not allow floater=float(int1/int2) - rather than floater=float
    (int1)/float(int2)?

    Give me a float (or an error message) from evaluating everything in
    the brackets. Don't make me explicitly convert everything myself
    (unless I want to)

    The guardians of the language agree with you and have changed this in
    Python 3. You can import the change to 2.7 thus:

    31/41
       0
    from __future__ import division
    31/41
       0.7560975609756098

    * No sign of a select .. case statement

    I won't comment on that.

    * Call me pedantic by why do we need a trailing comma for a list of
    one item? Keep it intuitive and allow lstShopping=[] or ["Bread"] or
    ["Bread", "Milk","Hot Chocolate"] I don't like ["Bread",]. It bugs
    me.

    Just write ["Bread"]. The comma is not needed.


    Round brackets are used mainly for grouping expressions and calling
    functions. Commas are used to separate function arguments and elements
    of collections like lists, dictionaries, and sets, and to construct
    tuples. The awkward case you have in mind is a one-element tuple that
    has to be written with a trailing comma.

    3,
       (3,)
    (3)
       3
    3,1
       (3, 1)
    (3,1)
       (3, 1)


    Best get used to that. It's just the optional trailing comma, but one
    doesn't want just 3 or (3) interpreted as a tuple - not in Python
    anyway - so in the one-element case optional becomes mandatory.

    3,1,
       (3, 1)
  • Chris Angelico at Nov 9, 2013 at 2:27 pm

    On Sun, Nov 10, 2013 at 12:08 AM, John von Horn wrote:
    Hi Everyone,

    I'm Mr. Noobie here, I've just started easing into Python (2.7.4) and am
    enjoying working along to some youtube tutorials. I've done a little
    programming in the past.

    Hi! For myself, I've come from a background writing code in many other
    languages (most notably C family), and I actually joined this list to
    ask how to do something that turned out to be impossible[1]. Ended up
    staying because the community's awesome. (Apart from a few. You know
    who you are. :) )

    I've just got a few thoughts I'd like to share and ask about:

    * Why not allow floater=float(int1/int2) - rather than floater=float
    (int1)/float(int2)?

    Give me a float (or an error message) from evaluating everything in the
    brackets. Don't make me explicitly convert everything myself (unless I
    want to)

    As others have said, what you're asking for is actually magic. One of
    the rules of Python - one for which I'm not aware of any exceptions -
    is that you can always take a subexpression out and give it a new
    name:


    floater = float(int1/int2)


    temporary = int1/int2
    floater = float(temporary


    will do the exact same thing (modulo the retention of an
    intermediate). This helps *HUGELY* with debugging, and it's part of a
    general "no magic" policy. Sometimes there are other handy cases,
    too... like that literals are nothing special, and that methods on
    objects carry all the information they need:

    formatter = "Foo {} bar {} quux".format
    formatter("Asdf","Qwer")
    'Foo Asdf bar Qwer quux'
    formatter("Hello","World")
    'Foo Hello bar World quux'


    I just created a function that's actually a method off a literal
    string. (It returns a string. I'm doing this at the interactive
    interpreter (REPL [2]), so the return values are being displayed.) As
    far as the rest of the code's concerned, it's a function just like any
    other. JavaScript doesn't do this. You can have closures, which carry
    state about with them... but for some reason that completely escapes
    my comprehension, methods aren't bound to the objects that called
    them, so these two do quite different things:


    document.getElementsByTagName("P");


    var func = document.getElementsByTagName;
    func("P");


    That's magic, and IMHO not a good thing. So, getting back to your
    query about floats... The only way for that to be not-magic would be
    for the int-divided-by-int part to be not yet evaluated by the time
    the float call happens. As others have pointed out, Python 3 has
    int/int --> float, so *this specific* instance wouldn't apply. But the
    same consideration applies to other types:

    import fractions
    fractions.Fraction(12345/54321)
    Fraction(4093955369001953, 18014398509481984)


    The division is done and results in either a float (Python 3, as shown
    above) or an int (which would be 0). Either way, by the time the
    Fraction constructor tries to figure out what value it's been given,
    information has been lost (floats get rounded). The correct way to
    create a Fraction is to pass it the numerator and denominator
    separately:

    fractions.Fraction(12345,54321)
    Fraction(4115, 18107)


    This now has the exactly correct value (it cancelled the common prime
    factor of 3 from both values). It's a small price to pay for a
    guarantee of no-magic evaluation, and the awesome simplicity that that
    gives.

    Just some initial thoughts. I just wanted to know the reasoning behind
    the above, be shown the shortcomings of my ignorance, pointed in the
    right direction. Let the High Priests of Python come forth and speak wise
    words and show me the ignorance of thy ways. Let my cup be filled to
    overflowing with your kind knowledge and wisdom.

    I like that attitude: "This seems odd, so I'll ask why, because that
    way I'll learn something". Some of us have worked with a large number
    of different programming languages, others have a background in
    mathematics (Steven D'Aprano, who'll probably post a response in this
    thread before long, recently contributed a shiny new statistics module
    to the Python standard library), still others have been working in
    computers so long that they've become them (okay, not quite). Maybe
    none of us is a High Priest of this language, but we all have our own
    perspectives on what works and what doesn't, so pretty much any
    question is going to get some responses. :)

    Is everyone happy with the way things are? Could anyone recommend a good,
    high level language for CGI work? Not sure if I'm going to be happy with
    Perl (ahhh, get him, he's mentioned Perl and is a heretic!) or Python. I
    would very much value any constructive criticism or insights.

    No, not everyone's happy with the way things are. If we were, where
    would Python 3.4 come from? :)


    If by CGI you actually literally mean CGI, then most of us don't have
    any experience with it. But if you mean more generally "code executed
    on the fly to create a web page", there are quite a few options. Some
    of us have worked with, again, a variety of languages (I just quit/got
    fired from a job involving PHP; my boss couldn't understand why I so
    strongly disliked PHP, despite lengthy explanations), and even within
    one language there are often multiple ways to do things (Python web
    frameworks are a huge thing all of their own). I would recommend
    setting down more of your requirements, then going through the
    languages and frameworks you know of and ticking the boxes as much as
    you can. When you've finished that exercise, you might have something
    like "I could use Django, except that it doesn't do XYZ for me", which
    would make a perfect python-list thread, or "I could use PHP, except
    that the hammer has two claws on it[3]", which wouldn't. :)


    Welcome to Python, and to python-list. You'll find us all fairly
    opinionated, but as long as you're willing to learn, we'll be more
    than happy to explain things :)


    ChrisA
    [1] For the curious, I was trying to sandbox CPython and run untrusted
    scripts while stopping them from accessing the OS or file system. It's
    basically impossible, so we switched to embedding JavaScript instead.
    [2] Read/Evaluate/Print Loop. Something I'd consider fairly standard
    now for an interactive interpreter. PHP's interactive mode is a
    Read/Eval Loop, so you have to explicitly print things - seems like a
    trivial difference, but it affects productivity hugely, especially
    when you didn't compile in GNU Readline support.
    [3] http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/
    and when you've read that,
    http://www.flickr.com/photos/raindrift/sets/72157629492908038
  • Tim Chase at Nov 9, 2013 at 8:39 pm

    On 2013-11-10 01:27, Chris Angelico wrote:
    Is everyone happy with the way things are? Could anyone recommend
    a good, high level language for CGI work? Not sure if I'm going
    to be happy with Perl (ahhh, get him, he's mentioned Perl and is
    a heretic!) or Python. I would very much value any constructive
    criticism or insights.
    If by CGI you actually literally mean CGI, then most of us don't
    have any experience with it.

    While there might be some die-hards in the group that would accuse
    you (the OP) of heresy, most folks here are pragmatics that will shrug
    and reply "if {Perl,PHP,Ruby,Pike,JavaScript,...} solves your problem,
    go for it. We just can't help you much unless it's Python". Much
    like I'm a vi/vim guy, but if emacs/Sublime/notepad/nano/ed/edlin/cat
    works for you, then go for it.


    Most of the major frameworks *can* be run as CGI (rather than FastCGI
    or WSGI), but performance is usually abysmal because the entire
    program is restarted for each request (whereas FCGI/WSGI have
    long-running processes that exact the spin-up cost once). It's more
    of a party trick or proof-of-concept than anything you'd want to put
    into high-traffic production. Django[1], CherryPy[2], Flask[3],
    web.py[4], web2py[5] all support deploying in a CGI environment (it
    looks like Pylons/Pyramid might too, but I couldn't scare up a link
    for explicit directions).


    I'm personally partial to Django because it offers so much out of
    the box, but I've done work in a couple of the others too (doing some
    CherryPy contract work currently).


    -tkc


    [1] http://joemaller.com/1467/django-via-cgi-on-shared-hosting/


    [2] http://tools.cherrypy.org/wiki/RunAsCGI


    [3] http://flask.pocoo.org/docs/deploying/cgi/


    [4] http://webpy.org/cookbook/cgi-apache


    [5] http://web2py.com/book/default/chapter/13
  • Steven D'Aprano at Nov 9, 2013 at 3:25 pm

    On Sun, 10 Nov 2013 01:27:11 +1100, Chris Angelico wrote:


    I was trying to sandbox CPython and run untrusted scripts while stopping
    them from accessing the OS or file system. It's basically impossible

    PyPy is supposed to come with a proper sandbox. Although even in that
    case, I think it is recommended to use a chroot jail to lock access down
    to some subset of the file system.




    --
    Steven
  • Chris Angelico at Nov 9, 2013 at 3:32 pm

    On Sun, Nov 10, 2013 at 2:25 AM, Steven D'Aprano wrote:
    On Sun, 10 Nov 2013 01:27:11 +1100, Chris Angelico wrote:

    I was trying to sandbox CPython and run untrusted scripts while stopping
    them from accessing the OS or file system. It's basically impossible
    PyPy is supposed to come with a proper sandbox. Although even in that
    case, I think it is recommended to use a chroot jail to lock access down
    to some subset of the file system.

    Yeah, which means that even that wouldn't be sufficient for our
    purposes (since part of the spec is that there should be fast and
    efficient data transfer between the untrusted code and the main
    engine, which has full FS access). That's why we switched away from
    Python altogether. Though I think my boss would have benefited from
    being forced to learn Python.


    ChrisA
  • Rusi at Nov 9, 2013 at 3:38 pm

    On Saturday, November 9, 2013 6:38:25 PM UTC+5:30, John von Horn wrote:
    Another useful tool in the programmer's toolbox
    Select DayofWeek
    case "mon"
    ...
    end select



    You can typically write this in python as a dictionary


    cases = {"mon": do_mon-action,
              "tue", do_tue_action,
    :
    :
    }
    combined with an 'interpreter'
    cases[DayofWeek]()


    Some variants:
    Need a default?
    cases.get(DayofWeek, do_default_action)()


    Sometimes nicer to pass some parameters:
    cases[DayofWeek](some_relevant_context)
  • Roy Smith at Nov 9, 2013 at 3:56 pm
    In article <d15d9993-90f2-43bd-824f-a1df6b7a4556@googlegroups.com>,
      rusi wrote:

    On Saturday, November 9, 2013 6:38:25 PM UTC+5:30, John von Horn wrote:
    Another useful tool in the programmer's toolbox
    Select DayofWeek
    case "mon"
    ...
    end select

    You can typically write this in python as a dictionary

    cases = {"mon": do_mon-action,
    "tue", do_tue_action,
    :
    :
    }
    combined with an 'interpreter'
    cases[DayofWeek]()

    Some variants:
    Need a default?
    cases.get(DayofWeek, do_default_action)()

    Sometimes nicer to pass some parameters:
    cases[DayofWeek](some_relevant_context)

    All of the above is true, but a more straight-forward way to emulate a
    switch/case is with a series of elifs:


    if day_of_week == "mon":
        print "mondays suck"
    elif day_of_week == "tue":
        print "at least it's not monday"
    elif day_of_week == "wed":
        print "humpday!"
    else:
        print "it's some other day"


    I've done both. Both are reasonable translations of switch/case logic
    from other languages.


    The elif chain is more straight-forward to understand, especially for
    somebody new to the language. It also can support more complicated
    selection logic:


    elif day_of_week in ['sat', 'sun']:
        print "it's the weekend"


    John's version is more modular, and lends itself to doing more dynamic
    things like passing around sets of actions as function arguments.
  • Rusi at Nov 9, 2013 at 4:30 pm

    On Saturday, November 9, 2013 9:26:02 PM UTC+5:30, Roy Smith wrote:
    In article rusi wrote:
    On Saturday, November 9, 2013 6:38:25 PM UTC+5:30, John von Horn wrote:
    Another useful tool in the programmer's toolbox
    Select DayofWeek
    case "mon"
    ...
    end select
    You can typically write this in python as a dictionary
    cases = {"mon": do_mon-action,
    "tue", do_tue_action,
    :
    :
    }
    combined with an 'interpreter'
    cases[DayofWeek]()
    Some variants:
    Need a default?
    cases.get(DayofWeek, do_default_action)()
    Sometimes nicer to pass some parameters:
    cases[DayofWeek](some_relevant_context)
    All of the above is true, but a more straight-forward way to emulate a
    switch/case is with a series of elifs:
    if day_of_week == "mon":
    print "mondays suck"
    elif day_of_week == "tue":
    print "at least it's not monday"
    elif day_of_week == "wed":
    print "humpday!"
    else:
    print "it's some other day"
    I've done both. Both are reasonable translations of switch/case logic
    from other languages.
    The elif chain is more straight-forward to understand, especially for
    somebody new to the language. It also can support more complicated
    selection logic:

    Well


    print ( {"mon":"mondays suck",
              "tue":"at least it's not monday",
              "wed":"humpday"
             }.get(day_of_week,"its some other day")
           )


    may be dense


    Separate into named dictionary and its ok (I think!)
  • Rick Johnson at Nov 11, 2013 at 5:36 am

    On Saturday, November 9, 2013 10:30:26 AM UTC-6, rusi wrote:
    [...]
    Well

    print ( {"mon":"mondays suck",
    "tue":"at least it's not monday",
    "wed":"humpday"
    }.get(day_of_week,"its some other day")
    )
    may be dense
    Separate into named dictionary and its ok (I think!)

    Proper code formatting can do WONDERS for readability!


    ## START CODE ##
    d = {
         "mon":"mondays suck",
         "tue":"at least it's not monday",
         "wed":"humpday"
         }
    default = "some other day"
    target = "tue"
    print d.get(target, default)
    target = "blah"
    print d.get(target, default)
    ## END CODE ##


    Of course you could create something "reusable" and "interface-ee".


    ## START CODE ##
    class UsageError(Exception):
         pass


    class Case(object):
         def __init__(self, defaultDict=None, defaultValue=None):
             self.d = defaultDict or {}
             self.defaultValue = defaultValue


         def __str__(self):
             return "Case({0})".format(self.d)


         def __call__(self, key):
             try:
                 v = self.d[key]
             except KeyError:
                 v = self.defaultValue
             return v


         def __getitem__(self, k):
             raise UsageError("RTFS MAN!!!")


    if __name__ == '__main__':
         import calendar
         d = {
             "mon":"mondays suck",
             "tue":"at least it's not monday",
             "wed":"humpday"
             }
         case = Case(d, "some other day")
         try:
             case["tue"]
         except UsageError:
             print 'Stopped improper useage.'
         print case
         lst = [s.lower() for s in calendar.weekheader(3).split(' ')]
         for dayName in lst:
             print "Case.__call__({0!r}) -> {1!r}".format(dayName, case(dayName))
    ## END CODE ##
  • Roy Smith at Nov 11, 2013 at 2:01 pm

    On Saturday, November 9, 2013 10:30:26 AM UTC-6, rusi wrote:
    print ( {"mon":"mondays suck",
    "tue":"at least it's not monday",
    "wed":"humpday"
    }.get(day_of_week,"its some other day")
    )

    In article <8618d47d-518c-4f35-a879-57fad7525411@googlegroups.com>,
      Rick Johnson wrote:
    Proper code formatting can do WONDERS for readability!

    d = {
    "mon":"mondays suck",
    "tue":"at least it's not monday",
    "wed":"humpday"
    }
    default = "some other day"
    target = "tue"
    print d.get(target, default)
    target = "blah"
    print d.get(target, default)

    I agree that Rick's version is better than rusi's version, but possibly
    not for the the reason Rick thinks it is :-) rusi's version has a
    "parsing surprise" in it. As a human scans the code, the thought
    process goes something like this:

    print ( {"mon":"mondays suck",

    "OK, I'm going to print a dictionary"

    "tue":"at least it's not monday",

    "Yeah, still looks like I'm printing a dictionary"

    "wed":"humpday"

    "Yeah, more dictionary, this still makes sense, I'm just waiting to get
    to the and of the dictionary so I can print it"

    }.get(day_of_week,"its some other day")

    "Oh, my! I'm not printing a dictionary after all! I'm doing a get() on
    it!"

    )

    "Ugh, what's this close paren? Does it terminate the get(), or the
    print()? I need to go back and count open parens to make sure"
  • Rusi at Nov 11, 2013 at 3:14 pm

    On Monday, November 11, 2013 7:31:07 PM UTC+5:30, Roy Smith wrote:
    On Saturday, November 9, 2013 10:30:26 AM UTC-6, rusi wrote:
    print ( {"mon":"mondays suck",
    "tue":"at least it's not monday",
    "wed":"humpday"
    }.get(day_of_week,"its some other day")
    )
    Rick Johnson wrote:
    Proper code formatting can do WONDERS for readability!
    d = {
    "mon":"mondays suck",
    "tue":"at least it's not monday",
    "wed":"humpday"
    }
    default = "some other day"
    target = "tue"
    print d.get(target, default)
    target = "blah"
    print d.get(target, default)
    I agree that Rick's version is better than rusi's version, but possibly
    not for the the reason Rick thinks it is :-) rusi's version has a
    "parsing surprise" in it. As a human scans the code, the thought
    process goes something like this:

    Yes I did not like my own version for similar reason: I expect the
    switch order (classic C) to be
    1. expression
    2. body
    3. default


    The following does not quite do it but is it better?


    def switch(val, default, body_dict):
         return body_dict.get(val,default)


    day=...
    switch(day, "something else",
                  {"mon" : "mondays suck",
                   "tue" : "at least it's not monday",
                   "wed" : "humpday"
                  }
           )


    Of course one can flip the body and the default but I find that looks more confusing.
  • Ethan Furman at Nov 12, 2013 at 10:38 pm

    On 11/11/2013 06:05 PM, Dennis Lee Bieber wrote:
    On Mon, 11 Nov 2013 09:01:07 -0500, Roy Smith <roy@panix.com> declaimed the
    following:

    "Ugh, what's this close paren? Does it terminate the get(), or the
    print()? I need to go back and count open parens to make sure"
    No... You need to use an editor/IDE that will highlight the matching
    parens for you...

    I have one of those, and I still sometimes miss one. :/


    --
    ~Ethan~
  • John von Horn at Nov 9, 2013 at 8:19 pm
    On Sat, 09 Nov 2013 07:08:25 -0600, John von Horn wrote:


    Thanks so much for the replies. I'll get my head down and keep on going.
    Sometimes it's great to be wrong. I have a good feeling about this
    language. It's also nice that I can tap into this pool of knowledge that
    is comp.lang.python - I'll be heading down to that watering hole on a
    regular basis. *Help, Help - the python's got me, I've been ambushed*


    And a "thank you" [guys] - alright!


    My next program:


    print 'And a '"thank you"' [guys] to the screen, expanding the list of
    guys to their individual names that have replied to my opening comment.
    displayed as a comma delimited list.


    Time to say "goodbye" to "Hello World" and take it to the next level.
    First floor, here I come.


    We are on a mission! I'm lovin' it.


    JvH
  • Mark Janssen at Nov 9, 2013 at 8:33 pm

    A little late, but a couple of cents worth more data:


    I've just got a few thoughts I'd like to share and ask about:

    * Why not allow floater=float(int1/int2) - rather than floater=float
    (int1)/float(int2)?

    This has to do with evaluation order, the stuff inside the parens gets
    evaluated first, resulting in an integer for versions of python less
    than v3.

    Give me a float (or an error message) from evaluating everything in the
    brackets. Don't make me explicitly convert everything myself (unless I
    want to)

    You only have to give one float value: int1/float(int2). The
    environment converts it to a floating point operation when either of
    the two is a float value. (try: 1/2.0, for example)

    * No sign of a select .. case statement

    Another useful tool in the programmer's toolbox

    I agree on this one, though I prefer C's syntax of switch/case. The
    if/then/elif "ladder" of python is a bit cumbersome, but was chosen to
    reduce language size -- a value with mixed reviews.

    * Call me pedantic by why do we need a trailing comma for a list of one
    item? Keep it intuitive and allow lstShopping=[] or ["Bread"] or
    ["Bread", "Milk","Hot Chocolate"] I don't like ["Bread",]. It bugs me.

    This one got answered, it has to do with the parser when dealing with parens.

    Is everyone happy with the way things are?

    No, but Python is still the best language.

    Could anyone recommend a good,
    high level language for CGI work? Not sure if I'm going to be happy with
    Perl (ahhh, get him, he's mentioned Perl and is a heretic!) or Python.

    Personally, I wouldn't recommend Python for web scripts. But I'm
    biased and am speaking from where I see the field of computer
    languages heading.


    MarkJ
    Tacoma, Washington
  • Mark Lawrence at Nov 9, 2013 at 9:01 pm

    On 09/11/2013 20:33, Mark Janssen wrote:
    * Call me pedantic by why do we need a trailing comma for a list of one
    item? Keep it intuitive and allow lstShopping=[] or ["Bread"] or
    ["Bread", "Milk","Hot Chocolate"] I don't like ["Bread",]. It bugs me.
    This one got answered, it has to do with the parser when dealing with parens.

    It got answered and was simply mistaken, no comma is needed but a comma
    will be accepted. How did the parser enter into this, or are you also
    thinking about tuples?

    mylist=['Bread']
    mylist
    ['Bread']
    mylist=['Butter',]
    mylist
    ['Butter']


    --
    Python is the second best programming language in the world.
    But the best has yet to be invented. Christian Tismer


    Mark Lawrence
  • Tim Chase at Nov 9, 2013 at 9:20 pm

    On 2013-11-09 21:01, Mark Lawrence wrote:
    no comma is needed but a comma will be accepted.

    I find the optional trailing comma particularly useful (and painful in
    languages that don't accept it) for doing inline lists to produce
    cleaner version-control diffs. I write most of my code like this
    (with a trailing comma):


       lst = [
         "one",
         "two",
         "three",
         ]


    so when I go to add something, the diff looks much more readable like


          "two",
          "three",
    + "four",
          ]


    instead of


          "two",
    - "three"
    + "three",
    + "four"
          ]


    which makes me look at all of the modified lines to validate exactly
    what did (and didn't) change.


    -tkc
  • Ned Batchelder at Nov 9, 2013 at 8:54 pm

    On Saturday, November 9, 2013 3:33:30 PM UTC-5, zipher wrote:
    Personally, I wouldn't recommend Python for web scripts. But I'm
    biased and am speaking from where I see the field of computer
    languages heading.

    MarkJ
    Tacoma, Washington

    I'd be interested to hear your thoughts on where the field of computer languages is heading, and how that affects the choice of languages for building web sites.


    --Ned.
  • Mark Janssen at Nov 9, 2013 at 9:21 pm
    I'd be interested to hear your thoughts on where the field of computer languages is heading, and how that affects the choice of languages for building web sites.

    Well, there aren't that many groupings towards which languages
    specialize for (not including embedded or other application-specific
    domains). There's OS scripting, Web scripting, and then the otherwise
    general-purpose "normative" languages in the middle of those two
    extremes. But this view presumes a model of computation which hasn't
    settled into wide agreement.
    --
    MarkJ
    Tacoma, Washington
  • Jonathan at Nov 9, 2013 at 10:44 pm

    On Saturday, November 9, 2013 8:27:02 AM UTC-5, Joshua Landau wrote:


    `select` is quite an odd statement, in that in most cases it's just a
    weaker variant of `if`. By the time you're at the point where a
    `select` is actually more readable you're also at the point where a
    different control flow is probably a better idea. Things like
    dictionaries or a variables pointing to functions are really useful
    and can be encapsulated in a class quite well. This is a bit more
    advanced but largely more rigorous.

    But most of the time the idea is just that an `if` is more explicit,
    and it's not like a `case` statement can be optimised as it can in
    lower-level languages with simpler datatypes.

    The C switch statement is very limited. The select statement in the dialect of BASIC I regularly use is more flexible. It's more concise on long if chains because it elides the "end if"s. But the use of indentation for blocks and the "in" operator certainly reduce the need for it in Python.


    In pythonic syntax:


    select <expression0>:
       case <case expression>,[<case expression>],:
       ....
       ....
       case else:




    where <case expression> is one of


    a) <expression1>


    which is equivalent to: elif <expression0> = <expression1>:


    b) <binary-operator> <expression2>


    which is equivalent to: elif <expression0> <binary-operator>


    Note that:
      "elif" is actually "if" for the first case in the select.
      control exits at next case, no need for breaks.
      expression0 is only evaluated once and stored in an anonymous temporary variable.


    The switch statement in (the language) go is similar, except that <expression0> defaults to true and it doesn't elide <expression0> in the case statements.


    Dictionaries can't handle the uses where expression0 is constant and the case expressions are not.
    Function variables beg the question. How did you decide what to assign to the variable?


    I'd use this select if it was in Python, but I don't see much need for it.


    jtc
  • Chris Angelico at Nov 9, 2013 at 11:29 pm

    On Sun, Nov 10, 2013 at 9:44 AM, Jonathan wrote:
    In pythonic syntax:

    select <expression0>:
    case <case expression>,[<case expression>],:
    which is equivalent to: elif <expression0> = <expression1>:
    which is equivalent to: elif <expression0> <binary-operator>

    Small clarification: It's more akin to assigning <expression0> to a
    temporary, and then comparing that temporary against everything. It's
    only evaluated once. Otherwise, yes, as you describe.


    ChrisA
  • MRAB at Nov 10, 2013 at 12:50 am

    On 09/11/2013 22:44, Jonathan wrote:
    On Saturday, November 9, 2013 8:27:02 AM UTC-5, Joshua Landau wrote:

    `select` is quite an odd statement, in that in most cases it's just a
    weaker variant of `if`. By the time you're at the point where a
    `select` is actually more readable you're also at the point where a
    different control flow is probably a better idea. Things like
    dictionaries or a variables pointing to functions are really useful
    and can be encapsulated in a class quite well. This is a bit more
    advanced but largely more rigorous.

    But most of the time the idea is just that an `if` is more explicit,
    and it's not like a `case` statement can be optimised as it can in
    lower-level languages with simpler datatypes.
    The C switch statement is very limited. The select statement in the dialect of BASIC I regularly use is more flexible. It's more concise on long if chains because it elides the "end if"s. But the use of indentation for blocks and the "in" operator certainly reduce the need for it in Python.

    In pythonic syntax:

    select <expression0>:
    case <case expression>,[<case expression>],:
    ....
    ....
    case else:
    [snip]


    It's more likely that the cases would be indented the same amount as
    the 'select', and you wouldn't need 'case else', just 'else'.
  • Chris Angelico at Nov 10, 2013 at 12:54 am

    On Sun, Nov 10, 2013 at 11:50 AM, MRAB wrote:
    On 09/11/2013 22:44, Jonathan wrote:
    In pythonic syntax:

    select <expression0>:
    case <case expression>,[<case expression>],:
    ....
    ....
    case else:
    [snip]

    It's more likely that the cases would be indented the same amount as
    the 'select', and you wouldn't need 'case else', just 'else'.

    To fully bike-shed something that's not even a proposal, much less one
    that's likely to happen: I would agree with Jonathan, the 'select'
    block ends with a colon and gets indented.


    ChrisA
  • Neil Cerutti at Nov 11, 2013 at 3:30 pm

    On Saturday, November 9, 2013 8:27:02 AM UTC-5, Joshua Landau wrote:
    The C switch statement is very limited. The select statement
    in the dialect of BASIC I regularly use is more flexible.
    It's more concise on long if chains because it elides the "end
    if"s. But the use of indentation for blocks and the "in"
    operator certainly reduce the need for it in Python.

    It's say the C switch isn't limited enough to be a Python
    resident. The default fallthrough, labels, jumps and breaks make
    it a poor Python construct.


    K&R have this to say: "Falling through from one case to another
    is not robust, being prone to disintegration when the program is
    modified."


    So Python would need something simler. Once you winnow it down to
    a robust feature, it provide virtually nothing you don't get with
    an if/elif/else. At best it would save a temporary.

    The switch statement in (the language) go is similar, except
    that <expression0> defaults to true and it doesn't elide
    <expression0> in the case statements.

    Go makes interesting use of switch statements. In addition to
    what you might expect, you can also do type switches. A type
    switch lets you provide a different execution path depending on
    the underlying object represented by an interface.


    Thus, Go carved out a useful niche for a robust switch statement.
    Python used duck-typing instead of interfaces and generally
    doesn't need any special syntax for type checks, hence Go's
    version of switch doesn't make sense for Python, either.


    Go's cases must be constants, and allows optional fallthrough
    with the 'fallthrough' keyword. This forces them to provide break
    semantics to break out of a switch, which makes using them to
    break of an immediately outer loop messy.

    Dictionaries can't handle the uses where expression0 is
    constant and the case expressions are not. Function variables
    beg the question. How did you decide what to assign to the
    variable?

    A Python generator might take the place of that application, but
    I haven't tried it for that.

    I'd use this select if it was in Python, but I don't see much
    need for it.

    Same here. Perhaps the real value of a switch is that it seems to
    be a more natural way of thinking about execution. The caveat to
    that is most *actual* switch implementations are a mess.


    --
    Neil Cerutti
  • Jorgen Grahn at Nov 10, 2013 at 8:47 am

    On Sat, 2013-11-09, Chris Angelico wrote:
    On Sun, Nov 10, 2013 at 12:08 AM, John von Horn wrote:
    ...
    * Why not allow floater=float(int1/int2) - rather than floater=float
    (int1)/float(int2)?

    Give me a float (or an error message) from evaluating everything in the
    brackets. Don't make me explicitly convert everything myself (unless I
    want to)
    As others have said, what you're asking for is actually magic. One of
    the rules of Python - one for which I'm not aware of any exceptions -
    is that you can always take a subexpression out and give it a new
    name:

    And it's not just Python: programming languages have been designed
    that way since at least the 1960s. People are used to analysing
    expressions inside and out according to rules common for almost all
    languages.


    /Jorgen


    --
       // Jorgen Grahn <grahn@ Oo o. . .
    \X/ snipabacken.se> O o .
  • Chris Angelico at Nov 10, 2013 at 9:22 am

    On Sun, Nov 10, 2013 at 7:47 PM, Jorgen Grahn wrote:
    On Sat, 2013-11-09, Chris Angelico wrote:
    On Sun, Nov 10, 2013 at 12:08 AM, John von Horn wrote:
    ...
    * Why not allow floater=float(int1/int2) - rather than floater=float
    (int1)/float(int2)?

    Give me a float (or an error message) from evaluating everything in the
    brackets. Don't make me explicitly convert everything myself (unless I
    want to)
    As others have said, what you're asking for is actually magic. One of
    the rules of Python - one for which I'm not aware of any exceptions -
    is that you can always take a subexpression out and give it a new
    name:
    And it's not just Python: programming languages have been designed
    that way since at least the 1960s. People are used to analysing
    expressions inside and out according to rules common for almost all
    languages.

    That's true to at least some extent, but quite a few languages have
    differences here and there. In C, there's no such thing as an array
    literal, only an initializer list, so:


    /* This works: */
    int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int this_month_days = month_days[this_month];


    /* This doesn't: */
    int three = {1, 2, 3, 4, 5}[2];


    PHP had similar issues up until a *very* recent version (5.3 or 5.4 or
    something), where you couldn't dereference an array returned by a
    function:


    //Works:
    $arr = func();
    $val = $arr[5];


    //Didn't work until recently, and therefore can't be trusted for
    //deployment to random systems across the internet:
    $val = func()[5];


    JavaScript has magic around the dot and function-call operators, as I
    mentioned earlier. Lots of other languages have some little quirk
    somewhere that breaks this rule; some have a LOT of quirks that break
    this rule. Does Python have any? Aside from parsing oddities like
    attribute access on a literal integer[1], are there any cases where
    two expressions yielding the same object are in any way different?


    ChrisA
    [1] You can write "(1234).to_bytes(2,'big')" but omitting the parens
    gives a SyntaxError because it looks like the start of a float
    literal.
  • Ian Kelly at Nov 10, 2013 at 11:39 am

    On Sun, Nov 10, 2013 at 2:22 AM, Chris Angelico wrote:
    JavaScript has magic around the dot and function-call operators, as I
    mentioned earlier. Lots of other languages have some little quirk
    somewhere that breaks this rule; some have a LOT of quirks that break
    this rule. Does Python have any? Aside from parsing oddities like
    attribute access on a literal integer[1], are there any cases where
    two expressions yielding the same object are in any way different?

    I can think of one:


    class Spam:
         def __init__(self):
             super().__init__() # This works.


    sup = super


    class Eggs:
         def __init__(self):
             sup().__init__() # This doesn't.
  • Chris Angelico at Nov 10, 2013 at 11:43 am

    On Sun, Nov 10, 2013 at 10:39 PM, Ian Kelly wrote:
    On Sun, Nov 10, 2013 at 2:22 AM, Chris Angelico wrote:
    JavaScript has magic around the dot and function-call operators, as I
    mentioned earlier. Lots of other languages have some little quirk
    somewhere that breaks this rule; some have a LOT of quirks that break
    this rule. Does Python have any? Aside from parsing oddities like
    attribute access on a literal integer[1], are there any cases where
    two expressions yielding the same object are in any way different?
    I can think of one:

    class Spam:
    def __init__(self):
    super().__init__() # This works.

    sup = super

    class Eggs:
    def __init__(self):
    sup().__init__() # This doesn't.

    Ah, yes, super() is magical. In that particular instance, I think the
    magic is better than the alternative, but let's face it: Multiple
    inheritance is an inherently hard problem, so a solution that has so
    little magic and manages to achieve the goal is doing well. The only
    thing that would have been better than this would be making it a piece
    of special syntax rather than something that looks like a function
    call, but it's too late to change now.


    ChrisA
  • Chris Angelico at Nov 10, 2013 at 11:29 pm

    On Mon, Nov 11, 2013 at 4:12 AM, Dennis Lee Bieber wrote:
    -123 .bit_length()
    -7

    No parens needed if a space precedes the .

    Heh! I would call that an inferior alternative to the parentheses
    though; it's so unusual to put a space before the dot that I wouldn't
    consider it something to do in normal code. Anyone coming through and
    editing would see it as a mistake to be fixed.


    ChrisA
  • Terry Reedy at Nov 11, 2013 at 12:13 am

    On 11/10/2013 6:29 PM, Chris Angelico wrote:
    On Mon, Nov 11, 2013 at 4:12 AM, Dennis Lee Bieber
    wrote:
    -123 .bit_length()
    -7

    No parens needed if a space precedes the .
    Heh! I would call that an inferior alternative to the parentheses
    though; it's so unusual to put a space before the dot that I wouldn't
    consider it something to do in normal code. Anyone coming through and
    editing would see it as a mistake to be fixed.

    I have only used int methods in interactive exploration, and have always
    used space. I have never used (), but agree that they are better for
    permanent code. The -7 is really nasty (unless one were to actually want
    that).


    --
    Terry Jan Reedy
  • Thomas Rachel at Nov 10, 2013 at 12:24 pm

    Am 09.11.2013 14:27 schrieb Joshua Landau:


    `select` is quite an odd statement, in that in most cases it's just a
    weaker variant of `if`. By the time you're at the point where a
    `select` is actually more readable you're also at the point where a
    different control flow is probably a better idea. Things like
    dictionaries or a variables pointing to functions are really useful
    and can be encapsulated in a class quite well. This is a bit more
    advanced but largely more rigorous.

    class Switch(object):
          def __init__(self, value):
              self.value = value
              self.called = False
          def case(self, other):
              def wr(func):
                  if not self.called and self.value == other:
                      self.called = True
                      return func(self.value)
              return wr
          def default(self, func):
              if not self.called:
                  self.called = True
                  return func(self.value)




    if __name__ == '__main__':
          import random


          while 1:
              n = random.randrange(0, 5)
              sw = Switch (n)
              @sw.case(1)
              def _(n): print n, "is one"


              @sw.case(2)
              def _(n): print n, "is two"


              @sw.default
              def _(n): print n, "is something else"
  • Lorenzo Gatti at Nov 11, 2013 at 10:09 am
    Regarding the "select" statement, I think the most "Pythonic" approach is using dictionaries rather than nested ifs.
    Supposing we want to decode abbreviated day names ("mon") to full names ("Monday"):
    day_abbr='mon'


    day_names_mapping={
         'mon':'Monday',
         'tue':'Tuesday',
         'wed':'Wednesday',
         'thu':'Thursday',
         'fri':'Friday',
         'sat':'Saturday',
         'sun':'Sunday'
         }
    try:
         full_day_name=day_names_mapping[day_abbr.casefold()]
    except KeyError:
         raise GoodLuckFixingItException('We don't have "'+day_abbr+'" in our week')


    This style is more compact (usually one line per case) and more meaningful (generic processing driven by separate data) than a pile of if statement, and more flexible:


    full_day_names=('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')
    day_names={x.casefold()[0:3] : x for x in full_day_names}
    #


    A dict can also contain tuples, lists, and nested dicts, consolidating multiple switches over the same keys and organizing nested switches and other more complex control structures.
  • Chris Angelico at Nov 11, 2013 at 10:39 am

    On Mon, Nov 11, 2013 at 9:09 PM, wrote:
    Regarding the "select" statement, I think the most "Pythonic" approach is using dictionaries rather than nested ifs.
    Supposing we want to decode abbreviated day names ("mon") to full names ("Monday"):

    That's an obvious mapping, though. If you're using a select/switch
    statement to handle straight-forward one-to-one mappings, then yes,
    obviously the better way to do it is to use a dictionary. In the more
    general sense, a switch/case block is much more directly translated
    into if/elif/else statements. You can't, for instance, build up a
    dictionary that handles inequalities, but you can do that with elif.


    That is, normally you can't. I have occasionally built up mappings
    that handle inequalities - it's a form of denormalization. Consider
    the following logic:


    A 'minor weapon' is based on a roll of a 100-sided dice. If it's 01 to
    70, "+1 weapon: 2,000gp [weapon]"; if it's 71 to 85, "+2 weapon:
    8,000gp [weapon]"; if 86 to 90, "Specific weapon [minor specific
    weapon]"; and if 91 to 100, "Special ability [minor special weapon]
    and roll again".


    My code to handle that starts out with this array:


    "minor weapon":({
         70,"+1 weapon: 2,000gp [weapon]",
         85,"+2 weapon: 8,000gp [weapon]",
         90,"Specific weapon [minor specific weapon]",
         100,"Special ability [minor special weapon] and roll again",
    }),


    (that's Pike; in Python it'd be a list, or maybe a tuple of tuples),
    and denormalizes it into a lookup table by creating 70 entries quoting
    the first string, 15 quoting the second, 5, and 10, respectively. So,
    with a bit of preprocessing, a lookup table (which in this case is an
    array (list), but could just as easily be a dict) can be used to
    handle inequalities. But this is because lookup tables can be treated
    as data, where if/elif/else blocks have to be code; there are roughly
    42 million such lookup tables in the code I snagged that from, and
    having code for each one would work out far less manageable. Normally,
    you'll want to render inequalities with code as if/elif.


    ChrisA
  • Robert Kern at Nov 11, 2013 at 11:53 am

    On 2013-11-11 10:39, Chris Angelico wrote:


    A 'minor weapon' is based on a roll of a 100-sided dice. If it's 01 to
    70, "+1 weapon: 2,000gp [weapon]"; if it's 71 to 85, "+2 weapon:
    8,000gp [weapon]"; if 86 to 90, "Specific weapon [minor specific
    weapon]"; and if 91 to 100, "Special ability [minor special weapon]
    and roll again".

    My code to handle that starts out with this array:

    "minor weapon":({
    70,"+1 weapon: 2,000gp [weapon]",
    85,"+2 weapon: 8,000gp [weapon]",
    90,"Specific weapon [minor specific weapon]",
    100,"Special ability [minor special weapon] and roll again",
    }),

    (that's Pike; in Python it'd be a list, or maybe a tuple of tuples),
    and denormalizes it into a lookup table by creating 70 entries quoting
    the first string, 15 quoting the second, 5, and 10, respectively. So,
    with a bit of preprocessing, a lookup table (which in this case is an
    array (list), but could just as easily be a dict) can be used to
    handle inequalities. But this is because lookup tables can be treated
    as data, where if/elif/else blocks have to be code; there are roughly
    42 million such lookup tables in the code I snagged that from, and
    having code for each one would work out far less manageable. Normally,
    you'll want to render inequalities with code as if/elif.

    Heh. I've done pretty much exactly the same thing to implement an engine[1] to
    draw from the random tables on Abulafia[2] which have nearly the same structure.
    It scales up reasonably well beyond d100s. It's certainly not a technique I
    would pull out to replace one-off if-elif chains that you literally write, but
    it works well when you write the generic code once to apply to many tables.


    [1] http://rollmeup.mechanicalkern.com/
    [2] http://www.random-generator.com/index.php?title=Main_Page


    --
    Robert Kern


    "I have come to believe that the whole world is an enigma, a harmless enigma
       that is made terrible by our own mad attempt to interpret it as though it had
       an underlying truth."
        -- Umberto Eco
  • Chris Angelico at Nov 11, 2013 at 12:07 pm

    On Mon, Nov 11, 2013 at 10:53 PM, Robert Kern wrote:
    Heh. I've done pretty much exactly the same thing to implement an engine[1]
    to draw from the random tables on Abulafia[2] which have nearly the same
    structure. It scales up reasonably well beyond d100s. It's certainly not a
    technique I would pull out to replace one-off if-elif chains that you
    literally write, but it works well when you write the generic code once to
    apply to many tables.

    I'd trust my current code for several orders of magnitude beyond where
    I'm currently using it, but as Steven said, you really don't want to
    be manually looking at the denormalized tables. Since all the strings
    are referenced anyway, having a lookup array of (say) 1,000,000 object
    pointers is fairly cheap.

    lst = ["Low" if i<500000 else "High" for i in range(1000000)]
    sys.getsizeof(lst)
    4348736


    That's pretty close to four bytes per entry, which would be the
    cheapest you could hope for on a 32-bit system. 10% overhead is quite
    acceptable. And this is a fairly extreme example :)


    ChrisA
  • Joshua Landau at Nov 11, 2013 at 8:50 pm

    On 11 November 2013 10:39, Chris Angelico wrote:
    On Mon, Nov 11, 2013 at 9:09 PM, wrote:
    Regarding the "select" statement, I think the most "Pythonic" approach is using dictionaries rather than nested ifs.
    Supposing we want to decode abbreviated day names ("mon") to full names ("Monday"):
    You can't [normally], for instance, build up a
    dictionary that handles inequalities, but you can do that with elif.
    [...] Consider the following logic:

    A 'minor weapon' is based on a roll of a 100-sided dice. If it's 01 to
    70, "+1 weapon: 2,000gp [weapon]"; if it's 71 to 85, "+2 weapon:
    8,000gp [weapon]"; if 86 to 90, "Specific weapon [minor specific
    weapon]"; and if 91 to 100, "Special ability [minor special weapon]
    and roll again".

    My code to handle that starts out with this array:

    "minor weapon":({
    70,"+1 weapon: 2,000gp [weapon]",
    85,"+2 weapon: 8,000gp [weapon]",
    90,"Specific weapon [minor specific weapon]",
    100,"Special ability [minor special weapon] and roll again",
    }),

    (that's Pike; in Python it'd be a list, or maybe a tuple of tuples),
    and denormalizes it into a lookup table by creating 70 entries quoting
    the first string, 15 quoting the second, 5, and 10, respectively. So,
    with a bit of preprocessing, a lookup table (which in this case is an
    array (list), but could just as easily be a dict) can be used to
    handle inequalities.

    The obvious way to me is a binary search:


         from bisect import bisect_left


         class FloorMap:
             def __init__(self, dct):
                 self.indexes = sorted(list(dct))
                 self.dct = dct


             def __getitem__(self, itm):
                 index = self.indexes[bisect_left(self.indexes, itm)]
                 return self.dct[index]




         minor_weapon = FloorMap({
             70: "+1 weapon: 2,000gp [weapon]",
             85: "+2 weapon: 8,000gp [weapon]",
             90: "Specific weapon [minor specific weapon]",
             100: "Special ability [minor special weapon] and roll again"
         })


         minor_weapon[63]
         #>>> '+1 weapon: 2,000gp [weapon]'


    The precise details of the wrapper class here are just to make
    initialisation pretty; it could be done straight from a pair of lists
    too:


         from bisect import bisect_left


         minor_weapon_indexes = 70, 85, 90, 100
         minor_weapon_descriptions = (
             "+1 weapon: 2,000gp [weapon]",
             "+2 weapon: 8,000gp [weapon]",
             "Specific weapon [minor specific weapon]",
             "Special ability [minor special weapon] and roll again"
         )


         minor_weapon_descriptions[bisect_left(minor_weapon_indexes, 80)]
         #>>> '+2 weapon: 8,000gp [weapon]'


    Compare to


         if 80 <= 70:
             res = "+1 weapon: 2,000gp [weapon]"


         elif 80 <= 85:
             res = "+2 weapon: 8,000gp [weapon]"


         elif 80 <= 90:
             res = "Specific weapon [minor specific weapon]"


         elif 80 <= 100:
             res = "Special ability [minor special weapon] and roll again"


    which although shorter? is a lot less data-driven and much less reusable.


    ? Longer if you ignore the import and class declaration.
  • Chris Angelico at Nov 11, 2013 at 10:21 pm

    On Tue, Nov 12, 2013 at 7:50 AM, Joshua Landau wrote:
    The obvious way to me is a binary search:

    Which makes an O(log n) search where I have an O(1) lookup. The
    startup cost of denormalization doesn't scale, so when the server
    keeps running for two years or more, it's definitely worth processing
    it that way.


    ChrisA
  • Joshua Landau at Nov 12, 2013 at 1:53 am

    On 11 November 2013 22:21, Chris Angelico wrote:
    On Tue, Nov 12, 2013 at 7:50 AM, Joshua Landau wrote:
    The obvious way to me is a binary search:
    Which makes an O(log n) search where I have an O(1) lookup. The
    startup cost of denormalization doesn't scale, so when the server
    keeps running for two years or more, it's definitely worth processing
    it that way.

    log 4 is tiny so I'd expect constant factors to be far more
    significant here. Then you add on the better asymptotic behaviours for
    large n, space wise, and the simplicity of implementation. This just
    seems like a premature optimisation to me, I guess.


    I agree that your way is faster; I just don't see a single case in
    which I'd care. I do see several circumstances (large or floating
    numbers) in which I'd probably prefer my way.


    Feel free to disagree, I'm not really trying to convince you.
  • Steven D'Aprano at Nov 11, 2013 at 11:17 am

    On Mon, 11 Nov 2013 21:39:27 +1100, Chris Angelico wrote:


    My code to handle that starts out with this array:

    "minor weapon":({
    70,"+1 weapon: 2,000gp [weapon]",
    85,"+2 weapon: 8,000gp [weapon]",
    90,"Specific weapon [minor specific weapon]", 100,"Special ability
    [minor special weapon] and roll again",
    }),

    (that's Pike; in Python it'd be a list, or maybe a tuple of tuples), and
    denormalizes it into a lookup table by creating 70 entries quoting the
    first string, 15 quoting the second, 5, and 10, respectively.

    Ewww :-(


    Imagine having to print out the dict looking for an error in the lookup
    table. Or imagine the case where you have:


    0...20000: do this
    20001...890001: do that
    890001...890003: do something else


    Don't get me wrong, it's a clever and reasonable solution for your
    specific use-case. But I'd much rather have a lookup table variant that
    matches on intervals.


    Hmmm... if you had an interval data type, which was hashable, that would
    probably be trivial... what am I missing? Ah, of course, what I'm missing
    is that although you're storing intervals as the keys, you're matching
    regular ints.


    I wonder if this would be a good use-case for Antoine Pitrou's
    TransformDict?


    http://www.python.org/dev/peps/pep-0455/




    --
    Steven
  • Chris Angelico at Nov 11, 2013 at 11:32 am

    On Mon, Nov 11, 2013 at 10:17 PM, Steven D'Aprano wrote:
    On Mon, 11 Nov 2013 21:39:27 +1100, Chris Angelico wrote:
    denormalizes it into a lookup table by creating 70 entries quoting the
    first string, 15 quoting the second, 5, and 10, respectively.
    Ewww :-(

    Imagine having to print out the dict looking for an error in the lookup
    table. Or imagine the case where you have:

    0...20000: do this
    20001...890001: do that
    890001...890003: do something else

    Don't get me wrong, it's a clever and reasonable solution for your
    specific use-case. But I'd much rather have a lookup table variant that
    matches on intervals.

    Of course it's "Ewww" in isolation :) But just imagine there are piles
    and piles of these tables, themselves keyed by keyword, and I want to
    be able to let untrusted people create tables (which means they
    basically have to be data, not code). Also, bear in mind, all the
    tables are based around dice that can be physically rolled, so none
    has more than 100 entries after denormalization. Quite a lot of the
    tables actually have unique entries per value (eg it's a d10 roll,
    with ten unique outputs), so it's simplest to just turn all the tables
    into that format; that way, the main code needs worry about one type
    only, and the preprocessor handles the denormalization.


    And if there's an error in the lookup table, well, you look at the
    normalized version, not at the one that actually gets parsed :) That's
    basically like looking back at the Python source code rather than the
    disassembled byte-code; apart from actually debugging the preprocessor
    itself (which can be done with a ten-entry table that's easily
    eyeballed), the denormalized version needn't be looked at by a human.


    But this is a very VERY specific situation. Normally it's best to just
    use an if/elif block. That's why this looks so "Ewww". :)


    ChrisA
  • Mark Janssen at Nov 11, 2013 at 10:29 pm

    On Mon, Nov 11, 2013 at 3:32 AM, Chris Angelico wrote:
    On Mon, Nov 11, 2013 at 10:17 PM, Steven D'Aprano
    wrote:
    On Mon, 11 Nov 2013 21:39:27 +1100, Chris Angelico wrote:
    denormalizes it into a lookup table by creating 70 entries quoting the
    first string, 15 quoting the second, 5, and 10, respectively.
    Ewww :-(

    Imagine having to print out the dict looking for an error in the lookup
    table. Or imagine the case where you have:

    0...20000: do this
    20001...890001: do that
    890001...890003: do something else

    Don't get me wrong, it's a clever and reasonable solution for your
    specific use-case. But I'd much rather have a lookup table variant that
    matches on intervals.
    Of course it's "Ewww" in isolation :) But just imagine there are piles
    and piles of these tables, themselves keyed by keyword, and I want to
    be able to let untrusted people create tables (which means they
    basically have to be data, not code). Also, bear in mind, all the
    tables are based around dice that can be physically rolled, so none
    has more than 100 entries after denormalization. Quite a lot of the
    tables actually have unique entries per value (eg it's a d10 roll,
    with ten unique outputs), so it's simplest to just turn all the tables
    into that format; that way, the main code needs worry about one type
    only, and the preprocessor handles the denormalization.

    Hmm, I automatically think of creating a hash function, but then
    that's how Python implements keys in dicts, so a dict is fine
    solution.


    --
    MarkJ
    Tacoma, Washington

Related Discussions

People

Translate

site design / logo © 2022 Grokbase