Noob question: Is all this typecasting normal?

S

sprad

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?
 
D

Diez B. Roggisch

sprad said:
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
 
V

vk

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.
 
R

r

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 :)
 
V

vk

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!
 
A

Andreas Waldenburger

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
 
R

r

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

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

Andreas Waldenburger

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:
/W
 
J

John Machin

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.
 
S

Steve Holden

Ben said:
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
 
S

s0suk3

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
 
R

r

[/QUOTE]
[snip]

sorry, here is TitleCase.py_b2
py> 'hello world'.title().replace(' ', '')
 
S

Steven D'Aprano

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 :)
 
R

Russ P.

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.
 
V

vk

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!
 
V

vk

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?
 
V

vk

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.)
 
B

Bruno Desthuilliers

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top