Re: Recommend decent Computer Science books

2012-06-27 Thread Greg
On Wednesday, June 27, 2012 2:00:03 PM UTC-7, David Thomas wrote:
> Hi I know that this is a group about Python.  But I am just wondering if 
> anybody can recommend any introductory/good books on Conputer Science.
> 
> Kind regards

I recommend "Python Programming: An Introduction to Computer Science" - 2nd
Edition by John Zelle.

Regards,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Having trouble getting Hello World to appear

2022-04-21 Thread Greg
I downloaded and installed the auto version of the software.

I go to the director C:\google-python-exercises> *python hello.py*

I am running Windows.



What am I doing incorrectly?



I had the zip file installed under my One Drive and then moved it to my C
drive



Patiently waiting,

Greg
-- 
https://mail.python.org/mailman/listinfo/python-list


Verifying I installed Python correctly

2022-04-25 Thread Greg
I am trying to get Hello World to appear under my directory. The files of

*C:\Users\gd752>cd C:\google-python-exercises> python hello.py*
*The system cannot find the path specified.*

*C:\Users\gd752>cd C:\google-python-exercises>*
*The syntax of the command is incorrect.*

I installed version 3.10. I am stuck and could use some help.
Thx,


[image: directory pic.png]
-- 
https://mail.python.org/mailman/listinfo/python-list


odd behavior

2005-11-11 Thread Greg
Forgive me, and be kind, as I am just a newby learning this language
out of M.L. Hetland's book.  The following behavior of 2.4.1 seems very
strange
>>> x = ['aardvark', 'abalone', 'acme', 'add',
 'aerate']
>>> x.sort(key=len)
>>> x
['add', 'acme', 'aerate', 'abalone', 'aardvark']
>>> x.sort(reverse=True)
>>> x
['aerate', 'add', 'acme', 'abalone', 'aardvark']
The function called on line 4, at least to me, should work on x as it
was on line 3, not the previously existing x on line 1.  What gives?
By the way these functions do not exist in 2.3.5 so they must be newly
implemented.

-- 
http://mail.python.org/mailman/listinfo/python-list


Read 16 bit integer complex data

2005-04-07 Thread Greg
Hi,

I'm new to python, I don't have a whole lot of programming experience
aside from Matlab.  I hope you'll excuse my ignorance.

I'm trying to figure out how to read in 16 bit integer complex data.
Each 16 bits alternate, first 16 bits represent the real part of the
number, next 16 bits represent the imaginary.

I've looked at the "unpack" command, but from what I can tell it isn't
really efficient for a large data sample.

Is there a command or method around to read in large amounts of 16 bit
complex data?

Thanks in advance for your help,

Greg

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read 16 bit integer complex data

2005-04-07 Thread Greg
That worked, thanks a lot.
Greg

-- 
http://mail.python.org/mailman/listinfo/python-list


encoding problem with BeautifulSoup - problem when writing parsed text to file

2011-10-05 Thread Greg
Hi, I am having some encoding problems when I first parse stuff from a
non-english website using BeautifulSoup and then write the results to
a txt file.

I have the text both as a normal (text) and as a unicode string
(utext):
print repr(text)
'Branie zak\xc2\xb3adnik\xc3\xb3w'

print repr(utext)
u'Branie zak\xb3adnik\xf3w'

print text or print utext (fileSoup.prettify() also shows 'wrong'
symbols):
Branie zak³adników


Now I am trying to save this to a file but I never get the encoding
right. Here is what I tried (+ lot's of different things with encode,
decode...):
outFile=open(filePath,"w")
outFile.write(text)
outFile.close()

outFile=codecs.open( filePath, "w", "UTF8" )
outFile.write(utext)
outFile.close()

Thanks!!





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: encoding problem with BeautifulSoup - problem when writing parsed text to file

2011-10-05 Thread Greg
Brilliant! It worked. Thanks!

Here is the final code for those who are struggling with similar
problems:

## open and decode file
# In this case, the encoding comes from the charset argument in a meta
tag
# e.g. 
fileObj = open(filePath,"r").read()
fileContent = fileObj.decode("iso-8859-2")
fileSoup = BeautifulSoup(fileContent)

## Do some BeautifulSoup magic and preserve unicode, presume result is
saved in 'text' ##

## write extracted text to file
f = open(outFilePath, 'w')
f.write(text.encode('utf-8'))
f.close()



On Oct 5, 11:40 pm, Steven D'Aprano  wrote:
> On Wed, 05 Oct 2011 16:35:59 -0700, Greg wrote:
> > Hi, I am having some encoding problems when I first parse stuff from a
> > non-english website using BeautifulSoup and then write the results to a
> > txt file.
>
> If you haven't already read this, you should do so:
>
> http://www.joelonsoftware.com/articles/Unicode.html
>
> > I have the text both as a normal (text) and as a unicode string (utext):
> > print repr(text)
> > 'Branie zak\xc2\xb3adnik\xc3\xb3w'
>
> This is pretty much meaningless, because we don't know how you got the
> text and what it actually is. You're showing us a bunch of bytes, with no
> clue as to whether they are the right bytes or not. Considering that your
> Unicode text is also incorrect, I would say it is *not* right and your
> description of the problem is 100% backwards: the problem is not
> *writing* the text, but *reading* the bytes and decoding it.
>
> You should do something like this:
>
> (1) Inspect the web page to find out what encoding is actually used.
>
> (2) If the web page doesn't know what encoding it uses, or if it uses
> bits and pieces of different encodings, then the source is broken and you
> shouldn't expect much better results. You could try guessing, but you
> should expect mojibake in your results.
>
> http://en.wikipedia.org/wiki/Mojibake
>
> (3) Decode the web page into Unicode text, using the correct encoding.
>
> (4) Do all your processing in Unicode, not bytes.
>
> (5) Encode the text into bytes using UTF-8 encoding.
>
> (6) Write the bytes to a file.
>
> [...]
>
> > Now I am trying to save this to a file but I never get the encoding
> > right. Here is what I tried (+ lot's of different things with encode,
> > decode...):
> > outFile=codecs.open( filePath, "w", "UTF8" )
> > outFile.write(utext)
> > outFile.close()
>
> That's the correct approach, but it won't help you if utext contains the
> wrong characters in the first place. The critical step is taking the
> bytes in the web page and turning them into text.
>
> How are you generating utext?
>
> --
> Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SDL doesn't cope well with FreeSans

2006-07-26 Thread greg
Carl Banks wrote:
> Greg Ewing wrote:
> > The characters come out slightly
> > higglety-pigglety -- randomly displaced up or down
> > a pixel or so from the baseline.

> It would depend on how you're displaying them, I would think.

I've seen the same thing happen two different ways:
* Rendering with PyGame's font functions
* With Soya, which is using OpenGL textures

Both of these are using FreeType to do the rastering,
I believe.

> 2. Convert it to a type 1 font and see if the problem remains.

Can FreeType deal with Type 1 fonts? Also, what utility
would I use to do that (preferably on MacOSX).

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter--does anyone use it for sophisticated GUI development?

2006-10-20 Thread greg
Paul Rubin wrote:

> I have yet to see a gui toolkit which doesn't suck.  I'm not sure why
> that is.

Have you seen PyGUI? It's my attempt at creating
a GUI toolkit for Python that doesn't suck. I'd
be interested to know if you think I've come
anywhere near to succeeding.

http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import confused by contents of working directory

2006-06-03 Thread greg
Jon wrote:
> It appears that (windows) python searches in the current working
> directory before looking in the local site-packages directory, or that
> '.' comes first in sys.path?

Unless it behaves very differently on Windows from
everything else, this isn't quite true. The current
directory is only put in the path when using the
interpreter interactively. When you do

   python somefile.py

the directory containing somefile.py is put at the
beginning of sys.path, not the current directory.
So you'd still have the same problem even if you
weren't cd'ed to the directory containing the test
program.

The moral is not to put your test program in the
same directory as your package files. (Or if you
must, have it delete sys.path[0] before importing
anything.)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Selection in Tkinter Text widget.

2006-06-03 Thread greg
Ant wrote:

> Strange behaviour though (IMHO), that the selection is only shown if
> the widget has focus.

It's only strange if you're used to certain platforms.
This is normal behaviour in the Macintosh world. One
of the original Apple UI Guidelines was that there
should only be one selection visible at a time, so
that it's always clear what you're operating on.

(They seem to be breaking that now in MacOSX, which
I think is a backward step...)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to Python: Do we have the concept of Hash in Python?

2006-06-03 Thread greg
A.M wrote:

> In essence, Ruby language is the best, but Ruby platform is too young for 
> me. I'll give Ruby another two years and come back to it again.
> 
> I found the Python language quite powerful and easy. With mature and strong 
> community support.

Welcome aboard. It'll be interesting to see whether
you *still* want to switch back to Ruby after getting
to know Python for two years!

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing zero-dimensional subscripts

2006-06-10 Thread greg
Carl Banks wrote:

> Think of it this way: an array with n-dimensions of length 3 would have
> 3**n total entries.  How many entries would a 0-dimensional array have?
>  3**0 == 1.

Er, hang on a minute. Along which dimension of this
0-dimensional array does it have a length of 3? :-)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding extra frames to traceback in C module

2006-06-10 Thread greg
Roger Binns wrote:
> One thing I would like to do in my extension module is
> add extra frames to the traceback when an extension
> occurs.
>
> I did find snippets of code
> doing things like PyTraceback_Here but they use a real
> Python frame which I don't have and don't know how to
> synthesize.

This is the code Pyrex uses to add frames to the traceback.
It creates a fake frame object and fills in just enough
of it to keep the traceback printing code happy.

Or you could just use Pyrex for your extension module
in the first place, and get it done for you automatically.

---
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"

static void __Pyx_AddTraceback(char *funcname) {
   PyObject *py_srcfile = 0;
   PyObject *py_funcname = 0;
   PyObject *py_globals = 0;
   PyObject *empty_tuple = 0;
   PyObject *empty_string = 0;
   PyCodeObject *py_code = 0;
   PyFrameObject *py_frame = 0;

   py_srcfile = PyString_FromString(%(FILENAME)s);
   if (!py_srcfile) goto bad;
   py_funcname = PyString_FromString(funcname);
   if (!py_funcname) goto bad;
   py_globals = PyModule_GetDict(%(GLOBALS)s);
   if (!py_globals) goto bad;
   empty_tuple = PyTuple_New(0);
   if (!empty_tuple) goto bad;
   empty_string = PyString_FromString("");
   if (!empty_string) goto bad;
   py_code = PyCode_New(
 0,/*int argcount,*/
 0,/*int nlocals,*/
 0,/*int stacksize,*/
 0,/*int flags,*/
 empty_string, /*PyObject *code,*/
 empty_tuple,  /*PyObject *consts,*/
 empty_tuple,  /*PyObject *names,*/
 empty_tuple,  /*PyObject *varnames,*/
 empty_tuple,  /*PyObject *freevars,*/
 empty_tuple,  /*PyObject *cellvars,*/
 py_srcfile,   /*PyObject *filename,*/
 py_funcname,  /*PyObject *name,*/
 %(LINENO)s,   /*int firstlineno,*/
 empty_string  /*PyObject *lnotab*/
   );
   if (!py_code) goto bad;
   py_frame = PyFrame_New(
 PyThreadState_Get(), /*PyThreadState *tstate,*/
 py_code, /*PyCodeObject *code,*/
 py_globals,  /*PyObject *globals,*/
 0/*PyObject *locals*/
   );
   if (!py_frame) goto bad;
   py_frame->f_lineno = %(LINENO)s;
   PyTraceBack_Here(py_frame);
bad:
   Py_XDECREF(py_srcfile);
   Py_XDECREF(py_funcname);
   Py_XDECREF(empty_tuple);
   Py_XDECREF(empty_string);
   Py_XDECREF(py_code);
   Py_XDECREF(py_frame);
}

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: PyGUI 1.7.2

2006-06-10 Thread greg
PyGUI 1.7.2 is now available:

   http://www.cosc.canterbury.ac.nz/~greg/python_gui/

This version adds support for multiple mouse buttons,
mouse enter and leave events, enhancements to the BlobEdit
example application, and a big pile of other enhancements
and bug fixes. See the CHANGES.txt file in the distribution
or on the website for details.


What is PyGUI?
--

PyGUI is an experimental highly-Pythonic cross-platform
GUI API. Implementations are currently available for
MacOSX and Gtk. For a full description of the project
goals, see the PyGUI web page at the above address.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: PyGUI 1.7.2-1

2006-06-10 Thread greg
I have uploaded a new PyGUI 1.7.2 package to correct
a couple of errors in the setup.py file.

http://www.cosc.canterbury.ac.nz/~greg/python_gui/

-

What is PyGUI?
--

PyGUI is an experimental highly-Pythonic cross-platform
GUI API. Implementations are currently available for
MacOSX and Gtk. For a full description of the project
goals, see the PyGUI web page at the above address.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyGUI 1.7.2-1

2006-06-12 Thread greg

[EMAIL PROTECTED] wrote:


if I try to run blobedit.py in the IDLE ide ...

> the path is equal to "8833" for some

reason.


I believe that IDLE sets up some kind of debugging
connection to its child process. That number might
be a processs ID or port number or something related
to that.


I tried to hunt down where the problem occurs, but I was led
to the method "application_openFile_(self, ns_app, path)" in the
class _PyGui_NSApplication. I couldn't find out how this method
ever got called though.


It's called by the Cocoa framework to handle files
passed to the application from the Finder. It also
seems to get called when there are command-line
arguments. But it works on the C-level argv, which
means it can pick up stuff that doesn't normally
end up in sys.argv. The check for sys.argv[0]
is there to work around one of the side effects of
that. It appears that you've encountered another
one.

I'm using a different method of dealing with
this now, which will probably fix your problem as
well. I've attached a replacement for
GUI/Cocoa/Applications.py. Let me know if it
works for you.

--
Greg
#
#   Python GUI - Application class - PyObjC
#

import os, sys, traceback
import objc
#from ExceptionHandling import \
#   NSExceptionHandler, NSLogUncaughtExceptionMask, 
NSLogAndHandleEveryExceptionMask
from Foundation import NSObject, NSBundle, NSDefaultRunLoopMode
import AppKit
from AppKit import NSApplication, NSResponder, NSScreen, NSMenu, NSMenuItem, \
NSKeyDown, NSKeyUp, NSMouseMoved, NSLeftMouseDown, NSSystemDefined, \
NSCommandKeyMask, NSPasteboard, NSStringPboardType, 
NSModalPanelRunLoopMode, \
NSAnyEventMask
import GApplications
from GApplications import application, Application as GApplication
from Events import Event
from Exceptions import Cancel, Quit
from Menus import _ns_standard_actions

#--

ns_application = None
ns_screen_height = None
ns_last_mouse_moved_event = None

#--

class Application(GApplication):
#  _ns_app  _PyGui_NSApplication
#  _ns_pasteboard   NSPasteboard
#  _ns_key_window   Window

_ns_menubar_update_pending = False

def __init__(self, **kwds):
#print "Application.__init__: argv =", sys.argv ###
create_ns_application()
self._ns_app = ns_application
self._ns_app.pygui_app = self
self._ns_init_standard_menu_items()
self._ns_pasteboard = NSPasteboard.generalPasteboard()
self._ns_key_window = None
GApplication.__init__(self, **kwds)
ns_application.init_application_name()

def destroy(self):
del self.menus[:]
import Windows
Windows._ns_zombie_window = None
self._ns_app.pygui_app = None
self._ns_app = None
self._ns_pasteboard = None
GApplication.destroy(self)

def set_menus(self, menu_list):
GApplication.set_menus(self, menu_list)
self._update_menubar()

def _update_menubar(self):
ns_app = self._ns_app
ns_menubar = NSMenu.alloc().initWithTitle_("")
menu_list = self._effective_menus()
for menu in menu_list:
ns_item = NSMenuItem.alloc()
ns_item.initWithTitle_action_keyEquivalent_(menu.title, 
'', "")
ns_menubar.addItem_(ns_item)
ns_menu = menu._ns_menu
#  An NSMenu can only be a submenu of one menu at a 
time, so
#  remove it from the old menubar if necessary.
old_supermenu = ns_menu.supermenu()
if old_supermenu:
i = 
old_supermenu.indexOfItemWithSubmenu_(ns_menu)
old_supermenu.removeItemAtIndex_(i)
ns_menubar.setSubmenu_forItem_(ns_menu, ns_item)
ns_app.setMainMenu_(ns_menubar)
# Apple's docs fail to explain that the menu you pass to 
setAppleMenu_
# must *also* be a member of the menu bar.
ns_app_menu = menu_list[0]._ns_menu
self._ns_app.setAppleMenu_(ns_app_menu)

def handle_events(self):
#print "Application.handle_events: entering NS run loop" ###
#try:
self._ns_app.run()
#finally:
#print "Application.handle_events: exiting NS run loop" 
###

def handle_next_even

ANN: Albow - A simple widget library for Pygame

2006-12-06 Thread greg
ALBOW - A Little Bit of Widgetry for PyGame
---

Version 1.0

This is a very basic, no-frills widget set for creating a GUI using
PyGame. It was originally developed for my PyWeek 3 competition entry,
Sneak. I am documenting and releasing it as a separate package so that
others may benefit from it, and so that it will be permissible for use
in future PyGame entries.

The download includes HTML documentation and an example program
demonstrating most of the library's features.

http://www.cosc.canterbury.ac.nz/greg.ewing/python/Albow/

--
Gregory Ewing
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-09 Thread greg
Bill Atkins wrote:
> And mistakes in nesting show up as mistakes in
> indenting.

Er, hang on a moment... how do you *know* when you've
got a mistake in indending? You must be visually
verifying the indentation... rather like one does
with Python code...

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatic debugging of copy by reference errors?

2006-12-09 Thread greg
Niels L Ellegaard wrote:
> I wanted to warn the user whenever he tried to
> change an object that was being refered to by a living object.

To see how fundamentally misguided this idea is,
consider that, under your proposal, the following
program would produce a warning:

   a = 1

The reason being that the assignment is modifying
the dictionary holding the namespace of the main
module, which is referred to by the main module
itself. So you are "changing an object that is
being referred to by a living object".

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-11 Thread greg
[EMAIL PROTECTED] wrote:
> compilers are GREATLY facilitated by having a
> macro facility because (at first blush) all you need to do is to
> macro-expand down to something you know how to turn into code.

There's no way you could compile Python to efficient
machine code just by macro expansion. You'd also need
some very heavy-duty type inferencing.

Python is extremely dynamic, even more so than Lisp.
That's why compiling Python is hard, not because it
doesn't have macros.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-11 Thread greg
Ken Tilton wrote:

> But with Lisp one does not have to clean up the indentation manually 
> after thrashing away at ones code.

That's not how I would describe the experience
I have when I'm editing Python code.

When moving a set of statements in Python, you
are usually selecting a set of complete lines,
cutting them out and then pasting them in
between two other lines somewhere else.

Having done that, the lines you've just pasted
in are selected. Now it's just a matter of
using using your editor's block-shifting commands
to move them left or right until they're in
the correct horizontal position.

I find this to be quite a smooth and natural
process -- no "thrashing" involved at all.

Having edited both Lisp and Python code fairly
extensively, I can't say that I find editing
Python code to be any more difficult or error
prone.

On the plus side, Python makes less demands on the
capabilities of the editor. All you really need
is block-shifting commands. Bracket matching is
handy for expressions but not vital, and you
certainly don't need bracket-based auto-indenting.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatic debugging of copy by reference errors?

2006-12-11 Thread greg
Russ wrote:
> The copy by reference semantics of Python give it great
> efficiency but are also its achille's heel for tough-to-find bugs.

You need to stop using the term "copy by reference",
because it's meaningless. Just remember that assignment
in Python is always reference assignment. If you want
something copied, you need to be explicit about it.

> I later discovered that a
> particularly nasty bug was due to the fact that my constructor "copied"
> the initializing list by reference.

The reason you made that mistake was that you were
using the wrong mental model for how assignment works
in Python -- probably one that you brought over from
some other language.

When you become more familiar with Python, you won't
make mistakes like that anywhere near as often. And
if you do, you'll be better at recognising the
symptoms, so the cause won't be hard to track down.

> So a fundamental question in Python, it seems to me, is when to take
> the performance hit and use "copy" or "deepcopy."

Again, this is something you'll find easier when
you've had more experience with Python. Generally,
you only need to copy something when you want an
independent object that you can manipulate without
affecting anything else, although that probably
doesn't sound very helpful.

In your vector example, it depends on whether you
want your vectors to be mutable or immutable. It
sounds like you were treating them as mutable, i.e.
able to be modified in-place. In that case, each
vector obviously needs to be a new object with the
initial values copied into it.

The alternative would be to treat your vectors as
immutable, i.e. once created you never change their
contents, and any operation, such as adding two
vectors, produces a new vector holding the result.
In that case, two vectors could happily share a
reference to a list of values (as long as there is
nothing else that might modify the contents of the
list).

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-11 Thread greg
Bill Atkins wrote:
> You're missing Ken's point, which is that in Lisp an s-expression
> represents a single concept - I can cut out the second form of an IF
> and know that I'm cutting the entire test-form.

For selecting a single form, that's true. For
more than one form (such as selecting some, but
not all, of the statements in a loop body) it's
not much different.

But my point was that I don't find "manually
reindenting the lines" to be a chore. He made it
sound like you have to laboriously go through
and adjust the lines one by one, but it's not
like that at all. You shift them all at once
in a block.

>>Having edited both Lisp and Python code fairly
>>extensively,
> 
> How extensively?

Enough to know what I'm talking about. Tens
of thousands of lines of Lisp and Scheme, and
hundreds of thousands of lines of Python, I
would estimate.

Seeing as you asked, how much Python code have
you or Ken edited?

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-11 Thread greg
[EMAIL PROTECTED] wrote:
> So if you guys would just fix
> your language by adding homogeneous syntax and all that it brings with
> it (macros, compilers, etc) we'd be happy to use your version of Lisp,
> and all its great libraries, instead of ours! :-)

But if we did that, it wouldn't be Python any
more, it'd be Lisp. And then all those great
libraries wouldn't work with it, because they're
for Python, not Lisp. :-(

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-11 Thread greg
Bill Atkins wrote:
> greg <[EMAIL PROTECTED]> writes:
> 
> > There's no way you could compile Python to efficient
> > machine code just by macro expansion. You'd also need
> > some very heavy-duty type inferencing.
> 
> A compiler shifts a lot of decisions that an
> interpreter would have to make at runtime to compile-time.  There is
> no reason a dynamic language can't enjoy this efficiency.

I'm not saying that it's impossible to compile
Python, only that's there's a lot more to it than
just macro expansion. The OP was saying something
like "If you added macros, you might get a compiler
for free", which is clearly far from true.

> if Python is doing a hash lookup on every function call,
> as Alex Mizrahi claims, compilation may not do much to smooth over
> such awkwardness.

As currently implemented, CPython does a dictionary
lookup or two every time a module global or builtin
(which most stand-alone functions are) is referenced.
It would actually be relatively easy to optimise this
into an array lookup in most cases, but most calls in
Python code tend to be *method* calls, which are rather
harder to deal with. Possibly cacheing of method
lookups would help, although I don't know of anyone
having tried it.

> > Python is extremely dynamic, even more so than Lisp.
> 
> Uh huh.  "More so than Lisp"?  Just making stuff up now?

When a Lisp compiler sees

   (setq c (+ a b))

it can reasonably infer that the + is the built-in numeric
addition operator. But a Python compiler seeing

   c = a + b

can't tell *anything* about what the + means without
knowing the types of a and b. They might be numbers, or
strings, or lists, or some user-defined class with its
own definition of addition.

 From another angle, think about what a hypothetical
Python-to-Lisp translator would have to do. It couldn't
just translate "a + b" into "(+ a b)". It would have
to be something like "(*python-add* a b)" where
*python-add* is some support function doing all the
dynamic dispatching that the Python interpreter would
have done.

That's what I mean by Python being more dynamic than
Lisp.

> Despite its dynamism, Lisp is quite compilable.

Please correct me if I'm wrong, but as I understand,
getting efficient code out of a Lisp compiler requires
putting type declarations into the source.

If you put the same declarations into a piece of
Python code, then of course it would be fairly
straightforward to compile it efficiently. But it
wouldn't really be dynamic Python any more.

Python may end up going this way -- there are
currently plans to make room for attaching optional
annotations to function arguments, which could be
used to convey type information to a compiler
(although that's not currently the main intended
use).

The alternative is whole-program analysis and huge
amounts of type inferencing, which the PyPy people
are working on. Maybe something practical will come
out of that.

Whichever, it's nowhere near a simple as just
"adding macros"!

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread greg
[EMAIL PROTECTED] wrote:

> Does the word "TRONDANT" hold some special meaning for you?

Er, no, in fact my brain raises a KeyError on it.
Is it supposed to mean anything?

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread greg
Juan R. wrote:

> I see no dinamism on your example, just static overloading.

There's nothing static about it:

   q = raw_input()
   if q == "A":
 a = 1
 b = 2
   else:
 a = "x"
 b = "y"
   c = a + b

There is no way that the compiler can statically
determine what the + operator needs to do here.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread greg
Espen Vestre wrote:

> Paul Rubin <http://[EMAIL PROTECTED]> writes:

> > there is a huge amount of
> > state scattered all through a running Python program, that the
> > application can modify at random
> 
> That's what I call /kludgy/, not /dynamic/ ;-)

I think "kludgy" is a bit unfair, since this is a
result of doing things in a very simple and uniform
way -- rather a Lispy concept, I would have thought. :-)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread greg
Paul Rubin wrote:

> I think the Lispies see "more dynamism" as a good thing and are
> therefore defending their language from suggestions that Python is
> even more dynamic than Lisp.  I mean "dynamic" in a less good way--

Indeed, Python has sometimes been described
as "pathologically dynamic". All that dynamism
is handy sometimes, but it does get in the
way of improving efficiency.

Often discussions take place on python-dev
about ways to selectively limit the dynamism
to make some optimisation possible.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread greg
Jon Harrop wrote:

> Outside Lisp, macros are for syntax. Evaluation semantics (e.g. lazy
> evaluation) then have nothing to do with macros.

I don't think that's entirely true. With currying
and lazy evaluation, there's a sense in which
Haskell function definitions already *are* macros.

There are limits to the degree of syntactical
transformation you can reasonably achieve -- it
wouldn't be easy to make Haskell code look exactly
like Cobol, for example. But usually that's not
what you're after -- rather you just want to
devise some way to express your intent with a
minimum of boilerplate.

I once implemented a parser in HUGS. Using nothing
but built-in language features, I was able to
construct a system whereby I could more or less
just write down the BNF grammar rules and feed them
straight into the HUGS compiler. Achieving a
similar trick in Lisp would probably have required
using macros.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread greg
Robert Uhl wrote:

> o Symbols
> 
> In Lisp, a symbol is essentially a hashed string;

Are you aware that strings can be interned in Python?
Furthermore, any string literal in the source that
is a syntactically valid identifier is automatically
interned, and you can intern any string explicitly
if you need. This gives you exactly the same
capabilities as symbols in Lisp.

For example, due to the automatic interning, the
string comparison in the following is just a pointer
comparison:

fred = 'hello'
if fred == 'hello':
   print 'Greetings'

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread greg
George Sakkis wrote:

> I'm sure there should be more convincing examples for macros, but
> neither this nor the 'unless' syntax sugar cuts it.

Also, the new 'with' statement and associated
protocol covers much of the ground that was left
out by the existing constructs.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-13 Thread greg
Timofei Shatrov wrote:

> Are you aware that you hardly know any Lisp yet make such bold and unfounded
> claims? Unless interning a string somehow gives it a property list, slot value
> and function value it doesn't give you the same capabilities.

I'm talking about the capability of comparing symbols
efficiently by address, which Robert seemed to think
that Python couldn't do. I was pointing out that it
can, despite not having a distinct symbol type.

I know about property lists. The Pythonic way to do
the equivalent thing is using a dictionary.

I also know about the dual function/other value of
a symbol, which has alway seemed like an idiotic
feature to me. All it seems to do is make it more
awkward than necessary to deal with functions as
first class objects, which is supposedly meant to
be one of Lisp's strengths. So I regard it as a
feature that Python *doesn't* have this. :-)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-13 Thread greg
Ken Tilton wrote:

> pps. How would Python do this?

Here's one way it could look:

   defskill("absolute-value",
 title = "Absolute Value",
 annotations = [
  "Take the absolute value of #op#.",
  "The vertical bars around #op# mean 'the absolute value of' #op#.",
  "Absolute value of #strn# is the 'distance' of #strn# from zero.",
  "Absolute value is always zero or positive: #str|n|=n#, and #str|-n|=n#."
 ],
 hints = [
  "What do those vertical bars around #op# mean?",
  "Have you learned about 'absolute value'?",
  """Absolute value can be thought of as the 'distance' of a value from
 zero on the number line, and distance is always positive.""",
  "The rule is:#str|-n|=|n|##str=n#.  Can you apply that to #op#?",
  "Some examples: #str|+42|=42#, #str|-42|=42#, and #str|0|=0#.",
  """To get the absolute value of a number such as #op#, we simply drop
 any minus sign."""
 ]
   )

 > Is it possible to avoid committing to an
 > implementation mechanism?

The defskill function could do just about anything with this.
Here's one possibility:

   skills = {}

   class Skill:
 pass # fill in whatever methods you need here

   def defskill(name, title, annotations, hints):
 skill = Skill()
 skill.title = title
 skill.annotations = annotations
 skill.hints = hints
 skills[name] = skill

This gives you a dictionary of Skill instances indexed by name,
each one having a title and lists of annotation and hint strings.
The rest of the system can process this however required.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditional iteration

2006-12-13 Thread greg
at wrote:

> It is not the addional line containing 'if x > 0:' that bothers me, but the
> additional indentation.

I don't find the additional indentation bothersome.
In fact I think it's helpful, because it makes it
obvious that there is something else going on besides
just a loop.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple inheritance and __slots__

2006-12-14 Thread greg
Simon Brunning wrote:

> Difficulty with subclassing is the price you pay for abusing slots.

Although you could have the same difficulty even
if you weren't abusing them.

It's just a limitation of the implementation.
The use of __slots__ forces a particular layout
im memory, and you can only do that for one
base class at a time.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-14 Thread greg
Ken Tilton wrote:

> How close can Python get when code is involved? The reverse function 
> signature is fixed, so can lambda help?

Lambda can be used if the body can be written as a
single expression. Otherwise you need to write the
function as a separate def. When the body is more
than a line or two, this is not usually much of
a problem, and is arguably more readable anyway.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditional iteration

2006-12-14 Thread greg
at wrote:

> I think by approving
> 
> a = b if condition else c

Again, this allows something to be written as an
expression that formerly could only be written as
a statement, which is a much bigger gain than just
crunching two statements into one.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditional iteration

2006-12-14 Thread greg
at wrote:

> With the current Python syntax, I can create for every two lines of code a
> dozen alternative implementations:

The "one way to do it" rule seems to be widely misquoted
and misunderstood.

Of course any Turing-complete programming language is
going to provide infinitely many ways of expressing
anything.

What the "one way" rule is saying is that there is no
point in the language going out of its way to provide
two syntaxes for something with no clear reason to
prefer one or the other in any given situation. Like,
for instance, Perl having both "if (condition) statement"
and "statement if (condition)".

That's exactly the sort of thing you're proposing here,
and that's why the "one way" rule-of-thumb suggests it's
not a good idea.

It's not a hard-and-fast rule; one could argue that
list comprehensions violate it, and many people did.
Ultimately Guido decided that LCs were a big enough
win in certain situations, probably because they bring
something from the realm of statements into the realm
of expressions. Your proposal doesn't do that -- it
just rewrites a pair of statements very slightly to
give another statement, and opinions differ on whether
it would improve or hurt readability.

Furthermore, Guido has considered this exact idea
before, promoted using the same arguments, and rejected
it, so it's unlikely he would change his mind this
time around.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: speed of python vs matlab.

2006-12-14 Thread greg
Chao wrote:

> I did some search, in previous discussion, people has compared
> python/numpy vs matlab,
> but it is actually comparison between numpy(which is implemented in c)
> vs matlab.

Yes, matlab is operating on whole arrays at a time,
like numpy. So it's not surprising that they have
comparable performance.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Famous Error Message: "ImportError: No module named python_script"

2006-12-14 Thread greg
rich murphy wrote:
> So, I assumed "the current directory" is C:\Python25 which did not
> work... What directory does it mean then?

It means the current directory of the process running
the Python interpreter, which, unless you've done
something to change it, will be the same as the
current directory of the command shell that you
ran the Python interpreter from. That, in turn,
will be whatever you set it to using the "cd" command.

However, it's important to understand that this only
applies when using the Python interpreter *interactively*,
which means just typing "python" and entering Python
statements at the >>> prompt.

If you tell the interpreter to run a .py file,
e.g.

python some\dir\myfile.py

then it does *not* look in the current directory of
the process for imported files -- instead, it looks in the
directory containing the "main" .py file, i.e. the one
you passed on the command line. This is more useful,
since it allows you to keep the main file and the
modules it uses together, and not have to worry about
cd'ing to the directory in order to run it.

Also, if you're using an IDE such as IDLE or PythonWin
instead of running the interpreter from a command shell,
relying on the "current directory" isn't very useful,
since it's hard to predict what it will be. Again,
just put the files to be imported alongside your main
.py file and you should be all right.

There are various ways of specifying additional places
to look for imported modules, but that should be enough
to get you going.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Famous Error Message: "ImportError: No module named python_script"

2006-12-14 Thread greg
Gabriel Genellina wrote:

> I bet your file is actually called fibo.py.txt then.
> (Perhaps some advise should be provided for Windows users, about 
> enclosing the name inside "double quotes", or selecting "All files 
> (*.*)" on the file type list)

Also, if by some chance you've got "Hide filename
extensions" turned on in your View options, TURN
IT OFF. It'll cause no end of confusion when you're
trying to program.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
Gabriel Genellina wrote:
> You can even make S = cT (c=ligth of speed in void space).
> The choice of fundamental units is rather arbitrary, and can be reduced 
> further to only 1 fundamental unit and even NO fundamental units.

I once heard mention of a system of units in use at
one time with the odd feature that capacitance came
out in units of length.

Picture the scene: Hobbyist walks into Dick Smith
store and says "I'd like a 5cm capacitor, please."

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
Ken Tilton wrote:

> So this:
> (defmethod tf-reverse (id (eql ',sub-id)) resx (drv-opnds tf drv))
> ,@reverser)
> 
> becomes this:
> 
> (defmethod tf-reverse ((id (eql ',sub-id)) tf drv
> &aux (opnds (drv-opnds tf drv)))
>(loop for resx in (results drv)
>  ,@reverser))

I don't see why you can't just write a function that
loops over the results and calls the user's reversal
function for each one.

   def reverse_multiple(skill, resx_list, opnds):
 for resx in rex_list:
   skill.reverse(resx, opnds)

There's no need to macro-expand this code into every
reversal function, when it can be done once as part of
the framework that calls the reversal functions.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
Ken Tilton wrote:

> The reason I post macro expansions along with examples of the macro 
> being applied is so that one can see what code would have to be written 
> if I did not have the defskill macro to "write" them for me.

It seems to me your brain is somewhat stuck on the use
of macros. You're looking at the expansion of your
macro and assuming that you'd have to write all that
code by hand if you didn't have macros. You're not
thinking about alternative approaches, which could
just as well be used in Lisp as well as Python, that
are just as compact yet don't make use of macros.

Unless there's something very subtle that I'm missing
(I can't claim to follow exactly what all the code
you posted does in detail) I haven't seen anything
that couldn't be done quite reasonably with an
appropriate data structure and ordinary functions
and methods operating on that data structure.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
[EMAIL PROTECTED] wrote:
> Neil Cerutti wrote:
> 
>>On 2006-12-13, [EMAIL PROTECTED]
>><[EMAIL PROTECTED]> wrote:
>>
>>>Expressions keep the same meaning even if you have to start
>>>breaking them across lines, etc.
>>
>>Yes, it's the same way in Python. Of course, not everything is an
>>expression in Python, so it's not saying quite as much.
> 
> I fail to see how it is the same in Python.

Probably what Neil is referring to is the fact that in
Python, *within an expression*, indentation is not relevant.
If you put parens around the whole expression, you can split
it across lines however you like, and indent all the lines
after the first one however you like, and it makes no
difference. You could probably even use your Lisp-aware
auto-indenter on the expression and it would do something
reasonable.

It's only *statement* nesting that's determined by relative
horizontal position (which is a better way of thinking about
it than "whitespace" -- the whitespace is only there to
get things into the right position). And statements normally
occupy one or more entire lines.

> How does a manual correction process come out as simple as "don't
> bother fixing the indentation if you don't care."?

I think the point is that correcting indentation in Python
is the equivalent of fixing misplaced parentheses in Lisp,
and that they're about equally difficult.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
[EMAIL PROTECTED] wrote:
> I wrote my first Python in a non-Python-aware editor, and somehow had
> swapped tabs and spaces; when I moved it to IDLE---the indentation
> *looked fine* but was invisibly weird.

That can admittedly be a problem. It would help if the
parser complained by default about mixed use of tabs and
spaces in a single file, instead of silently assuming tab
stops every 8 spaces (an historical misfeature that we still
have for the time being). Probably this will change in
Python 3.0.

Personally I find Python pleasant enough to work with
that I'm willing to put up with the odd screwup like that
happening now and then. And they really don't happen all
that often -- once you've experienced it a few times,
you learn how to guard against it and get better at
fixing it when it does happen.

 > I will even admit that white-space significance does not
> materially increase errors among experienced Pythonistas. What it isn't
> is some kind of miraculous invention that saves programmers from ever
> making mistakes that are common in other languages,

We don't claim that -- only that it's not the unmitigated
disaster than some people assume it will be without ever
having tried it.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
[EMAIL PROTECTED] wrote:
> Neil Cerutti wrote:
> 
> > The parenthesis I added means I don't have
> > to use the new-line escape character (\), either.
> 
> Is this so unconscious that you don't recognize you are doing it, even
> though you take a sentence to explain what you had to do to work around
> it? 

Yes, it is pretty unconscious. We all do many things
unconsciously in everyday life that would take at
least one sentence to explain to someone else if we
had to think about it.

Besides, in many cases the required brackets are
already there -- e.g. if it's a list, or a function
call with many arguments -- in which case you don't
have to add anything at all.

> Adding parentheses ... all this is a
> burden specific to Python.

As opposed to Lisp, where all you have to do is
use parentheses... oh, er...

> By the way, you guys seem fixate on the parentheses of Lisp without
> having the experience

I don't know about the other Pythonistas in this
discussion, but personally I do have experience with
Lisp, and I understand what you're saying. I have
nothing against Lisp parentheses, I just don't agree
that the Lisp way is superior to the Python way in
all respects, based on my experience with both.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
Ken Tilton wrote:

> What if it turns into an SQL lookup during refactoring?

If the macro can produce SQL code, then whatever interprets the
table can produce SQL code as well.

If you're thinking of the macro taking apart the user's reverse
function (rather than just wrapping it) and somehow translating
it into SQL, well... a macro *could* do that, but it would be
an awfully hairy thing to do, especially if the user is allowed
to write arbitrary Lisp code in the body of his function (as
it seems he is, in your example).

A better way would be to design an abstract API for the user
to use in his reverse functions. Then you can just re-implement
the functions making up the API so that they do SQL queries
instead of whatever they were doing before. No macro processing
needed then.

> The last example showed the macro inserting code to magically produce a 
> binding inside the reverse function.

Are you sure? It looked to me like it was adding code *around*
the reverse function, not inside it. I posted a Python function
that achieves the same thing by calling the existing reverse
function.

> It would be easier to compare and 
> contrast with the Python equivalent if someone had posted such, but your 
> troops have fallen back to Fort So What? and pulled up the drawbridge.

I'm still trying, but some of the code you posted is rather
impenetrable without knowing a lot more about the details of
your system. I'm doing my best to show some Python demonstrating
the gist of what could be done.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CLPython (was Re: merits of Lisp vs Python)

2006-12-15 Thread greg
Willem Broekema wrote:

> I guess in part it's because there are not that many people really into
> both Python and Lisp, and those who are might not find this an
> interesting project because there is nothing "wow" to show, yet.

Another reason (or maybe the reason for the reason) is
that people are usually interested in Python because it's
a relatively simple and lightweight thing.

Having to install a complex and heavyweight thing like
a Common Lisp system just to be able to program in
Python doesn't seem like a good deal.

It might become a good deal if you could then compile
the Lisp and get a lean, efficient binary executable
out of it. But that's going to require much more than
just a straightforward translation from Python to Lisp.

If CLPython starts to show signs of making progress
in that direction, then it could start to get
interesting. Although I think I'd rather target Scheme
than CL if I were doing it -- cleaner language, small
yet still extremely good implementations available.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
Ken Tilton wrote:

> McCarthy: "Is code also data in Python?"
> Norvig: "No."

I don't think that was the right answer. He should have
said "Yes", and then shown McCarthy eval() and exec.

Code isn't quite as *convenient* to work with as data
in Python as it is in Lisp, but that doesn't mean it
can't be done.

(I agree that the proffered example was not an instance
of "code is data", though.)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
Ken Tilton wrote:

> I think your brain is stuck on flaming.

Sorry, I didn't mean to come across as flaming, far
from it. I'll take a deep breath before posting from
now on, I promise. :-)

> I did explain the last little fun bit (where reverse code miraculously 
> got a case-specific "signed-value" parameter bound to exactly the right 
> bit of math structure).

I didn't mention that because it was addressed by
another poster. The signature of the user's reverse
function can be made extremely flexible if you have
the foresight to define it as something like

def reverse(resx, opnd, **kwds):
  ...

Then you can later change it to

   def reverse(resx, opnd, signed_value, **kwds):
  ...

and any existing reverse functions will just absorb
and ignore the extra argument.

However, rather than add an ever-increasing number
of arguments to the signature, I think I would do it
a different way: pass a single object with attributes.
For the want of a better name, let's call it "env"
for "environment". The signature is then

   def reverse(env):
  ...

and the body can refer to env.resx, env.opnd,
env.signed_value, or whatever else is required.

If this still doesn't cover the requirements, please
explain and I'll try to adapt it accordingly.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
André Thieme wrote:
>  (aif (timeConsumingCalculation)
>  (use it))

I think the answer is that you just wouldn't do
that in Python at all. Having magic variables
spring into existence in your local namespace
as a side effect of calling something is just
not Pythonic. (It is very Perlish, on the other
hand.)

The closest you might come is using the new
"with" statement like this:

   with aif(timeConsumingCalculation()) as it:
 use(it)

where the object returned by aif(x) has an
__enter__ method that raises an exception which
aborts the whole with statement if x is None,
thus avoiding executing the body. But that's
so horribly convoluted that any sane programmer
would just write it out the straightforward
way to begin with.

>  > There's a Haskell builtin called 'seq' which forces evaluation but
>  > again I'm not sure precisely how to apply it here.
> 
> So in some languages that support functional programming one needs to do
> extra work to get lazyness, while in Haskell one gets extra work if one
> doesn't want it.

Sort of, but it's more so that you can write code
that does things like I/O in what looks like a
procedural style, even though it's still purely
functional. Read about "monads" if you want to
know more -- it's truly mind-expanding (and
possibly head-exploding:-) stuff...

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
André Thieme wrote:

> The thing with most (if not all) programming languages other than Lisp
> is: these abstractions are leaky.
> They have a low level knowledge leak. Users of aif need to know how to
> pass in arguments. As you see he had do embed the code that needs execution
> into a block (anon function) and then use this special syntax for x.

Yes, but all the standard looping constructs, etc.
in Ruby are expressed like this too. So it's
perfectly consistent with the rest of the language.
It's not something new that the user needs to learn
just to use this function.

This is even more evident in Smalltalk, where
*all* control structures, without exception, are
expressed in terms of code blocks, possibly
with parameters. And Smalltalk has no macros,
either, btw.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
André Thieme wrote:

> So instead of
> cmp(foo(a, b, c), bar(x, y, z)) you would prefer
> foo(a, b, c) cmp bar(x, y, z) ?

Incidentally, someone once came up with an fiendishly
clever hack that lets you write things in Python like

   foo(a, b, c) |kmp| bar(x, y, z)

i.e. effectively define your own infix operators. And
it doesn't even require a macro. :-)

(Finding the trick to implementing this is left as an
exercise for the googler.)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
[EMAIL PROTECTED] wrote:
> Then bring in more statement and you either have to
> remember precedence rules (I can never remember those) or add some
> parenthesis (oops!).

Probably you've been burned by C, which has a
ridiculously large number of precedence levels --
I don't know *anyone* who can remember them all.
Most people just remember a subset and use
parens for everything else.

Pascal had four levels, which was easy to remember
but not really enough. About six or seven seems
optimal to me.

Python, incidentally, has rather too many (it
seems to have caught this disease from C).

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread greg
André Thieme wrote:

> The <=> is called cmp in Python.
> In Lisp it is called signum. The Lisp function has in general the
> advantage that it keeps type information.
> While Pythons cmp returns either -1, 0 or 1 the Lisp version can
> also return -1.0 and 1.0 and also complex numbers:
> (signum #C(10 4))  =>  #C(0.9284767 0.37139067)

Unless you can use it to compare arbitrary types
such as two strings or two lists, it's not really
the same thing as Python's cmp.

Python 2.3 (#1, Aug  5 2003, 15:52:30)
[GCC 3.1 20020420 (prerelease)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> cmp("hello", "world")
-1
 >>> cmp([1,3], [1,2])
1

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-16 Thread greg
Ken Tilton wrote:

> How does a generic engine that sees only a solution (a 
> list of mathematical expressions and for each the transformations, 
> results, and opnds logged by individual TF functions) build up this 
> environment such that it has named attributes such as signed-value?

How did your macro know that the user's reverse function
needed a signed_value parameter in that particular case?

> Assume that it can examine all those opnds and results looking
> for tagged values such that it then knows the name of those values
> that have been named.

You might be able to handle this using a general method
that searches the tree for a specified tag, e.g.

env.find_tag("signed_value")

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-16 Thread greg
Nick Maclaren wrote:

> A collection is inhomogeneous if, for some attribute that is needed
> for at least one action on at least one element of the collection,
> the attribute is not shared by all elements of the collection.

If you mean "attribute" in the Python sense, then this
is wrong, because you're just defining it in terms of
concrete types again.

There is no rigorous definition in Python terms, because
Python doesn't formally embody the concept. But that
doesn't mean the concept isn't real.

There are other languages that do embody it, for example,
C. A Python tuple is like a C struct, and a Python list
is like a C array.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-17 Thread greg
Roy Smith wrote:

> The struct does lookup by name, the tuple is inherently index based.

I was trying to help people understand the distinction
we're talking about by showing an example of the same
distinction in another language where it's much clearer.

There are a great many ways in which C structs are
different from Python tuples, and C arrays are different
from Python lists. But they're not the aspects I'm
drawing an analogy between.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-18 Thread greg
Nick Maclaren wrote:

> Unfortunately, you are confusing the issue, because there are far
> more extraneous aspects than relevant ones, and your view of the
> similarities requires looking at the issue in a very strange way.
> I think that I can see what you mean, but only just.

Each member of a struct has a distinct, predefined
role. Even if they all have the same type, you
can't swap their values around without destroying
the meaning of the data. That's what's meant by
"heterogeneous" in this context -- it's not about
the values themselves, but the way they're used.

This is the kind of thing for which Python tuples
are mainly designed -- use as a struct whose
members happen to be named by integers rather
than strings.

If you still don't understand, then I'm afraid
I've run out of ideas on how to explain it.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-18 Thread greg
Bill Atkins wrote:
> This is not a response to any particular post, but rather to the
> general argument that macros are not as useful as we Lispers claim.
> 
> Here is a fairly complete GUI RSS reader in 90 lines of Lisp

For comparison, here's how something with a similar
API might be used from Python.

class RSSInterface(Interface):

   def __init__(self):
 Interface.__init__(self,
   panes = [
 TextInput('url_pane',
   title = 'Feed URL:',
   callback = 'add_feed',
   callback_type = 'interface'),
 PushButton('add',
   text = 'Add Feed',
   callback = 'add_feed',
   callback_type = 'interface'),
 PushButton('refresh',
   text = 'Refresh All',
   callback = 'refresh_feeds',
   callback_type = 'interface'),
 PushButton('delete',
   text = 'Delete Feed',
   callback = 'delete_feed',
   callback_type = 'interface'),
 TreeView('tree',
   visible_min_width = ('character', 84),
   visible_min_height = ('character', 40),
   action_callback = 'browse_item',
   callback_type = 'item_interface',
   expandp_function = lambda: True, # not sure how best to translate
   children_function = 'tree_item_children',
   print_function = 'tree_item_string')
 ],
   layouts = [
 ColumnLayout('main', ('top', 'tree')),
 RowLayout('top', ('url_pane', 'add', 'refresh', 'delete'))
 ],
   title = 'Barebones RSS Reader v1.0')
 self.channels = [
   parse_rss_from_url(url) for url in [
 'http://planet.lisp.org/rss20.xml',
 'http://feeds.theonion.com/theonion/daily']]

   def add_feed(self):
 ...

   def delete_feed(self):
 ...

   # etc.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python-hosting.com projects: dead?

2006-12-19 Thread greg
[EMAIL PROTECTED] wrote:

> I certainly hope so, but this is what I'm reacting to (from
> http://www.webfaction.com/freetrac):
> 
> "We're sorry, we're not longer accepting applications for free trac/svn
> accounts. People have left their Trac sites unattended and as a result
> our server is being flooded with spam. We need to do some serious
> cleanup and when that's done we'll accept new applications again (that
> might take weeks, if not months though). "

Um, that sounds to me like they're not accepting *new*
projects, not that they're shutting down existing ones.
Unless *my* reading comprehension skills have completely
abandoned me.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python-hosting.com projects: dead?

2006-12-20 Thread greg
Remi wrote:

> We had to do some serious cleanup and we disabled a lot of Trac sites
> that looked abandoned (people left their Trac sites open to spammers
> and our server was crawling under the load caused by these spammers).

Perhaps it would be a good idea to send email to the owners
of these accounts letting them know what you've done and how
to get it re-enabled. Just shutting it down without any word
could be seen as a bit rude.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python-hosting.com projects: dead?

2006-12-20 Thread greg
Richard Jones wrote:

> Actually, to clarify the DEFAULT configuration for Trac is to leave it open
> to spam.

That sounds like a really bad choice of default.

A bit like the way Windows comes with all the
"let anyone in the world send me a virus"
options turned on...

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-20 Thread greg
Nick Maclaren wrote:

> It does explain why you think of lists as homogeneous, but the
> analogy doesn't hold water on closer inspection.  There doesn't seem
> to be ANYTHING in the specification or implementation that assumes
> lists are homogeneous.

Then what do you think is suggested by the fact
that lists have an index() method but tuples don't?

That's how this whole discussion got started --
someone wanted an explanation of why that is so.
The explanation is that tuples and lists were
designed for different use cases.

You don't *have* to use them that way, but if
you use them differently, you're on your own
and can't complain if they don't have all the
features you want.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-20 Thread greg
Nick Maclaren wrote:

> Nope.  Sorry.  Consider the old model where an I/O list is an ordered
> sequence of strings and agents (effectively procedure calls), with no
> constraints on how those are ordered.  With your specification, that
> is neither heterogenous nor homogenous :-)

I don't see any difficulty. This is a list (homogeneous) of
two-element tuples (heterogeneous).

If you're thinking of representing this as just a flat
list, [str1, agent1, str2, agent2, ...], that's a borked
way of doing it and you deserve whatever philosophical
knots you get into as a result.

> It's a complete delusion, because even the claimed assumption of list
> homogeneity is tantmount to saying that Python doesn't encourage (or,
> arguably, support) ANY way of using mutable heterogenous sequences
> (such as the example above).

It's unfortunate that Python doesn't make the homogeneous/
heterogeneous distinction orthogonal to the mutable/immutable
one. Ideally, yes, there would be mutable and immutable
tuples, and mutable and immutable lists. Perhaps also even
fixed and variable sized versions of these as well.

But that would be eight different data types, which is a
lot of trouble to go to just to give you something that's
precisely tailored to exactly what you want. Some might
say it was overkill.

Python takes a more pragmatic approach, and provides
just two: the tuple, optimised for the case of heterogeneous
*and* fixed size *and* immutable -- and the list, for
everything else.

So it's not really that lists are intended *only* for
homogeneous collections, but for anything that can't be
represented as a tuple for whichever reason.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-20 Thread greg
Nick Maclaren wrote:

> Not at all.  I didn't say that they came in pairs.  Consider:
> 
> [str1, str2, agent1, str3, agent2, agent3, agent4, str4, ...]

That's homogeneous. Any item of the list can be
either a string or an agent, and the only thing
the position in the list affects is what order
the strings and agents are processed in.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: PyGUI 1.6

2006-02-12 Thread greg
PyGUI 1.6 is now available:

   http://www.cosc.canterbury.ac.nz/~greg/python_gui/

The major change in this version is that the Mac version
is based on Cocoa instead of Carbon. This should provide a
much better base for future development, but it does mean
that MacOSX will now be required. (This isn't as big a
change as it seems, since the Carbon version actually
required MacOSX too, despite being Carbon.)

There have been numerous other changes and improvements
as well. See the CHANGES file in the distribution or on
the web site for full details.


What is PyGUI?
--

PyGUI is an experimental highly-Pythonic cross-platform
GUI API. Implementations are currently available for
MacOSX and Gtk. For a full description of the project
goals, see the PyGUI web page at the above address.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyGUI 1.6: A Note for MacOSX Users

2006-02-28 Thread greg
A small problem has come to light with PyGUI 1.6
on MacOSX systems.

If you get the following exception:

File "GUI/Generic/BaseAlertFunctions.py", line 5, in ?
ImportError: No module named Alerts

it's probably because you don't have PyObjC installed.

I will fix this to produce a more informative error
message in the next release.

==

What is PyGUI?
--

PyGUI is an experimental highly-Pythonic cross-platform
GUI API. Implementations are currently available for
MacOSX and Gtk. For a full description of the project
goals, see the PyGUI web page at the above address.

The current version is available from:

   http://www.cosc.canterbury.ac.nz/~greg/python_gui/

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Steven D'Aprano wrote:

>  You can't shell an egg that isn't there.

Yesterday upon the stair
I shelled an egg that wasn't there.
I'd shell the thing again today
If only I could find a way.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Ben Finney wrote:
> On the assumption these might be basic types, though, that
> name doesn't read so easily in lowercase ('enummember').

Maybe 'enumval'?

I also thought of 'enumber' (from munging together
'enum' and 'member') but that looks too much like
'e-number' rather than 'enum-ber'.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Paul Rubin wrote:

> Do you anticipate having parameters like socket.AF_INET that are
> currently integers, become enumeration members in future releases?

Since these are derived from values defined
as integers in C, it's probably better to leave
them that way. There may be code that relies
on them being integers or having those integer
values.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Giovanni Bajo wrote:

> What's the repr of an enumeration value? OTOH, it should be something like
> "Weekdays.wed", so that eval(repr()) holds true. Also, it'd be very useful in
> debug dumps, tracebacks and whatnot.

That would be nice, but I don't think that's possible
with what the PEP proposes, because in

   Weekdays = enum('mon', 'tue', etc...)

there's no way for the enum object to know that it's
meant to be called 'Weekdays'.

A constructor argument could be added for this, but
then you end up having to write the name twice,
making the construct far less elegant.

Maybe *this* is a good argument for making the enum
object a class?

Or maybe it's an argument for allowing decorators
to operate on things other than functions, so you
could write something like

@enum
Weekdays = ('mon', 'tue', etc...)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-03-01 Thread greg
Dan Sommers wrote:

> In some parts of the world, calendar weeks begin on Monday
> and end on Sunday, and in other parts of the world, work weeks begin on
> Sunday and end on Thursday.

Things like days of the week really have a circular
ordering, so it doesn't inherently make sense to
ask whether one day of the week is less than or
greater than another.

Maybe there should be a circular_enum type, where
order comparisons even among the *same* type are
disallowed?

Another thought -- should enum values have pred()
and succ() methods, like in Pascal? If so, for
a circular_enum these should wrap around.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying behaviour of the != operator

2005-06-10 Thread greg
David M. Cooke wrote:

>>To solve that, I would suggest a fourth category of "arbitrary
>>ordering", but that's probably Py3k material.
> 
> We've got that: use hash().
> [1+2j, 3+4j].sort(key=hash)

What about objects that are not hashable?

The purpose of arbitrary ordering would be to provide
an ordering for all objects, whatever they might be.

Greg

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-03 Thread greg
Paul Rubin wrote:
> E.g. your program might pass its test and run properly for years
> before some weird piece of input data causes some regexp to not quite
> work.

Then you get a bug report, you fix it, and you add a test
for it so that particular bug can't happen again.

> Once I got the
> function to work, I deployed it without writing permanent tests for
> it.

That suggests you had a temporary test at some point.
So, keep it and make it a permanent test. Even if it's
just a small manually-created directory, it's still
better than nothing, and you can add to it over time
to cover any bugs that turn up.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-04 Thread greg
Roy Smith wrote:
> greg <[EMAIL PROTECTED]> wrote:

> > Then you get a bug report, you fix it, and you add a test
> > for it so that particular bug can't happen again.

> The TDD zealots would tell you you've got the order wrong.  Instead of 
> "fix, then write a test", it should be "write a failing test, then fix it".

Yes, I'm aware of that. I said "and", not "then". :-)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building a Python app with Mozilla

2007-07-04 Thread greg
[EMAIL PROTECTED] wrote:

> wxWidgets will give you native looking apps on both Linux and Windows

Well, maybe. There's more to getting a native feel than
just using the right widgets. I once saw a Qt-based app on
MacOSX that had tiny little buttons that were too small
for the text they contained -- Aqua buttons just don't
scale down like that. :-(

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Portable general timestamp format, not 2038-limited

2007-07-04 Thread greg
James Harris wrote:
> With that the time would range to +/- 9000
> quintillion years (18 digits)

Use the Big Bang as the epoch, and you won't have
to worry about negative timestamps.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object references/memory access

2007-07-04 Thread greg
John Nagle wrote:
> C gets to
> run briefly, drains out the pipe, and blocks.  P gets to run,
> fills the pipe, and blocks.  The compute-bound thread gets to run,
> runs for a full time quantum, and loses the CPU to C.  Wash,
> rinse, repeat.

I thought that unix schedulers were usually a bit more
intelligent than that, and would dynamically lower the
priority of processes using CPU heavily.

If it worked purely as you describe, then a CPU-bound
process would make any interactive application running
at the same time very unresponsive. That doesn't seem
to happen on any of today's desktop unix systems.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MethodType/FunctionType and decorators

2007-07-04 Thread greg
Alex Popescu wrote:
> - for decorators, my test is executed before the class is defined and
> so at that moment the function is still a function; it will become a
> methodinstance only after the class definition is closed

Closer, but still not quite right. Even after the class
is defined, the function sitting inside it is still
just an ordinary function. You can see this by looking
at

A.__dict__['method']

An instancemethod is only created when you look the
method up in an instance, i.e.

a = A()
a.method

The instancemethod encapsulates a value for 'self' and
a reference to the underlying function. This is known
as a "bound method".

(You also get an instancemethod if you look the method
up in the class, i.e.

A.method

but in that case the instancemethod doesn't contain
a value for 'self', and is known as an "unbound
method".)

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building a Python app with Mozilla

2007-07-10 Thread greg
[EMAIL PROTECTED] wrote:
> Last I looked (3.1-ish), Qt didn't use the Aqua widgets but rather
> tried to write their own widgets that looked (kinda) like the MacOS
> widgets.

That might be so, but even if it had used real Aqua widgets,
the same problem would have occurred.

My point was that using native widgets is not in itself
enough to ensure a native experience. There are conventions
about *how* the widgets are used, and other things about
the behaviour that don't relate to widgets at all.

Native widgets are certainly a better thing to start
from, though.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Portable general timestamp format, not 2038-limited

2007-07-10 Thread greg
Ilya Zakharevich wrote:
> In pedantic mode: negative timestamps make sense with Big Bang as the
> epoch as well.  (AFAIU, the current way of thinking is that it was
> "just too hot" before the big bang, it is not that "there was
> nothing".)

If Stephen Hawking is right, the shape of the universe
is such that there isn't any time "before" the big bang
at all. It's like asking what's north of the North Pole.

Of course, this may have been replaced with some other
equally bizarre idea by now...

Another thought: If the cosmologists ever decide if
and when the Big Crunch is going to happen, we may be
able to figure out once and for all how many bits we
need in the timestamp.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object references/memory access

2007-07-10 Thread greg
Dennis Lee Bieber wrote:

>   If a process is known to be CPU bound, I think it is typical
> practice to "nice" the process... Lowering its priority by direct
> action.

Yes, but one usually only bothers with this for long-running
tasks. It's a nicety, not an absolute requirement.

It seems like this would have been an even more important
issue in the timesharing environments where unix originated.
You wouldn't want everyone's text editors suddenly starting
to take half a second to respond to keystrokes just because
someone launched "cc -O4 foo.c" without nicing it.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The best platform and editor for Python

2007-07-10 Thread greg
Nicola Musatti wrote:
> It's in *commercial* projects that
> features nobody really needs are not implemented. Profit is
> fundamental in convincing you that you really need the features.

In Soviet Russia, you don't need features, features need *you*.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.wait() losing child?

2007-07-10 Thread greg
Jason Zheng wrote:
> while (True):
>   pid = os.wait()
>   ...
>   if (someCondition):
> break
 >   ...

Are you sure that someCondition() always becomes true
when the list of pids is empty? If not, you may end
up making more wait() calls than there are children.

It might be safer to do

   while pids:
 ...

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.wait() losing child?

2007-07-11 Thread greg
Jason Zheng wrote:
> Hate to reply to my own thread, but this is the working program that can 
> demonstrate what I posted earlier:

I've figured out what's going on. The Popen class has a
__del__ method which does a non-blocking wait of its own.
So you need to keep the Popen instance for each subprocess
alive until your wait call has cleaned it up.

The following version seems to work okay.

import os
from subprocess import Popen

pids = {}
counts = [0,0,0]
p = [None, None, None]

for i in xrange(3):
   p[i] = Popen('sleep 1', shell=True)
   pids[p[i].pid] = i
   print "Starting child process %d (%d)" % (i,p[i].pid)

while (True):
   (pid,exitstat) = os.wait()
   i = pids[pid]
   del pids[pid]
   counts[i]=counts[i]+1

   #terminate if count>10
   if (counts[i]==10):
 print "Child Process %d terminated." % i
 if reduce(lambda x,y: x and (y>=10), counts):
   break
 continue

   print "Child Process %d (%d) terminated, restarting" % (i, pid),
   p[i] = Popen('sleep 1', shell=True)
   pids[p[i].pid] = i
   print "(%d)" % p[i].pid

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I change one line in a file without rewriting the whole thing?

2007-07-14 Thread greg
J. J. Ramsey wrote:
> if I can avoid doing what amounts to reading the
> whole file into memory, changing the copy in memory, and writing it
> all out again.

Except in very special circumstances, not really.
If you do anything that makes a line longer or
shorter, everything after that line in the file
needs to be re-written, one way or another.

If you're doing this sort of thing a lot, and
need it to be faster than reading and rewriting the
file, you may need to look into using a more
sophisticated format on disk than a plain file.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Circular import problem

2007-07-14 Thread greg
bvdp wrote:
> before I moved other
> imports around I was able to do the following:
> 
>  1. NOT include MMA.gooves,
>  2. call the function MMA.grooves.somefunc()
> 
> and have it work.

The import doesn't necessarily have to be in the same module
where the attribute is used. The first time *any* module
does 'import MMA.grooves', a grooves attribute gets put
into MMA, which can be used by any module that has a
reference to MMA.

It's probably not a good idea to rely on this, though,
and better to put an explicit 'import MMA.grooves' into
every module that uses it. Importing something more than
once does no harm.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Snobol 1.0

2007-07-22 Thread greg
Aahz wrote:
> So adding
> SNOBOL patterns to another library would be a wonderful gift to the
> Python community...

I wrote a module for Snobol-style pattern matching a
while back, but didn't get around to releasing it.
I've just put it on my web page:

http://www.cosc.canterbury.ac.nz/greg.ewing/python/Snobol.tar.gz

There's no manual yet, but there's a fairly complete
set of docstrings and some test cases to figure it
out from.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floats as keys in dict

2007-08-01 Thread greg
Brian Elmegaard wrote:
> However, the dict keys are then floats and I have to round the values
> of new possible nodes in each step.

Be careful with this. If you have two values that are
very close together, but on different sides of a rounding
boundary, they will end up as distinct keys even though
they "should" be regarded as equal.

I don't think there's any way to use a dictionary for
this that works properly in all cases. Whatever scheme
you come up with for comparison and hashing will suffer
from this problem one way or another.

So, like Alex said, you need a different data structure.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Redirecting stderr to null and revert

2007-08-07 Thread greg
reubendb wrote:
> def nullStderr():
>   sys.stderr.flush()
>   err = open('/dev/null', 'a+', 0)
>   os.dup2(err.fileno(), sys.stderr.fileno())
> 
> def revertStderr():
>   sys.stderr = sys.__stderr__

You're doing the redirection at one level and
trying to revert it at a different level.

If this is a Python function that's doing its
output by writing to sys.stderr, there's a
much simpler way to do the redirection:

   sys.stderr = open('/dev/null', 'w')

(that's the Python builtin function 'open',
not the one in os). Then your revertStderr
function will work.

BTW I'd arrange for the reversion to be done
in a try-finally, e.g.

   nullStderr()
   try:
 do_something()
   finally:
 revertStderr()

so you won't get stuck with a redirected stderr
if an exception occurs, and thereby not be able
to see the traceback!

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing * From a Package

2007-08-07 Thread greg
Patrick Doyle wrote:
> This is the part that has me confused -- why does "from package import
> *" go on to import names that were explicitly loaded by previous
> import statements?

Because there's no easy way for it *not* to do that.
All it does is grab whatever names are defined in the
module at the time. It can't tell whether those names
got there as a result of an import statement or some
other way.

A more pertinent question is why it *doesn't* import
submodules that haven't already been explicitly imported.
Probably this is just because it could be quite expensive
to do so -- you would potentially be triggering a lot
of disk activity to load the previously unused modules
into memory, many of which you may not be going to use.

Just in case it's not clear, "importing" can actually
mean two different things. If the module hasn't been
imported before, it has to be loaded into memory, which
is expensive. If it has been imported before, then
you're just creating another reference to the same
module object, which is very cheap. An import *
just does the cheap part, and leaves you to explicitly
ask for the expensive part if you really want it.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Something in the function tutorial confused me.

2007-08-07 Thread greg
Steve Holden wrote:
> OK. The difference is that [] is a mutable value, while None is 
> immutable.

No, it's not. It has nothing to do with mutability
vs immutability.

The difference is that in the first version the
expression [] is evaluated only *once*, when the
function is defined. Therefore there is just one
list object getting re-used.

In the second version, the expression [] gets
evaluated *each* time the function is called,
creating a new list object each time.

> When the function starts out with None as y's value any assignment to y 
> causes it to reference a different value  (since None is immutable).

You're confused. Assigning to y simply causes it
to reference whatever object is being assigned.
This is always true, regardless of what y was
referencing before.

To see that the immutability of None has nothing
to do with it, try the following version:

def f(x, y = []):
   y = []
   y.append(x)
   print y

f(17)
f(42)

Try to work out what it will do, then try it, and
see if you understand why it does what it does.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Issues of state

2007-08-08 Thread greg
Paul Rubin wrote:
> I'm not sure what you're getting at in this context.  You can write a
> desktop app where the window system communicates with a gui toolkit
> through a socket (at least that's how X windows works)

An X server connection is *much* more stateful than
an HTTP one. It persists throughout the entire use
session of the application, for one thing, and there
is heaps of state being kept on both sides of the
connection. There's also a very high communication
bandwidth between them. There's really no comparison.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Issues of state

2007-08-08 Thread greg
Paul Rubin wrote:
> The high bandwidth and persistence is not needed for an http
> connection, which just gets a form submission once in a while.

Bandwidth isn't really the main issue. The point is
that a lot of state is kept on both ends, making it
much easier to implement a rich user interface.

In fact, the more state is kept, the *less* bandwidth
you need, because communication can make use of shared
context to compress the messages.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Something in the function tutorial confused me.

2007-08-08 Thread greg
Steve Holden wrote:

> For some reason your reply got right up my nose,

I'm sorry about that. Sometimes it's hard to judge the
level of experience with Python that a poster has. In
discussions about this particular topic, often it turns
out that the person is a newcomer to Python who is
using the wrong mental model of assignment, and your
comment about None being immutable suggested that this
is what was going on. If I was mistaken about that,
then I apologise.

While it may not have been what you meant, what you
*seemed* to be saying is that the result of a (plain)
assignment somehow depends on what was previously
bound to the name being assigned. I was just trying
to point out that this is not true.

The reason I suggested trying an example is that it
can be hard to talk about these things clearly when
you're not sure whether the words you're using, such
as "assignment", mean the same thing to the person
on the other end. The interpreter always interprets
things unambiguously.

--
Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >