Noob question: Is all this typecasting normal?

Discussion in 'Python' started by sprad, Jan 2, 2009.

  1. sprad

    sprad Guest

    I've done a good bit of Perl, but I'm new to Python.

    I find myself doing a lot of typecasting (or whatever this thing I'm
    about to show you is called), and I'm wondering if it's normal, or if
    I'm missing an important idiom.

    For example:

    bet = raw_input("Enter your bet")
    if int(bet) == 0:
    # respond to a zero bet

    Or later, I'll have an integer, and I end up doing something like
    this:

    print "You still have $" + str(money) + " remaining"

    All the time, I'm going int(this) and str(that). Am I supposed to?
     
    sprad, Jan 2, 2009
    #1
    1. Advertising

  2. sprad schrieb:
    > I've done a good bit of Perl, but I'm new to Python.
    >
    > I find myself doing a lot of typecasting (or whatever this thing I'm
    > about to show you is called), and I'm wondering if it's normal, or if
    > I'm missing an important idiom.


    It is normal, although below you make things needlessly complicated.

    Python is strongly typed, which is a good thing. It refuses to guess you
    mean when you multiply a string with a number. Or how a number is to be
    formatted when printed.

    > For example:
    >
    > bet = raw_input("Enter your bet")
    > if int(bet) == 0:
    > # respond to a zero bet



    You might better do

    bet = int(raw_input("Enter your bet"))

    because then you don't need to later on convert bet again and again.

    But *one* conversion you need.

    > Or later, I'll have an integer, and I end up doing something like
    > this:
    >
    > print "You still have $" + str(money) + " remaining"


    This is more concisely & with much better control over the output-format
    (think e.g. digits of a fraction) using string-interpolation. See

    http://docs.python.org/library/stdtypes.html#string-formatting-operations

    for an overview.

    In your case, a simple

    print "You still have $%i remaining" % bet

    does the trick.

    Diez
     
    Diez B. Roggisch, Jan 2, 2009
    #2
    1. Advertising

  3. You can use the built-in string formatting options and operations.
    2.5: http://www.python.org/doc/2.5.2/lib/typesseq-strings.html
    2.6: http://docs.python.org/library/string.html

    In essence, you can do:

    print "You still have $%i remaining" %(money)

    On Jan 2, 2:15 pm, sprad <> wrote:
    > I've done a good bit of Perl, but I'm new to Python.
    >
    > I find myself doing a lot of typecasting (or whatever this thing I'm
    > about to show you is called), and I'm wondering if it's normal, or if
    > I'm missing an important idiom.
    >
    > For example:
    >
    > bet = raw_input("Enter your bet")
    > if int(bet) == 0:
    >     # respond to a zero bet
    >
    > Or later, I'll have an integer, and I end up doing something like
    > this:
    >
    > print "You still have $" + str(money) + " remaining"
    >
    > All the time, I'm going int(this) and str(that). Am I supposed to?
     
    TechieInsights, Jan 2, 2009
    #3
  4. sprad

    vk Guest

    > You might better do
    >
    > bet = int(raw_input("Enter your bet"))
    >
    > because then you don't need to later on convert bet again and again.


    This is all fine until you give it to an end-user.
    This is what I picture:

    $ ./script.py
    Enter your bet: $10

    ... or perhaps "ten", "all", or a jillion other tainted inputs.

    Python will try to cast these strings, but will slap you with a
    ValueError instead (an error of some sort, at least).


    There needs to be a "user_io" or "sanitize" module in the standard
    library to take care of this stuff.
    Like:

    import userio

    logic = userio.userio()

    number = logic.getNumeric("blah: ") # will offer the user a "re-do" in
    case of bad input
    number = logic.forceGetNumeric("Enter your bet!: ") # even if input is
    tainted, will return some number

    text = logic.getText("blargh: ") # return all text

    text = logic.setValidText("[A-Za-z]")
    text = logic.forceGetText("blargh: ") # return some text, strips
    invalid chars


    .... but there isn't, as far as I know.
     
    vk, Jan 2, 2009
    #4
  5. On Fri, 2 Jan 2009 14:36:04 -0800 (PST) vk <> wrote:

    > There needs to be a "user_io" or "sanitize" module in the standard
    > library to take care of this stuff.
    > [snip example]
    >

    Great idea! +1


    > ... but there isn't, as far as I know.

    Well, get to it, then. ;)

    /W

    --
    My real email address is constructed by swapping the domain with the
    recipient (local part).
     
    Andreas Waldenburger, Jan 2, 2009
    #5
  6. sprad

    r Guest

    > There needs to be a "user_io" or "sanitize" module in the standard
    > library to take care of this stuff.

    [snip]

    +1
    You are sooo right. You know, it is easy to forget about such things
    after you learn a language, i have written my own input logic, but i
    remember my __init__ days with python now and the learning curve.

    Every new user will makes much use of raw_input()[or input 3.0] and
    has to climb this same little hill every time, you and i do it as
    second nature. A small module like you describe would be a great
    addition to the standard library, and heck, i would even use it :)
     
    r, Jan 2, 2009
    #6
  7. sprad

    vk Guest

    > If there were, I would expect it to conform with PEP 8 (get those ugly
    > camelCase names outta there :)


    haha, please forgive me.
    I'll try and think of some more creative names.

    atm, I've got a chem final to study for.
    I'll probably post something resembling useful code tomorrow morning.

    until then, int(input()) away!
     
    vk, Jan 3, 2009
    #7
  8. On Fri, 2 Jan 2009 16:16:10 -0800 (PST) vk <> wrote:

    > > If there were, I would expect it to conform with PEP 8 (get those
    > > ugly camelCase names outta there :)

    >
    > haha, please forgive me.
    > I'll try and think of some more creative names.


    FYI: The names themselves aren't he problem at all. They just should
    be all_lowercase_with_underscores if they're functions or variables.
    CamelCase (with initial capital!) is "reserved" for classnames only.

    /W

    --
    My real email address is constructed by swapping the domain with the
    recipient (local part).
     
    Andreas Waldenburger, Jan 3, 2009
    #8
  9. sprad

    r Guest

    On Jan 2, 6:26 pm, Andreas Waldenburger <> wrote:
    > On Fri, 2 Jan 2009 16:16:10 -0800 (PST) vk <> wrote:
    >
    > > > If there were, I would expect it to conform with PEP 8 (get those
    > > > ugly camelCase names outta there :)  

    >
    > > haha, please forgive me.
    > > I'll try and think of some more creative names.

    >
    > FYI: The names themselves aren't he problem at all. They just should
    > be all_lowercase_with_underscores if they're functions or variables.
    > CamelCase (with initial capital!) is "reserved" for classnames only.
    >
    > /W
    >
    > --
    > My real email address is constructed by swapping the domain with the
    > recipient (local part).


    FYI camelCase with __init__ capital is called "title case" try this:

    >>> 'hello world".title()
     
    r, Jan 3, 2009
    #9
  10. On Fri, 2 Jan 2009 16:44:11 -0800 (PST) r <> wrote:

    > On Jan 2, 6:26 pm, Andreas Waldenburger <> wrote:
    > > On Fri, 2 Jan 2009 16:16:10 -0800 (PST) vk <> wrote:
    > >
    > > > > If there were, I would expect it to conform with PEP 8 (get
    > > > > those ugly camelCase names outta there :)  

    > >
    > > > haha, please forgive me.
    > > > I'll try and think of some more creative names.

    > >
    > > FYI: The names themselves aren't he problem at all. They just should
    > > be all_lowercase_with_underscores if they're functions or variables.
    > > CamelCase (with initial capital!) is "reserved" for classnames only.
    > >
    > > /W
    > >
    > > --
    > > My real email address is constructed by swapping the domain with the
    > > recipient (local part).

    >
    > FYI camelCase with __init__ capital is called "title case" try this:
    >

    OK, since we're smartassing anyway: CamelCase refers specifically to
    compound words or phrases that are conjoined, that is, written without
    spaces between the words, where words are separated by writing their
    respective first letters in capitals. Title case however refers to
    normal phrases where (space separated) words are capitalized, and no
    inner capitals occur (unless of course actual CamelCase words are used
    in the phrase).

    You even assumed that distinction in your example:
    > >>> 'hello world".title()


    /W

    --
    My real email address is constructed by swapping the domain with the
    recipient (local part).
     
    Andreas Waldenburger, Jan 3, 2009
    #10
  11. sprad

    John Machin Guest

    On Jan 3, 11:16 am, vk <> wrote:
    > > If there were, I would expect it to conform with PEP 8 (get those ugly
    > > camelCase names outta there :)

    >
    > haha, please forgive me.
    > I'll try and think of some more creative names.
    >
    > atm, I've got a chem final to study for.
    > I'll probably post something resembling useful code tomorrow morning.
    >
    > until then, int(input()) away!


    Building on the earlier example (entering the amount of money for a
    bet), consider the following possibilities:
    10
    $10
    USD 10.00
    USD 10,00 # many European locales
    10000 # moving to the high rollers table
    10,000
    10.000 # European
    10T # T -> thousand

    dates:
    1/12/35 # 1 December or 12 January? What year? 2035? Perhaps not, if
    the prompt was 'Enter pensioner's date of birth -> '.

    etc etc ... IOW consider not biting off more than you can chew.

    Also consider that raw_input is not sufficiently frequently used in
    real-world applications to warrant a data validation library to be
    built on top of it.
     
    John Machin, Jan 3, 2009
    #11
  12. sprad

    Steve Holden Guest

    Ben Finney wrote:
    > vk <> writes:
    >
    >>> If there were, I would expect it to conform with PEP 8 (get those
    >>> ugly camelCase names outta there :)

    >> haha, please forgive me.
    >> I'll try and think of some more creative names.

    >
    > They don't need to be creative; they merely need to conform with the
    > naming scheme as laid out in the PEP.
    >

    They don't *need* to do that. It's just a good habit to get into if you
    plan to write code that gets read and possibly modified by other people.

    If you write a function called doSomething the PSU won't

    "%@#&%":,,.. carrier lost
     
    Steve Holden, Jan 3, 2009
    #12
  13. sprad

    Guest

    On Jan 2, 7:20 pm, Ben Finney <>
    wrote:
    > vk <> writes:
    > > > If there were, I would expect it to conform with PEP 8 (get those
    > > > ugly camelCase names outta there :)

    >
    > > haha, please forgive me.
    > > I'll try and think of some more creative names.

    >
    > They don't need to be creative; they merely need to conform with the
    > naming scheme as laid out in the PEP.


    If it's something to be included in the standard library, I agree
    (just for consistency, not because using_underscores is better).

    But for user code, I prefer mixedCase.

    +1 for mixedCase!

    Sebastian
     
    , Jan 3, 2009
    #13
  14. sprad

    r Guest

    On Jan 2, 6:57 pm, Andreas Waldenburger <> wrote:
    [snip]
    > You even assumed that distinction in your example:
    >
    > > >>> 'hello world".title()

    [snip]

    sorry, here is TitleCase.py_b2
    py> 'hello world'.title().replace(' ', '')
     
    r, Jan 3, 2009
    #14
  15. On Fri, 02 Jan 2009 21:02:19 -0500, Steve Holden wrote:

    > Ben Finney wrote:
    >> vk <> writes:
    >>
    >>>> If there were, I would expect it to conform with PEP 8 (get those
    >>>> ugly camelCase names outta there :)
    >>> haha, please forgive me.
    >>> I'll try and think of some more creative names.

    >>
    >> They don't need to be creative; they merely need to conform with the
    >> naming scheme as laid out in the PEP.
    >>

    > They don't *need* to do that.


    They do if you want it accepted into the standard library, which was the
    hope.

    Not *my* hope, you understand, but that of the person who suggested it :)



    --
    Steven
     
    Steven D'Aprano, Jan 3, 2009
    #15
  16. sprad

    Russ P. Guest

    On Jan 2, 6:15 pm, wrote:
    > On Jan 2, 7:20 pm, Ben Finney <>
    > wrote:
    >
    > > vk <> writes:
    > > > > If there were, I would expect it to conform with PEP 8 (get those
    > > > > ugly camelCase names outta there :)

    >
    > > > haha, please forgive me.
    > > > I'll try and think of some more creative names.

    >
    > > They don't need to be creative; they merely need to conform with the
    > > naming scheme as laid out in the PEP.

    >
    > If it's something to be included in the standard library, I agree
    > (just for consistency, not because using_underscores is better).
    >
    > But for user code, I prefer mixedCase.
    >
    > +1 for mixedCase!
    >
    > Sebastian


    I agree. I find underscores in variable names to be both ugly and
    harder to read. At first glance, the underscores are easy to miss.
     
    Russ P., Jan 3, 2009
    #16
  17. sprad

    vk Guest

    > etc etc ... IOW consider not biting off more than you can chew.

    It's possible that I am, but where's the fun without the risk?
    Good thinking in your post though!

    I will add "get_date" at some point, and I've modified "get_numeric"
    already.
    All-right, the moment you've all been waiting for:

    ---------------------------------------------------------------------
    http://docs.google.com/View?docid=dgsp7w2t_2gwf447g8
    ---------------------------------------------------------------------

    Provides:
    1) user_io.user_io
    -- get_text(msg)
    -- filter_get(msg, valid_chars)
    -- get_numeric(msg)
    -- bully_numeric(msg)

    2) user_io.progress_bar
    -- ping()
    -- stop()

    Read the doc-strings for details.

    I know it isn't perfect, so just yell at me on this thread if you
    don't like something and I'll try to fix it.
    Actually, I'd rather you fix it yourself and THEN yell at me to update
    the module.

    have fun!
     
    vk, Jan 3, 2009
    #17
  18. sprad

    vk Guest

    > Unless you explicitly *never* intend sharing your code with *anyone*,
    > it's best to code all your Python code in accordance with PEP 8 anyway.


    Well said. Let's bury the puppy already.

    Anyone have something to say about the userio stuff?
     
    vk, Jan 3, 2009
    #18
  19. sprad

    vk Guest

    > Anyone have something to say about the userio stuff?

    (If you're going to post something about my coding style, I invite you
    to do something infinitely more useful:
    write crapToPep8.py {or is it crap_to_pep8?} to satisfy your sick
    fetish for consistency.)
     
    vk, Jan 3, 2009
    #19
  20. sprad a écrit :
    > I've done a good bit of Perl, but I'm new to Python.
    >
    > I find myself doing a lot of typecasting (or whatever this thing I'm
    > about to show you is called),


    Actually, it's just plain object instanciation.

    > and I'm wondering if it's normal, or if
    > I'm missing an important idiom.
    >
    > For example:
    >
    > bet = raw_input("Enter your bet")
    > if int(bet) == 0:
    > # respond to a zero bet


    raw_input() returns a string. If you want an int and the string is
    supposed to contain a legitimate string representation of an integer,
    then yes, passing the string to the int object constructor is the right
    thing to do. I'd just write it a bit diffently:

    bet = int(raw_input("Enter your bet"))
    if bet == 0:
    # code here

    or even better:

    def read_int(prompt, err="Sorry, '%s' is not a valid integer"):
    while True:
    answer = raw_input(prompt)
    try:
    return int(answer)
    except ValueError:
    print err % answer

    bet = read_int("Enter your bet")
    if bet == 0:
    # code here

    > Or later, I'll have an integer, and I end up doing something like
    > this:
    >
    > print "You still have $" + str(money) + " remaining"


    May suggest learning about string formatting ?

    print "You still have $%s remaining" % money


    But indeed, you obviously cannot add strings with numerics nor
    concatenate numerics with strings. This would make no sense.

    > All the time, I'm going int(this) and str(that). Am I supposed to?


    Depends on the context.
     
    Bruno Desthuilliers, Jan 3, 2009
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?Smlt?=

    ArrayList typecasting from binary SQL data

    =?Utf-8?B?Smlt?=, Apr 11, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    532
    Bruce Barker
    Apr 11, 2005
  2. Kapil Khosla

    Understanding Typecasting in C++

    Kapil Khosla, Jul 19, 2003, in forum: C++
    Replies:
    3
    Views:
    7,386
    John Harrison
    Jul 20, 2003
  3. Arun Prasath
    Replies:
    2
    Views:
    356
    Peter Shaggy Haywood
    Nov 26, 2003
  4. रवींदर ठाकà¥à¤° (ravinder thakur

    noob question : library versus normal python files

    रवींदर ठाकà¥à¤° (ravinder thakur, Jun 6, 2008, in forum: Python
    Replies:
    1
    Views:
    286
  5. kevin
    Replies:
    1
    Views:
    103
Loading...

Share This Page