This is from a response to a question about rational
division on the Edu-SIG list.
On Sat, 5 Feb 2000, Ka-Ping Yee wrote:
>
> In E, there are two operators for division:
>
> 2 / 3 yields 0.666666
>
> 2 _/ 3 yields 0
>
> Read "_/" as "floor-divide".
> (See http://www.eright.org/elang/grammar/expr.html.)
>
> Note that in the current Python, if a and b are integers and
> f is the floating-point result of dividing a by b, then
> a/b is *not* equal to int(f). It's equal to math.floor(f).
Then i realized that math.floor returns a float.
So, really, in order to replace the old /,
a / b
becomes
import math
int(math.floor(a / b))
As long as we're going to push forward into the realm
of sanity (and i'm in support of this change!) do we
need an easier way to spell this to help folks convert?
I rather like E's "_/" operator, but that may be harder
to swallow here since "_" goes in Python identifiers.
E allows "_" in identifiers too, but you can use spaces
to avoid ambiguity, e.g.:
a _/ b # parses as 'a' floor-divide 'b'
a_/b # parses as 'a_' float-divide 'b'
But perhaps that is just too arcane for Python.
"//" was also considered for a floor-divide operator
for a while, but Java-style comments won out.
So do we go for a new operator, or put a 'div()' in
__builtins__, or what?
> int() truncates, always rounding towards zero (an abomination
> in my opinion!), while floor() rounds down.
This is also possibly an Edu-SIG question, but don't
you think it would be nice to have a round() built-in?
I can see it being invaluable for classroom and
scientific work. Something like:
def round(x):
return int(math.floor(x + 0.5))
or even:
def round(x, unit=1):
return int(math.floor(x / unit + 0.5))*unit
-- ?!ng
"If I have not seen as far as others, it is because giants were standing
on my shoulders."
-- Hal Abelson
Hi, folks. A couple of people have suggested that I ought to start
building up a page full of links to Python modules (and Python-friendly
packages like VTK) that would be of interest to scientific and engineering
programmers. It could eventually be part of the new-look python.org, stay
at software-carpentry.com, or...? Pointers much appreciated...
Thanks,
Greg
Guido already said it all: Python is going Unicode in 1.6
and things are moving fast into that direction.
But... to make the integration rock solid, I need your
participation: please test the patch in every way you can
so that I can get it ready for prime time as soon as possible.
I am most interested in hearing about its behaviour in
mixed string/Unicode situations. The idea behind the
implementation is that strings and Unicode should inter-
operate to the greatest extent possible.
Note that the patch also includes a completely new core
feature: the codec APIs and registry. You can write
stackable streams, data converters, etc. in a generic
way and use them throughout Python. This should be especially
interesting for people in the web business who want to
provide content using many different encodings, e.g.
Latin-1, UTF-8, etc. Encryption and compression codecs
should also be possible using the new APIs.
To make things more convenient for you, I'll also put a
complete Python source distribution on the web page for
you to download -- this eliminates the need to patch the
CVS sources.
Thanks,
--
Marc-Andre Lemburg
______________________________________________________________________
Business: http://www.lemburg.com/
Python Pages: http://www.lemburg.com/python/
Greetings everybody,
During the course of implementing the Unicode proposal we
discussed here in early December I stumbled into an old
problem which has caused me some troubles already in the
early stages of writing mx.DateTime:
Most of the C slot functions are not capable of dealing
with mixed type arguments. Even worse, most expect to be
passed "their" type of arguments without even checking
them. In Python things are much better: you have the __r***___
methods, can do mixed type arguments, etc.
In short: we need the same things for the C level !
To start this discussion, I would like to point you to
an old patch I wrote for Python 1.5. It focusses mainly
on the numeric slots, but does provide some insights into
possible ways out of the current problems with C level
coercions (the business of dealing with mixed type argument):
http://starship.skyport.net/~lemburg/CoercionProposal.html
Here are some starters for the discussion. I think we need:
· slots which are able to deal with mixed type argument
· slots which do not expect to find a certain type without
checking for it
· coercion implemented at two levels:
1. a generic mixed type abstract operation mechanism (such as
the one included in the above patch for numeric types)
2. slots which can handle mixed type argument and have a
way to signal "I can't handle this type combination"
(the patch uses a special singleton for this instead of
exceptions because the latter cause too much of a perfomance
hit -- yes I've tested this).
· all of the above for the numeric slots as well as most
of the other slots dealing with PyObject* arguments
Note that these things are also needed for David Ascher's rich
comparisons.
--
Marc-Andre Lemburg
______________________________________________________________________
Business: http://www.lemburg.com/
Python Pages: http://www.lemburg.com/python/
In Include/object.h, around line 140, many pointer to functions are
typedef'ed. I need a new function type:
int (*f)(PyObject *, PyObject *)
And I'm at a bit of a los what to call it.
Anyone has any idea what the naming convention is?
Is objobjproc the right thing?
Thanks for your attention.
--
Moshe Zadka <mzadka(a)geocities.com>.
INTERNET: Learn what you know.
Share what you don't.
I taught Python at Los Alamos National Laboratory for the second time
two weeks ago, and finally found time last night to go through both
sets of feedback forms. Given the current discussion on python-dev of
ternary conditionals, namespaces, etc., I figured syntax issues would
be most topical.
Most of the students were in their 20's or 30's, with a handful in their
40's and 50's. When asked what they used on a daily basis, they split
pretty evenly between Fortran and C++ (no C-but-not-C++ responses). They
also divided pretty evenly between "numerical and/or visualization" and
"systems programming". (At the lab, the latter means everything from
making the web archive of past experimental results searchable, through to
porting HDF-5 to massively-parallel machines and hacking the Linux kernel
to make inter-process communication run faster.) 28 students had Ph.D.'s
(all in math, physical science, or engineering); nine had M.Sc.'s (one in
C.S.), and the three B.Sc.'s were all in C.S.
So here goes...
-------------------------------------------------------------------------
0. "Hey, using indentation to show nesting is cool!"
'Nuff said --- thanks, Guido.
-------------------------------------------------------------------------
1. "What's with 'while 1: break' for normal loops?"
This was the most common complaint about syntax --- neither Fortran
nor C programmers found it natural to create an infinite loop, then
jump out of it. (Several of the C++ programmers said that house style
in their groups only allows 'break' for truly exceptional cases.)
One student suggested the following loop-and-a-half notation:
do:
first-half
while condition:
second-half
which has the nice property that both of the degenerate forms:
do:
first-half
while condition # no trailing ':'
and
while condition:
second-half
are useful in their own right. Tim Peters tells me that this has been
discussed many times before, and that the main obstacle is the
introduction of a new keyword. He mentioned:
while:
first-half
and while condition-1:
second-half
and while condition-2:
third-half # [sic]
and while final-condition # no trailing ':'
as an interesting (but possibly confusing) generalization.
-------------------------------------------------------------------------
2. "Using range() in for loops is clumsy."
My audience does a lot of 'for' loops over numerical bounds, and would
prefer something slice-ish like:
for i in 0:10:2 :
body
I think they could live with:
for i in [0:10:2] :
body
I believe Brian Harvey mentions somewhere in "Computer Science Logo
Style" (the best programming books for kids I've ever seen) that it
was important to make basic counting loops very, very simple to write.
It's a different audience (10-year-olds instead of Ph.D.'s with 30
years of Fortran behind them), but maybe worth examining.
(While we're on the topic: is there an easy way to construct a slice
like 3:10, pass it around as a variable, and later use it to index an
arbitrary sequence?)
-------------------------------------------------------------------------
3. "Where is '+=' ?" and "Why can't I redefine assignment?"
To my surprise, no-one asked why assignment wasn't an operator.
However, a lot of people wanted in-place modification --- it's one of
the innovations of C and derived languages that scientific programmers
appreciate, since it saves them having to write
'pressure_gradient[(ix+1)*3+idx][iy-1-(idx%2)]' on both sides of an
assignment, and then remember to update both occurrences when they
notice the typo. (The '%' should be a '/'.)
Several of the students who ticked the box "Familiar with
object-oriented programming" asked why they could redefine addition,
membership, etc., but not straight assignment. Guido explained the
reasoning to me at IPC8, and pointed out that classes can always
define a '.set(...)' method. However, I'm pretty sure that 'set()'
will be a non-starter with this crowd (I can explain why if people
care).
-------------------------------------------------------------------------
3.1 Min and Max
On a related note, I also had requests for redefining "min" and "max"
(e.g. to handle objects representing bounding volumes in 3D graphics).
As a certain kind of mathematician will point out, these are really
binary operators, just like "+", and it's only an historical accident
that they aren't treated with the same respect (I'm quoting here).
I mentioned this to Guido, and suggested the C* notation:
a = x <? y # min
b = x >? y # max
He said (rightly) that '<?' and '>?' won't be familiar even to experienced
programmers, but that user-definable 'min' and 'max' might be do-able.
The only issue then is that if '+=' makes it into the language, something
like 'min=' ought to as well...
-------------------------------------------------------------------------
3.2 Case Statement, and Remembering Matches in Conditionals
Another related point came up in discussion of regular expressions. The
code I showed them was:
pat1 = re.compile(...)
pat2 = re.compile(...)
...etc...
while 1:
line = ...get input...
m = pat1.match(...)
if m:
code
continue
m = pat2.match(...)
if m:
code
continue
...etc...
Several students said that it wasn't at all clear that the various
matches were intended to be mutually exclusive; one student became
very frustrated trying to debug this code after accidentally deleting
a 'continue'. If there's a cleaner way to structure this, I'd be
grateful for an example.
One student (a physicist who now does computer graphics) sent me:
if x is:
expr1, expr2:
code using x (which is either val1 or val2)
expr3:
code using x (which is guaranteed to be val3)
else:
code using x (which is something else)
which would make the above:
while 1:
line = ...get input...
if m is:
pat1.match(...):
code using m
pat2.match(...):
code using m
etc.
(I'm not advocating, I'm just reporting...)
-------------------------------------------------------------------------
4. "Aren't tuples redundant?"
I explained that the const-ness of tuples was needed so that they
could be used as dictionary keys. The guy with Perl in his background
immediately asked if that's reliable --- a tuple can contain a list,
which can be mutated. You've all heard this one more times than I
have...
-------------------------------------------------------------------------
5. "Why can't I put an 'except' after an 'if'?"
This one surprised me. Several students wanted to be able to say:
if (dict['fred'] > 0):
code
except KeyError:
other-code
or:
for i in seq:
i = i ** 2
except ArithmeticError:
error-handling-code
or even (from one guy with Perl in his background):
dict['fred'] = dict['fred'] + 1
except KeyError:
dict['fred'] = 1
They pointed out that 'try' does nothing except introduce a block, so
why not just use the blocks that other keywords introduce? I'd be
interested in knowing whether other people's students think like
this... :-)
-------------------------------------------------------------------------
6. "There is no number six."
That's really all that came up about Python syntax. None of the
students were OO expects, so meta-classes and the like weren't raised.
Generic programming did come up once, but the guy who asked hadn't
clued in that typing is dynamic. The same guy also asked why he
couldn't interleave anonymous and named function arguments, as in
"def foo(a, b=3, c, d=5)" also came up, but everybody else who
expressed an opinion said they'd find that confusing.
Hope it's useful,
Greg
I propose to include functions to access the windows registry
into the python 1.6 core.
I have thrown together some code which I will post hopefully
tomorrow, but I would like to hear some comments before.
----------------------------------------------------------------------
winreg - registry access module
Constants:
HKEY_CLASSES_ROOT, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER,
HKEY_USERS - bases of registry
KEY_READ, KEY_WRITE, KEY_ALL_ACCESS - access rights
REG_SZ, REG_DWORD, REG_BINARY - typecodes for values
Exception:
error - raised when a function fails. Will usually contain
a windows error code and a textual description.
Functions:
OpenKey (base, subkey, [, rights=KEY_READ]) -> integer
Opens an existing key with the specified access rights
and returns an integer handle. The handle must be closed
by a call to CloseKey().
CreateKey (base, subkey [, sam=KEY_ALL_ACCESS]) -> integer
Creates a new subkey or opens an exsiting one
and returns an integer handle.
base must be one of the HKEY_ constants or an integer handle.
The handle must be closed by a call to CloseKey().
CloseKey (handle)
Closes a key handle.
EnumValues (handle, subkey) -> sequence
Returns a sequence containing name, value, typecode triples
for each existing value.
EnumKeys (handle, subkey) -> sequence
Returns a sequence containing the names of all subkeys.
QueryValue (handle, subkey) -> tuple
Returns a tuple containing name, value and typecode.
SetValue (handle, name, typecode, value)
Sets the value of a name to value.
value must be a string for REG_SZ or REG_BINARY,
an integer for REG_DWORD.
DeleteValue (handle, valuename)
Deletes the value.
DeleteKey (handle, name [,recursive=0)
Deletes the named key if no subkeys exist. If recursive is
given as a true value, subkeys are recursively deleted.
This is done with Reg* calls, NOT with SHDeleteKey and
SHDeleteEmptyKey functions, so should work under any
flavor of NT and Win9x.
Note: To use the SetValue and Delete* functions, the key must have
been opened with KEY_WRITE_ACCESS or KEY_ALL_ACCESS.
----------------------------------------------------------------------
Open Questions:
Is the recursive-flag for DeleteKey() too dangerous?
Should I switch from an integer handle to a full blown
python-object, which would call CloseKey() automatically in the
destructor?
A higher level interface would be nice, but this should probably
implemented
on top of this module in python.
Comments appreciated!
Thomas Heller
ION-TOF GmbH
I've sent a patch to patches(a)python.org which does the 'in' hook in the
pseudo-right way: adding a slot to the sequence methods structure, and
adding a flag to support it for backwards compatability.
Now that it's there, I've also changed instance method to use it, and to
map it to __contains__. The code there also has special-case for strings,
so if someone (maybe me) adds such a slot to strings, then the code will
only have to do the C equivalent of
try:
obj.__contains__(whatever)
except AttributeError:
for element in obj:
if element == whatever:
return 1
return 0
Is this desirable? It shouldn't be too hard...
--
Moshe Zadka <mzadka(a)geocities.com>.
INTERNET: Learn what you know.
Share what you don't.
Have we decided not to do anything to take the load off of our poor Guido?
Where have the discussion gone?
Perhaps someone should just do something? (hint, hint, nudge, nudge,
people whose name starts with B <wink>)
--
Moshe Zadka <mzadka(a)geocities.com>.
INTERNET: Learn what you know.
Share what you don't.