Re: tree functions daily exercise: Table

2005-06-24 Thread xah
Dear Dr Jon D Harrop,

“List Comprehension” is a special concise syntax form that
generates lists, as a way to save typing such as for loops. It is
primarily a jargon bandied about by programers which have contributed
huge misunderstandings and miscommunications. The extensiveness of this
particular jargon's harm has also encroached into functional programing
languages as to cause irregular syntax and less powerful semantics. The
utility of “list comprehension” is just a (normal) function
designed to generate list.

References:
• A exposition of list comprehension in Python.
http://xahlee.org/perl-python/list_comprehension.html

• Jargons of Info Tech Industry
http://xahlee.org/UnixResource_dir/writ/jargons.html

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

Jon Harrop wrote:
> David Hopwood wrote:
> > That's consistent with the behaviour of list comprehensions in other
> > languages -- including "set/tuple formers" in SETL
> > , which I believe was the
> > first language to support them. I don't know of any language where
> > a list comprehension with multiple loops creates nested lists.
>
> I'm not entirely sure what a list comprehension is, but Mathematica might be
> an example of a language in which multiple loops create nested lists.
>
> --
> Dr Jon D Harrop, Flying Frog Consultancy
> http://www.ffconsultancy.com

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

Re: PEP 304 - is anyone really interested?

2005-06-24 Thread Patrick Maupin
John Roth wrote:

>  I'd like to suggest a different mechanism, at least for packages
> (top level scripts don't generate .pyc files anyway.)  Put a system
> variable in the __init__.py file.  Something like __obj__ = path
> would do nicely. Then when Python created the __init__.pyc file,
> it would insert a back link __src__ entry.

I like the kernel of that proposal.  One down-side is that you might
wind up compiling at least __init__.py on every execution which imports
the package (to extract the object directory variable __obj__).   If
you had automatic .pyc directory creation and updating of __obj__ for
sub-packages, you would only take the hit of recompiling the topmost
__init__.py in a package tree.

I'm not as sure about the use of the backlink -- it seems to introduce
a little bit of a chicken/egg problem to be able to import from a .pyc
directory which knows where its .py directory is -- how did the .pyc
files get there in the first place?  There must have been a separate
compilation phase at some point, and while I can envision a use case
for that, I don't have a pressing need for it.

I'm also not sure about the extent of the changes required to the
import/compile mechanism.  It seems the importer would have  to be able
to defer writing out the .pyc file until after the execution of the
body of the __init__.py module.

Finally, I think you're dismissing one of the discussed use-cases out
of hand :)  Although it is true that a top-level script will not
generate a .pyc file, a slightly more generic use of the term "script"
could encompass a top-level module and one or more sub-modules in the
same directory.  If the script is run infrequently enough and the
sub-modules are small enough, in some cases I would certainly love to
be able to tell Python "Please don't litter this directory with .pyc
files."

Assuming the deferral of writing .pyc files until after module
execution is is not a problem (for all I know it already works this
way, but I wouldn't know why that would be), I think a slightly more
fleshed out (but still very green) proposal might be:

1) When a module is first imported, the importing module's globals are
searched for an __obj__ identifier.  The importer will make a local
copy of this variable during the import:

objdir = passed_globals.get('__obj__', None)

2)  If a .pyc/.pyo file is found in the same directory as the
coresponding .py file:
   a) If the .pyc/.pyo is newer, it is loaded and executed and we
are done; or
   b)  objdir is set to None to indicate that we should regenerate
.pyc/.pyo in situ.

Step b) could be debated, but I think it would be very confusing to
have an out-of-date .pyc file in a directory, with the "real" .pyc file
elsewhere...

3) If this is a package import and objdir is a non-null string, objdir
is updated to include the package name.  Something like:

if is_package and objdir: objdir = os.path.join(objdir, package_name)

4) If objdir is a non-null string and there is a newer readable
.pyc/.pyo file at the directory indicated in objdir, that file is
loaded and executed and we are done.

5) The source file is compiled into memory.

6) If objdir is not None the globals of the newly created module are
updated such that __obj__= objdir.

7) The module body is executed, including performing any sub-imports.

8)  The module's __obj__ is now examined to determine if and where to
write the module's .pyc/.pyo file:

if __obj__  does not exist -- write to same directory as .py (same as
current behavior)

if __obj__ exists and is a non-empty string and is equal to objdir
(e.g. not modified during initial module body execution) -- write to
the named directory.  Create the leaf directory if necessary (e.g. for
package imports).

if __obj__ exists and is the empty string, do not create a .pyc file.
This allows author suppression of writing .pyc files.

if __obj__ exists but is not equal to objdir, create the leaf directory
if it does not exist, but do not write the .pyc file.   This is an
optimization for the case where __init__.py specifies a new package
subdirectory -- why write out a .pyc file if you won't know where it is
until you re-compile/re-execute the source .py file?  You'll never be
able to make use of the .pyc file and maybe you don't even have write
privileges in the directory.   Even though this is true, we still want
to create the directory, so that sub-package imports don't have to
create multiple directory levels.

I think this mechanism would allow for the following:

- Control of package/subpackage .pyc file location with a single line
of code in the topmost __init__ file, at the small cost of recompiling
the __init__ file on every program execution.

- Control of _all_  .pyc file location (unless overridden for a given
package as described above) from a top-level script.  In this case,
regular .pyc files would wind up _inside_ the __obj__ directory of the
package which first imported them, and package .pyc files would wind up
in a subdi

Re: Favorite non-python language trick?

2005-06-24 Thread Enrico
"Joseph Garvin" <[EMAIL PROTECTED]> ha scritto nel messaggio
news:[EMAIL PROTECTED]
> --This code won't run because it's in a comment block
> --[[
> print(10)
> --]]
>
> --This code will, because the first two dashes make the rest a comment,
> breaking the block
> ---[[
> print(10)
> --]]
>
> So you can change whether or not code is commented out just by adding a
> dash. This is much nicer than in C or Python having to get rid of """ or
> /* and */. Of course, the IDE can compensate. But it's still neat :)

python:

"""
print 10
"""

and

#"""
print 10
#"""

C++:

/*
print(10);
*/

and

///*
print(10);
//*/

?

Bye,
Enrico


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


Re: Favorite non-python language trick?

2005-06-24 Thread Uwe Mayer
Friday 24 June 2005 09:18 am Enrico wrote:

[...]
>> --This code will, because the first two dashes make the rest a comment,
>> breaking the block
>> ---[[
>> print(10)
>> --]]
[...]

> python:
> 
> """
> print 10
> """
> 
> and
> 
> #"""
> print 10
> #"""
> 
> C++:
> 
> /*
> print(10);
> */
> 
> and
> 
> ///*
> print(10);
> //*/
> 
> ?

I think the *trick* here was that if you had larger blocks you'd only have
to change one side of the comment, i.e. the opening line, to de-comment the
block without searching the end of it and commenting that out aswell.

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


printing indented html code

2005-06-24 Thread Lowell Kirsh
Is there a module or library anyone knows of that will print html code 
indented? What I'd like would be for a function or class which works 
like this:

htmlIndent(sys.stdout, 'foobar...')

and will print somethinkg like this to stdout:


   
 foobar
   
   ...

My current way of doing this kind of stuff is less than ideal and will 
write such a function if it doesn't exist.

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


Re: Running WMI within a Windows service

2005-06-24 Thread Roger Upole
Build 204 of pywin32 has a change so that the working dir
for a service  is the folder where its executable is located
instead of \system32, hopefully avoiding trying
to import wmi.dll instead of wmi.pyd.

   Roger

"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
[EMAIL PROTECTED]
|

[.. re problems running WMI in a service ...]

| Changing the path didn't do anything, but changing the name of the
| module to my_wmi did the trick.
|
| Thanks very much,
|
| Cam.
|

Thanks for the feedback; I'll try to find the time to
experiment a bit but I know I've used the change-the-name
trick in the past. It has been suggested that I permanently
change the module name, but I'm a bit loth to do that. Mark
(Hammond) was talking about a patch which would prevent
imports from picking up the false .dll, but I don't know
if it's gone anywhere.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
 



== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: connecting to an exsisting COM server

2005-06-24 Thread Roger Upole
Normally you get that if the application doesn't register itself
with the Running Object Table.  Do you know if the COM
server in question registers itself ?

 Roger

"jelle" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Hi,
>
> I'm using
> win32com.client.GetObject(Class='Rhino3.Application')
> to connect to an existing COM server. However when doing so:
>
> Traceback (most recent call last):
>  File "", line 1, in ?
>  File "C:\Python24\lib\site-packages\win32com\client\__init__.py",
> line 80, in GetActiveObject
>dispatch = pythoncom.GetActiveObject(resultCLSID)
> com_error: (-2147221021, 'Operation unavailable', None, None)
>
> A com_error is raised. This problem has come up a few times on this
> list, however that didn't help me to find a way of connecting to it.
> What else could I try?
>
> Cheers,
>
> Jelle
> 



== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-24 Thread gatti
Joseph Garvin wrote:
> I'm curious -- what is everyone's favorite trick from a non-python
> language? And -- why isn't it in Python?

Duff's device is a classic masterpiece of lateral thinking.
It is not possible in Python for many fundamental reasons, we are not
at risk.

Lorenzo Gatti

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


Re: Favorite non-python language trick?

2005-06-24 Thread Duncan Booth
Uwe Mayer wrote:

>> /*
>> print(10);
>> */
>> 
>> and
>> 
>> ///*
>> print(10);
>> //*/
>> 
>> ?
> 
> I think the *trick* here was that if you had larger blocks you'd only
> have to change one side of the comment, i.e. the opening line, to
> de-comment the block without searching the end of it and commenting
> that out aswell. 

Yes, but you can do that easily in C++ as well:

/*
print(10);
//*/

Change to:

//*
print(10);
//*/

I can't remember the exact pattern, but I remember using a
similar trick in BCPL where at least there was the excuse of not
otherwise having conditional compilation. C and C++ there is no excuse
for such tricks. 

Google found Clive Feather's description of the BCPL trick at 
http://www.lysator.liu.se/c/clive-on-history.html:

> I doubt it (though DMR may contradict me, of course).  Every compiler
> I remember using allowed both // and /* */ type comment delimiters. 
> Some also allowed | and \ to be used instead of /, so that || was also
> a comment-to-end-of-line, and \* ... *\ was an alternate block comment
> symbol.  The latter was particularly useful, because it could be used
> to comment out blocks of code that included /* ... */ comments (as
> with C, comments do not nest).  We used comments with vertical bars to
> implement a variety of conditional compilation: 
> 
>   |**||| IF
>   normal code
>   |* ELSE
>   alternate code
>   |* CANCEL ELSE
>   more normal code
>   |* ELSE
>   more alternate code
>   |**||| ENDIF
> 
> By default, this would compile the "normal code".  To switch to the
> "alternate code", the first line was changed to |**||* or |*
> instead.  Because this comment symbol was used, the code could contain
> normal comments and the "commenting-out" reverse comments I described
> above. 

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


Re: A tool for Python - request for some advice

2005-06-24 Thread TPJ
> (...) I've seen the claim that every Linux
> distro comes with Python installed, but can't verify it.

So have I. And I think it might be truth. The only problem is that
different distros might be released with different versions of Python.



> Then again, the same comments apply to bash. Distributions that have
> their roots in AT&T Unix probably don't come with bash by default,
> with Mac OS X being an exception. This makes depending on bash a bad
> idea if you want to write a script that portable across Unix distros.

Good to know. So my script written in bash will be primary targeted for
Linux distros. OK, I can live with that.

> If your target platform is Linux, indications are that python is as
> portable as bash.

I've thought about it for a few days and I disagree with you. Python
isn't as portable as bash because of one reason. The problem is that
development of Python is much more dynamic than development of bash. If
I wrote my script in Python it would be possible that this script
wouldn't run on the same distro with _different_ version of Python.

(This is problem because someone has sugested that he'd like to run
this script on RH 9. So older distros must be considered as well as
newer.)

As long as I'm using bash, I'll deal with a tool that has the same
features on different distros (well... _almost_ the same features)

(This is about portability, of course. There are also another
advantages of using bash.)

> If your target platform is Unix, then the same is true - except you
> shouldn't be writing bash if you want portability.

Well, my primary goal is Linux. I'm working on Linux and I have no
access to any *BSD system (or another flavour of Unix). I thought that
bash scripts are portable, but now I can see I was wrong.

Thanks for all your help.

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


Re: zipfile + symlink [Solved]..

2005-06-24 Thread A. Murat Eren

 Hi again,

On Thursday 23 June 2005 23:43, A. Murat Eren wrote:
>  I have a problem about zipfile.

 I solved the problem and want to share my solution for archiving purposes (Hi 
Googlers ;))..

> ---8<---8<8<--8<---
> def add_file(self, fileName):
> """add file or directory to a zip file"""
> if os.path.isdir(fileName):
> self.zip.writestr(fileName + '/', '')
> for f in os.listdir(fileName):
>self.add_file(fileName + '/' + f)
> else:
> if os.path.islink(fileName):
> dest = os.readlink(fileName)
> self.zip.writestr(fileName, dest)
> #do something here to set 'fileName's attributes
> #to write it as a symlink into the zip
> else:
> self.zip.write(fileName, fileName, zipfile.ZIP_DEFLATED)
> 
> --->8--->8>8-->8---
>--
>
>  But here is a problem raising for symlinks (at the commented section of
> the code passage).. If i don't perform any special process for symlinks in
> the function, function produces zip files without symlinks, naturally;
> symlinks become regular files with the 'dest' content.. I have to set the
> attribute of the symlinks in the zip to make them a real symlink for the
> 'dest', how can i do that?

 Here is the solution for adding properly both dir and file symlinks into a 
zipfile:

 ---8<---8<8<--8<---

def add_file(self, fileName):
"""Add file or directory to a zip file"""
if os.path.isdir(fileName) and not os.path.islink(fileName):
self.zip.writestr(fileName + '/', '')
for f in os.listdir(fileName):
   self.add_file(fileName + '/' + f)
else:
if os.path.islink(fileName):
dest = os.readlink(fileName)
attr = zipfile.ZipInfo()
attr.filename = fileName
attr.create_system = 3
attr.external_attr = 2716663808L # long type of hex val 
 # of '0xA1EDL'
 # say, symlink attr magic..
self.zip.writestr(attr, dest)
else:
self.zip.write(fileName, fileName, zipfile.ZIP_DEFLATED)

 --->8--->8>8-->8---

 When you trying to unpack this zipfile (or any zip file which contains 
symlinks), you have to check this value instead of directly reading from zip 
and writing to the file system:

 ---8<---8<8<--8<---

  info = zip.getinfo(fileName)
  if hex(info.external_attr) == 2716663808L:
  target = zip.read(fileName)
  os.symlink(target, ofile)

 --->8--->8>8-->8---



 Ciao,
-- 

- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
 A. Murat Eren
 meren at uludag.org.tr
 http://cekirdek.uludag.org.tr/~meren/
 0x527D7293, 
 7BCD A5A1 8101 0F6D 84A4  BD11 FE46 2B92 527D 7293
- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -

--
 Alan Cox sounds as if he hasn't followed the
 development of programming languages
 and compilers for the last 10 years (exa).
-


pgpzCyu9ndaDX.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: suggestions invited

2005-06-24 Thread Aditi
Thank You All for your valuable suggestions. You people definitely
eased out my problem and now I can start my work with an eclectic of
all of your solutions.
Greetings 
Aditi.

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


Re: Favorite non-python language trick?

2005-06-24 Thread Lowell Kirsh
Check out lisp macros. Other languages have macro systems but none 
compare in power to lisp's. They are so powerful in lisp because lisp is 
the only language where the source code closely resembles its parse tree 
(created within the compiler/interpreter).

Lowell

Joseph Garvin wrote:
> As someone who learned C first, when I came to Python everytime I read 
> about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), 
> getattr/setattr, the % operator, all of this was very different from C.
> 
> I'm curious -- what is everyone's favorite trick from a non-python 
> language? And -- why isn't it in Python?
> 
> Here's my current candidate:
> 
> So the other day I was looking at the language Lua. In Lua, you make a 
> line a comment with two dashes:
> 
> -- hey, this is a comment.
> 
> And you can do block comments with --[[ and ---]].
> 
> --[[
> hey
> this
> is
> a
> big
> comment
> --]]
> 
> This syntax lets you do a nifty trick, where you can add or subtract a 
> third dash to change whether or not code runs:
> 
> --This code won't run because it's in a comment block
> --[[
> print(10)
> --]]
> 
> --This code will, because the first two dashes make the rest a comment, 
> breaking the block
> ---[[
> print(10)
> --]]
> 
> So you can change whether or not code is commented out just by adding a 
> dash. This is much nicer than in C or Python having to get rid of """ or 
> /* and */. Of course, the IDE can compensate. But it's still neat :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A tool for Python - request for some advice

2005-06-24 Thread TPJ


> So, to make sure I've understood (...) : you want to provide
> a specialized install script for Python (3rd party modules,
> non-standard locations, etc.)

yes

> You started in bash to deal with minority cases without an extant
> Python install.

My motivation was rather to avoid a bootstrap-like problems. I thought
that writing a script in _Python_ for compiling _Python_ is just silly
idea. I thought that bash (available even in rescue distros!) would be
a better tool.

> But clearly, there will be a Python install by the
> time your bash script is done, or something will have gone very wrong.

yes

> That suggests implementing the custom installation work in Python, and
> having a bash script that will



Well... not exactly.

My primary goal is to save time spent on downloading, uncompressing,
reading documentation, configuring, compiling and installing software.
So I want to write a tool that would allow me to spent a few minutes to
tell it what to do - and then it would do it all. I would pay attention
to this tool for a few minutes, instead of wasting much more time doing
it all myself.

I could check for a Python installation and install Python in standard
way in case Python wouldn't be available but this would have following
disadvantages:
1) It would be a large waste of time spent on installing Python in
standard way. (Especially if user wouldn't like _standard_ Python
installation. I'm working on this script because in most situations I'm
not happy with such standard installation!)
2) It would lead to download a particular Python's version for a
temporary purpose - and this means additional waste of time and
bandwith.

For now my script works as follows:
1) It allows user to configure all options and actions.
2) When user is ready it just does what it is supposed to do.

The first stage is very important - it takes a few minutes and then all
is done automatically.


Thanks for your advice - it was really helpful.

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


Re: suggestions invited

2005-06-24 Thread Aditi


Konstantin Veretennicov wrote:
> Pardon me, is it a real company or a fictious one?

I think my previous mail was in plain understandable english which can
be easily interpreted and clearly says the project has been assigned in
a not so intelligent spirit and thus sounds fictitious. I think going
through a problem before trying to reply is also a good idea.

> If you have real users, your first step is to talk to them to define
> project goals. Everything else (xml, python, etc.) is irrelevant until
> you know *what* you want to build.

Had this been possible I would not have posted the problem at all.


> Go talk to your potential users, know why (if at all) they need this
> monitoring system, learn their current tools and processes, see how
> your system could help them do their job more efficiently. Don't start
> coding until you have clear understanding of requirements.

> There are lots of nice intelligent people on this list, but they can't
> substitute people you are building this system for :)


Nice and intelligent people on this list and many other lists have
helped my by giving some suggestions and sharing their knowledge
...others who have not understood the problem can continue thinking
that they are also nice and intelligent. (:-))
Regards.
Aditi.

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


Re: A tool for Python - request for some advice

2005-06-24 Thread TPJ
I've heard about this "EasyInstall" and I like this idea.

If EI becomes a part of Python's standard library, my script will use
it.

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


Re: Favorite non-python language trick?

2005-06-24 Thread Roel Schroeven
Joseph Garvin wrote:
> As someone who learned C first, when I came to Python everytime I read 
> about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), 
> getattr/setattr, the % operator, all of this was very different from C.
> 
> I'm curious -- what is everyone's favorite trick from a non-python 
> language? And -- why isn't it in Python?
> 
> Here's my current candidate:
> 
> So the other day I was looking at the language Lua. In Lua, you make a 
> line a comment with two dashes:
> 
> -- hey, this is a comment.
> 
> And you can do block comments with --[[ and ---]].
> 
> This syntax lets you do a nifty trick, where you can add or subtract a 
> third dash to change whether or not code runs:
> 
> So you can change whether or not code is commented out just by adding a 
> dash. This is much nicer than in C or Python having to get rid of """ or 
> /* and */. Of course, the IDE can compensate. But it's still neat :)

Off topic, but in C or C++ it's easier to do it using

#ifdef 1
...
#endif

Then you just have to change the 1 into 0 or vice versa. It also 
prevents problems with nested comments.

Back on topic, the lack of such a construct in Python is actually one of 
the very few things that bother me in the language. There are 
work-arounds, of course; idle, for example, has a feature that prepends 
a # to every line in the selection, or removes the # again. But not all 
editors have such a feature, and even if they have it I still need to 
select the block of code every time. Not that big a deal though.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Favorite non-python language trick?

2005-06-24 Thread Claudio Grondi
> And you can do block comments with --[[ and ---]].

I am very happy not to have such "tricks" in Python.

Any other (useful) suggestions?

Claudio

"Joseph Garvin" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> As someone who learned C first, when I came to Python everytime I read
> about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(),
> getattr/setattr, the % operator, all of this was very different from C.
>
> I'm curious -- what is everyone's favorite trick from a non-python
> language? And -- why isn't it in Python?
>
> Here's my current candidate:
>
> So the other day I was looking at the language Lua. In Lua, you make a
> line a comment with two dashes:
>
> -- hey, this is a comment.
>
> And you can do block comments with --[[ and ---]].
>
> --[[
> hey
> this
> is
> a
> big
> comment
> --]]
>
> This syntax lets you do a nifty trick, where you can add or subtract a
> third dash to change whether or not code runs:
>
> --This code won't run because it's in a comment block
> --[[
> print(10)
> --]]
>
> --This code will, because the first two dashes make the rest a comment,
> breaking the block
> ---[[
> print(10)
> --]]
>
> So you can change whether or not code is commented out just by adding a
> dash. This is much nicer than in C or Python having to get rid of """ or
> /* and */. Of course, the IDE can compensate. But it's still neat :)


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


Re: don't understand MRO

2005-06-24 Thread Martin Franklin
Uwe Mayer wrote:
> Thursday 23 June 2005 19:22 pm Terry Reedy wrote:
> 
> [...]
> 
>>In the absence of other information, I would presume that none of the
>>other classes have a move() method.
> 
> 
> move() is implemented in the class qtcanvas.QCanvasItem
> I checked the pyqt sources and it is linked via sip to the C++ object file.
> In C++, QCanvasItem.move is delegated to QCanvasItem.moveBy. 
> 
> -- snip: C++ sources --
> void QCanvasItem::move( double x, double y ){
> moveBy( x-myx, y-myy );
> }
> 
> void QCanvasItem::moveBy( double dx, double dy ){
> if ( dx || dy ) {
> removeFromChunks();
> myx += dx;
> myy += dy;
> addToChunks();
> }
> }

I wonder if it is to do with the signature of these methods.  they
accept two doubles and perhaps the python bindings do not automatically
convert from integers, therefore these methods are not called and the
rules of mro kick in (thus calling the python move method)





> -- snip --
> 
> 
>>Are you sure that QCanvasItem has a move method?  What results from
>>
>print qtcanvas.QCanvasItem.move # ?
>>
>>If so, I would need to see its code to try to answer.
> 
> 
import qtcanvas
qtcanvas.QCanvasItem.move
> 
> 
> 
> Here is a working portion which recreates the strange output:
> 
> -- snip --
> from qtcanvas import *
> 
> class Node(object):
> def move(self, x,y):
> print "Node: move(%d,%d)"%(x,y)
> 
> class Rhomb(QCanvasPolygon, Node):
> def __init__(self, parent):
> QCanvasPolygon.__init__(self, parent)
> Node.__init__(self)
> 
> print Rhomb.mro()
> r = Rhomb(None)
> r.move(1,2)
> -- snip --
> 
> This prints:
> 
> [, ,  'qtcanvas.QCanvasPolygonalItem'>, ,  'qt.Qt'>, , , ]
> Node: move(1,2)
> 
> Ciao
> Uwe
> 

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


Re: Favorite non-python language trick?

2005-06-24 Thread Joseph Garvin
Claudio Grondi wrote:

>>And you can do block comments with --[[ and ---]].
>>
>>
>
>I am very happy not to have such "tricks" in Python.
>
>Any other (useful) suggestions?
>
>Claudio
>  
>
I'm glad and all that not everyone shares my enthusiasm over Lua's 
trick, and I'm glad that C/C++ can do it, but the original issue was 
non-python language tricks in general. Lets keep the thread on track.

So far we've got lisp macros and a thousand response's to the lua trick. 
Anyone else have any actual non-python language tricks they like?

Yeesh.


>"Joseph Garvin" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
>news:[EMAIL PROTECTED]
>  
>
>>As someone who learned C first, when I came to Python everytime I read
>>about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(),
>>getattr/setattr, the % operator, all of this was very different from C.
>>
>>I'm curious -- what is everyone's favorite trick from a non-python
>>language? And -- why isn't it in Python?
>>
>>Here's my current candidate:
>>
>>So the other day I was looking at the language Lua. In Lua, you make a
>>line a comment with two dashes:
>>
>>-- hey, this is a comment.
>>
>>And you can do block comments with --[[ and ---]].
>>
>>--[[
>>hey
>>this
>>is
>>a
>>big
>>comment
>>--]]
>>
>>This syntax lets you do a nifty trick, where you can add or subtract a
>>third dash to change whether or not code runs:
>>
>>--This code won't run because it's in a comment block
>>--[[
>>print(10)
>>--]]
>>
>>--This code will, because the first two dashes make the rest a comment,
>>breaking the block
>>---[[
>>print(10)
>>--]]
>>
>>So you can change whether or not code is commented out just by adding a
>>dash. This is much nicer than in C or Python having to get rid of """ or
>>/* and */. Of course, the IDE can compensate. But it's still neat :)
>>
>>
>
>
>  
>

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


Re: A tool for Python - request for some advice

2005-06-24 Thread Robert Kern
TPJ wrote:
> I've heard about this "EasyInstall" and I like this idea.
> 
> If EI becomes a part of Python's standard library, my script will use
> it.

Why wait? Just make it the second thing that the script installs after 
Python itself.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: pickle broken: can't handle NaN or Infinity under win32

2005-06-24 Thread Kent Johnson
Robert Kern wrote:
> 
> And floating point is about nothing if not being usefully wrong.
> 

+1 QOTW and maybe it could be worked into the FAQ about floats as well :-)
http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate

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


Re: printing indented html code

2005-06-24 Thread TechBookReport
Lowell Kirsh wrote:
> Is there a module or library anyone knows of that will print html code 
> indented? What I'd like would be for a function or class which works 
> like this:
> 
> htmlIndent(sys.stdout, 'foobar...')
> 
> and will print somethinkg like this to stdout:
> 
> 
>   
> foobar
>   
>   ...
> 
> My current way of doing this kind of stuff is less than ideal and will 
> write such a function if it doesn't exist.
> 
> Thanks,
> Lowell

There are lots of HTML pretty printers around, but for starters take a 
look at this: http://www.oreilly.com/catalog/pythonsl/chapter/ch05.html

HTH
==
TechBookReport - http://www.techbookreport.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: printing indented html code

2005-06-24 Thread Lowell Kirsh
Thanks. At a glance, that looks like it's what I'm looking for.

Lowell

TechBookReport wrote:
> Lowell Kirsh wrote:
> 
>> Is there a module or library anyone knows of that will print html code 
>> indented? What I'd like would be for a function or class which works 
>> like this:
>>
>> htmlIndent(sys.stdout, 'foobar...')
>>
>> and will print somethinkg like this to stdout:
>>
>> 
>>   
>> foobar
>>   
>>   ...
>>
>> My current way of doing this kind of stuff is less than ideal and will 
>> write such a function if it doesn't exist.
>>
>> Thanks,
>> Lowell
> 
> 
> There are lots of HTML pretty printers around, but for starters take a 
> look at this: http://www.oreilly.com/catalog/pythonsl/chapter/ch05.html
> 
> HTH
> ==
> TechBookReport - http://www.techbookreport.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble subclassing str

2005-06-24 Thread Kent Johnson
Donn Cave wrote:
> Left unexplained is ``true "is-a" relationships''.  Sounds
> like an implicit contradiction -- you can't implement
> something that truly is something else.  Without that, and
> maybe a more nuanced replacement for "is-implemented-using-a",
> I don't see how you could really be sure of the point.

Try this article for an explanation of is-a:
http://www.objectmentor.com/resources/articles/lsp.pdf

IMO Robert Martin explains what good OO design is better than anyone else. His 
book "Agile Software Development" is excellent.

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


Re: Thanks for PIL (and other stuff)

2005-06-24 Thread Do Re Mi chel La Si Do
+1

-- 
Michel Claveau



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


Re: suggestions invited

2005-06-24 Thread Simon Brunning
On 23 Jun 2005 13:46:18 -0700, Peter Herndon <[EMAIL PROTECTED]> wrote:
> Reasonable enough.  As per Mike's suggestion below, building a few web
> pages to document the apps is a good start.  To expand on that idea,
> you could write daemons/cron jobs, perhaps in Python if Python runs on
> OS/400,

http://www.iseriespython.com/

> that monitor each app's status and log that information to the
> web server.

I'm ot sure how you'd define an 'application' on a '400. You just have
a bunch of progams in libraries. I'm not sure what the 'status' of an
application might meain, either, in general terms. This is really very
pooly specified.

> You could then write a web application that takes the
> monitoring data and formats it appropriately for human consumption.

Running a Python web application on a '400 would be a pretty daunting
task, if it's even possible.

> Perhaps an RSS or Atom feed for each application's status.
> 
> I don't know anything about OS/400, but if it has a tool similar to
> syslog, you could configure the application hosts to report their
> status to a remote syslogd, perhaps on your web server, and parse the
> log file for the status data.

QHST is similar to syslog - but what's an application host in 400 terms?

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: formatted xml output from ElementTree inconsistency

2005-06-24 Thread Kent Johnson
Matthew Thorley wrote:
> Greetings, perhaps someone can explain this. I get to different styles 
> of formatting for xmla and xmlb when I do the following:
> 
> Is that because the some_file.xml is already nicely formatted? I thought 
> that the formatting was ignored when creating new elements.

ElementTree is preserving the whitespace of the original.
> 
> Is their a function to 'pretty print' an element? 

AFAIK this is not supported in ElementTree. I hacked my own by modifying 
ElementTree._write(); it wasn't too hard to make a version that suited my 
purposes.

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


Re: Favorite non-python language trick?

2005-06-24 Thread Thomas Guettler
Am Fri, 24 Jun 2005 00:55:38 -0600 schrieb Joseph Garvin:

> As someone who learned C first, when I came to Python everytime I read 
> about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), 
> getattr/setattr, the % operator, all of this was very different from C.
> 
> I'm curious -- what is everyone's favorite trick from a non-python 
> language? And -- why isn't it in Python?
> 
> Here's my current candidate:
[cut]
> This syntax lets you do a nifty trick, where you can add or subtract a
> third dash to change whether or not code runs:

I do it this way:

if 0: # Just for testing
print value
.

You only need to change "if 0" to "if 1" and the code gets executed.

 Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: Help wanted in piping in Windows

2005-06-24 Thread Thomas Guettler
Am Fri, 24 Jun 2005 01:28:38 +0530 schrieb Apple Grew:

> I want to develope a Winboard like application which will support 
> Winboard protocol. For that I require to know how to handle piping in 
> Python. I seperated out module popen2, but when I use 
> fileObject.readline() then it halts the program if the sub-process is 
> waiting for user input; will executing the readline() part in a seperate 
> thread be helpful? My target platform is Windows.
> 
> Links to helpful web resources and sample Python codes will be highly 
> appreciated.

Piping on Windows is not much different than on Unix. You
should only have *one* open file descriptor. If the subprocess
needs to read from stdin, then stdout and stderr should be
redirected to a file. Otherwise you can get deadlocks, because
the buffers have a finit size.

AFAIK ">file" and "2>file" does work on windows.

On Unix you can the module "select".

 HTH,
  Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: getting tracebacks from traceback objects

2005-06-24 Thread Kent Johnson
Michael P. Soulier wrote:
> Hello,
> 
> For a GUI app I've tried resetting sys.excepthook to my own
> exceptionhandler bound method, which accepts a type, value and traceback
> object. 
> 
> Now, the traceback module has print_exc and format_exc methods that are
> supposed to take a traceback object and return a formatted traceback
> like the default output. Unfortunately I keep getting 'None' out of
> them. Not sure why. 

You are misreading the docs. print_exc() and format_exc() take args of [limit[, 
file]] not a traceback.

> I want format_exe especially, since I don't want to print to stdout, I
> want to provide the traceback in a popup dialog.

Use format_exception() or pass a StringIO object as the file parameter to 
print_exc().

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


Re: printing indented html code

2005-06-24 Thread Konstantin Veretennicov
On 6/24/05, Lowell Kirsh <[EMAIL PROTECTED]> wrote:
> Is there a module or library anyone knows of that will print html code
> indented?

Depends on whether you have to deal with xhtml, valid html or just
any, possibly invalid, "pseudo-html" that abounds on the net.

Here's an example of (too) simple html processing using standard
HTMLParser module:

from HTMLParser import HTMLParser

class Indenter(HTMLParser):

def __init__(self, out):
HTMLParser.__init__(self)
self.out = out
self.indent_level = 0

def write_line(self, text):
print >> self.out, '\t' * self.indent_level + text

def handle_starttag(self, tag, attrs):
self.write_line(
'<%s %s>' % (tag, ' '.join('%s=%s' % (k, v) for k, v in attrs))
)
self.indent_level += 1

def handle_endtag(self, tag):
self.indent_level -= 1
self.write_line('' % tag)

handle_data = write_line

# handle everything else...
# http://docs.python.org/lib/module-HTMLParser.html

if __name__ == '__main__':
import sys
i = Indenter(sys.stdout)
i.feed('foobarbody')
i.close()

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


Re: printing indented html code

2005-06-24 Thread Lowell Kirsh
Looks good. I'll give it a try.

Konstantin Veretennicov wrote:
> On 6/24/05, Lowell Kirsh <[EMAIL PROTECTED]> wrote:
> 
>>Is there a module or library anyone knows of that will print html code
>>indented?
> 
> 
> Depends on whether you have to deal with xhtml, valid html or just
> any, possibly invalid, "pseudo-html" that abounds on the net.
> 
> Here's an example of (too) simple html processing using standard
> HTMLParser module:
> 
> from HTMLParser import HTMLParser
> 
> class Indenter(HTMLParser):
> 
> def __init__(self, out):
> HTMLParser.__init__(self)
> self.out = out
> self.indent_level = 0
> 
> def write_line(self, text):
> print >> self.out, '\t' * self.indent_level + text
> 
> def handle_starttag(self, tag, attrs):
> self.write_line(
> '<%s %s>' % (tag, ' '.join('%s=%s' % (k, v) for k, v in attrs))
> )
> self.indent_level += 1
> 
> def handle_endtag(self, tag):
> self.indent_level -= 1
> self.write_line('' % tag)
> 
> handle_data = write_line
> 
> # handle everything else...
> # http://docs.python.org/lib/module-HTMLParser.html
> 
> if __name__ == '__main__':
> import sys
> i = Indenter(sys.stdout)
> i.feed('foobarbody')
> i.close()
> 
> - kv
-- 
http://mail.python.org/mailman/listinfo/python-list


howto load and unload a module

2005-06-24 Thread Guy Robinson
Hello,

I have a directory of python scripts that all (should) contain a number of 
attributes and methods of the same name.

I need to import each module, test for these items and unload the module. I 
have 
2 questions.

1.. How do unload an imported module?
2.. how do I test for the existance of a method in a module without running it?

TIA,

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


Re: howto load and unload a module

2005-06-24 Thread Peter Hansen
Guy Robinson wrote:
> I have a directory of python scripts that all (should) contain a number 
> of attributes and methods of the same name.
> 
> I need to import each module, test for these items and unload the 
> module. I have 2 questions.
> 
> 1.. How do unload an imported module?

Why would you want to?  Doing what you describe doesn't require that you 
"unload" a module, unless that means something more to you than, say, 
merely releasing the memory used by it (which is likely insignificant to 
you).

> 2.. how do I test for the existance of a method in a module without 
> running it?

The object bound to the name used in the import statement is, well, an 
object, so you can use the usual tests:

import mymodule
try:
 mymodule.myfunction
except AttributeError:
 print 'myfunction does not exist'

or use getattr(), or some of the introspection features available in the 
"inspect" module.

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


Re: Help wanted in piping in Windows

2005-06-24 Thread Peter Hansen
Thomas Guettler wrote:
> AFAIK ">file" and "2>file" does work on windows.

Not, unfortunately (at least in the past), on Windows 98.

That might no longer matter, however.  How many people are still stuck 
using Windows 98?  Given that in one year you won't even be able to get 
support from Microsoft's update site (such as if you have to reinstall), 
isn't it time to move on?

to Linux...

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


Sorting part of a list

2005-06-24 Thread Sibylle Koczian
Hello,

I thought I understood list slices, but I don't. I want to sort only the 
last part of a list, preferably in place. If I do

 >>> ll = [3, 1, 4, 2]
 >>> ll[2:].sort()
 >>> ll
[3, 1, 4, 2]

ll isn't changed, because ll[2:] is a copy of the last part of the list, 
and this copy is sorted, not the original list. Right so far?

But assignment to the slice:

 >>> ll[2:] = [2, 4]
 >>> ll
[3, 1, 2, 4]

_does_ change my original ll.

What did I misunderstand?

Thanks,
Sibylle

-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


help!

2005-06-24 Thread Eser Çetinkaya
Title: help!






In your documentation, it is written :

  "

  os.path.getatime(path)

Return the time of last access of path. The return value is a number giving the number of seconds since the epoch (see the time  module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number. 

"


what do you mean by "access" ?  this function gives same outputs with the " os.path.getmtime(path) "  

What can change an acess time of a path different from modification?

Is there any mistakes in the implementation or am i missing some points?


M.Eser Cetinkaya



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

help!

2005-06-24 Thread Eser Çetinkaya
Title: help!








In your documentation, it is written :

  "

  os.path.getatime(path)

Return the time of last access of path. The return value is a number giving the number of seconds since the epoch (see the time  module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number. 

"


what do you mean by "access" ?  this function gives same outputs with the " os.path.getmtime(path) "  

What can change an acess time of a path different from modification?

Is there any mistakes in the implementation or am i missing some points?


M.Eser Cetinkaya



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

Re: OT: Re: Looking For Geodetic Python Software

2005-06-24 Thread Diez B. Roggisch
Dennis Lee Bieber wrote:
>   Of course, the great circle arc, except for paths with start/end
> latitude of 0 (equator) or with (lon1 - lon2) = 0, require a constant
> variation in compass heading -- and I don't think IFR currently make use
> of great circle arcs (and GPS to maintain them).

I'm not totally sure what you mean by IFR - but I know for certain that 
intercontinental flights do flight on great circles - as this saves 
considerable amounts of distance and thus time, fuel and money. And GPS 
isn't exactly news on multi-million-dollar heavy airplanes...


Diez

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


Re: howto load and unload a module

2005-06-24 Thread Fuzzyman
Answer to 2 - ``hasattr(module, name)``

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


Re: howto load and unload a module

2005-06-24 Thread Guy Robinson

> 
> Why would you want to?  Doing what you describe doesn't require that you 
> "unload" a module, unless that means something more to you than, say, 
> merely releasing the memory used by it (which is likely insignificant to 
> you).
> 

Hi Peter,

I have an application with Python embedded. I'm parsing a script directory to 
build a dictionary of script names with descriptions of what the scripts etc 
extracted from each script. The user then selects one of these scripts to 
execute by the embedded python.

Some of these scripts could potentially be quite large. Also the list of 
scripts 
could be quite large. So the main reason for unloading modules is to save 
memory.

Regards,

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


Re: Sorting part of a list

2005-06-24 Thread Fuzzyman
You can assign to a slice in place, but referencing a slice creates a
copy.

I think you understand it quite well :-)

a = ll[2:]
a.sort()
ll[2:] = a

To do a partial sort, in place, you'll have to subclass list - but
you'll still end up doing something similar unless you delve into C or
write your own sort algorithm in Python. Neither are recommended.

Best Regards,

Fuzzy
http://.voidspace.org.uk/python 
(back online hurrah)

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


Re: help!

2005-06-24 Thread Andreas Kostyrka
Just out of curiosity, does the filesystem support seperate a/m/c times?

Andreas

On Fri, Jun 24, 2005 at 02:49:01PM +0300, Eser Çetinkaya wrote:
> 
> 
> In your documentation, it is written :
>   "
>   os.path.getatime(path)
>   Return the time of last access of path. The return value is a number 
> giving the number of seconds since the epoch (see the time  
> module). Raise os.error if the file does not exist or is inaccessible. New in 
> version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, 
> the result is a floating point number. 
>   "
> 
> what do you mean by "access" ?  this function gives same outputs with the " 
> os.path.getmtime(path) "  
> What can change an acess time of a path different from modification?
> Is there any mistakes in the implementation or am i missing some points?
> 
> M.Eser Cetinkaya

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


Re: Sorting part of a list

2005-06-24 Thread John Machin
Sibylle Koczian wrote:
> Hello,
> 
> I thought I understood list slices, but I don't. I want to sort only the 
> last part of a list, preferably in place. If I do
> 
>  >>> ll = [3, 1, 4, 2]
>  >>> ll[2:].sort()

It may help in unravelling any bogglement to point out that this is 
equivalent to

temp = ll[2:]; temp.sort(); del temp


>  >>> ll
> [3, 1, 4, 2]
> 
> ll isn't changed, because ll[2:] is a copy of the last part of the list, 
> and this copy is sorted, not the original list. Right so far?

Quite correct.

> 
> But assignment to the slice:
> 
>  >>> ll[2:] = [2, 4]
>  >>> ll
> [3, 1, 2, 4]
> 
> _does_ change my original ll.

Quite correct.

> 
> What did I misunderstand?


What misunderstanding? You have described the behaviour rather 
precisely. Which of the two cases is boggling you?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting part of a list

2005-06-24 Thread Benji York
Fuzzyman wrote:
> a = ll[2:]
> a.sort()
> ll[2:] = a
> 
> To do a partial sort, in place, you'll have to subclass list 

Or be using 2.4:

 >>> ll = [3, 1, 4, 2]
 >>> ll[2:] = sorted(ll[2:])
 >>> ll
[3, 1, 2, 4]
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: create a pdf file

2005-06-24 Thread Jim
If it is a plain text file (or close to it, like the Gutenburg Project
files), think about using pdfLaTeX.

Jim

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


Re: help!

2005-06-24 Thread Benji York
Eser Çetinkaya wrote:
> What can change an acess time of a path different from modification?
> Is there any mistakes in the implementation or am i missing some points?

When a file is read it is accessed but not modified:

 >>> import os.path
 >>> os.path.getmtime('a_file')
1119615705
 >>> os.path.getatime('a_file')
1119615705
 >>> os.system('cat a_file')
0
 >>> os.path.getmtime('a_file')
1119615705
 >>> os.path.getatime('a_file')
1119615758
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


webserver application (via Twisted?)

2005-06-24 Thread flupke
I need to program and setup serveral webservices.
If i were still using jsp, i would use Tomcat to make the several
applications available on a given port.
How can i accomplish this in Python?
I was thinking about Twisted but it's not clear to me what parts i need 
to make a webserver listen on a certain port and having it serve 
different application based on the url that i received.

Any advice on this?

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


Re: Favorite non-python language trick?

2005-06-24 Thread Steven D'Aprano
On Fri, 24 Jun 2005 00:55:38 -0600, Joseph Garvin wrote:

> I'm curious -- what is everyone's favorite trick from a non-python 
> language? And -- why isn't it in Python?

Long ago, I used to dabble in Forth. You could say, the entire Forth
language was a trick :-) It was interesting to be able to define your own
compiler commands, loop constructs and so forth.

One of the things I liked in Pascal was the "with" keyword. You could
write something like this:

with colour do begin
red := 0; blue := 255; green := 0;
end;

instead of:

colour.red := 0; colour.blue := 255; colour.green := 0;

Okay, so maybe it is more of a feature than a trick, but I miss it and it
would be nice to have in Python.


-- 
Steven

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


Two questions on lambda:

2005-06-24 Thread Xavier Décoret
Hi,

I cannot find the way to do generic lambda functions using the lambda 
syntax in python. I am probably missing a point.

For example, the code

# f = lambda : print "hello"
# f()

does not compile, although:

# def f():
#   print "hello"
# f()

does compile. Is there a particular syntax for lambda that I am missing 
or is it simply limited and I cannot do what I want with lambda.

In the same spirit, how can I do to compute intermediary values in the 
body of a lambda function. Let's say (dummy example):

f = lambda x : y=x*x,y+y


In languages like Caml, you can do:

let f = function x -> let y=x*x in y+y;;

Does the lambda : syntax in python allow for the same kind of constructs?

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


Re: Looking For Geodetic Python Software

2005-06-24 Thread paron
Howard Butler http://hobu.biz/ has some nice Python wrappers for gdal
and Frank Warmerdam's other tools. I have to say, though, that geodesy
is inherently complicated. Python makes it easy to program, but not
easy to understand. http://maps.hobu.net:7080/RPC2 is an XMLRPC service
that he exposes that will transform various coordinate systems: take a
look at http://hobu.biz/index_html/projection_service/blogentry_view to
see what I mean.

Ron Phillips

Tim Daneliuk wrote:
> Is anyone aware of freely available Python modules that can do any of
> the following tasks:
>
> 1) Given the latitude/longitude of two locations, compute the distance
> between them.  "Distance" in this case would be either the straight-line
> flying distance, or the actual over-ground distance that accounts for
> the earth's curvature.
>
> 2) Given n latitude/longitude coordinates, compute the
> "geocenter".  That is, return the lat/long of the location that
> is most "central" to all n initial coordinates.
>
> 3)  Given n lat/long coordinates, compute a Kruskal-type spanning
>  tree.
>
> 4) Given n lat/long coordinates, compute an optimal (shortest or longest)
> visitation path that reaches each node exactly once.  Better still would
> be something that had "pluggable" heuristic engines so we could try
> different approaches like greedy, shortest-path, hill climbing, and
> so forth.  It would be even nicer if one could also simulate different
> routing schemes (Monte Carlo?).
>
> In effect, I'm looking for something that mates traditional graph traversal
> heuristics with operations research tools working on a geodetic
> coordinate system.   This is *way* outside my field of expertise so
> I'm hoping someone has taken the pain of it for dummies like me ;)
>
> TIA,
> --
> 
> Tim Daneliuk [EMAIL PROTECTED]
> PGP Key: http://www.tundraware.com/PGP/

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


Re: Favorite non-python language trick?

2005-06-24 Thread Claudio Grondi
I supose it will be very, very hard to find a trick
which turns out useful in Python. The current
set of features is from my point of view very
well designed out of the experience with many
other languages, so maybe you can use Python
as reference telling you which tricks are really
useful in programming and which are just bad,
non-Pythonic style.

At least I am myself out of ideas, else I had
proposed a PEP already, to get it or have
provided a module for it.

So feel free to poke around with Python.

if(not \
"--[[" == "--[["):
  # block of code
# --]]
as (already suggested) will also do the
trick with the block comment.

By the way,   I personally find
--[[
 good style comment block
]]--
or
[[--
 good style comment block
--]]
much more intuitive than
--[[
 bad style comment block
--]]

Claudio


"Joseph Garvin" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Claudio Grondi wrote:
>
> >>And you can do block comments with --[[ and ---]].
> >>
> >>
> >
> >I am very happy not to have such "tricks" in Python.
> >
> >Any other (useful) suggestions?
> >
> >Claudio
> >
> >
> I'm glad and all that not everyone shares my enthusiasm over Lua's
> trick, and I'm glad that C/C++ can do it, but the original issue was
> non-python language tricks in general. Lets keep the thread on track.
>
> So far we've got lisp macros and a thousand response's to the lua trick.
> Anyone else have any actual non-python language tricks they like?
>
> Yeesh.
>
>
> >"Joseph Garvin" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
> >news:[EMAIL PROTECTED]
> >
> >
> >>As someone who learned C first, when I came to Python everytime I read
> >>about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(),
> >>getattr/setattr, the % operator, all of this was very different from C.
> >>
> >>I'm curious -- what is everyone's favorite trick from a non-python
> >>language? And -- why isn't it in Python?
> >>
> >>Here's my current candidate:
> >>
> >>So the other day I was looking at the language Lua. In Lua, you make a
> >>line a comment with two dashes:
> >>
> >>-- hey, this is a comment.
> >>
> >>And you can do block comments with --[[ and ---]].
> >>
> >>--[[
> >>hey
> >>this
> >>is
> >>a
> >>big
> >>comment
> >>--]]
> >>
> >>This syntax lets you do a nifty trick, where you can add or subtract a
> >>third dash to change whether or not code runs:
> >>
> >>--This code won't run because it's in a comment block
> >>--[[
> >>print(10)
> >>--]]
> >>
> >>--This code will, because the first two dashes make the rest a comment,
> >>breaking the block
> >>---[[
> >>print(10)
> >>--]]
> >>
> >>So you can change whether or not code is commented out just by adding a
> >>dash. This is much nicer than in C or Python having to get rid of """ or
> >>/* and */. Of course, the IDE can compensate. But it's still neat :)
> >>
> >>
> >
> >
> >
> >
>


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


Re: howto load and unload a module

2005-06-24 Thread Peter Hansen
Guy Robinson wrote:
> Some of these scripts could potentially be quite large. Also the list of 
> scripts could be quite large. So the main reason for unloading modules 
> is to save memory.

Unless you're talking megabytes of bytecode (do a "wc *.pyc" on the 
compiled files and see) it's probably not worth the bother.

Still, assuming the modules are pure Python, and don't do strange things 
like inject references to themselves or their data into other places 
(i.e. other modules, including sys or builtins), it should be possible 
to unload them simply by deleting all references to them, *including* 
manually removing them from sys.modules.

How do you plan to import them?  Using the import statement, or 
__import__, or some other means?  How you do it will determine exactly 
what steps are required to free them up.

Note also that this won't necessarily release any memory back to the 
operating system, and it won't necessarily unload any extension modules 
or other shared libraries that are loaded.  The whole concept of 
"unloading" a module is pretty much undefined in Python, so whatever you 
can get is the best you can expect...

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


Re: howto load and unload a module

2005-06-24 Thread John Machin
Peter Hansen wrote:
> Guy Robinson wrote:
> 
>> I have a directory of python scripts that all (should) contain a 
>> number of attributes and methods of the same name.
>>
>> I need to import each module, test for these items and unload the 
>> module. I have 2 questions.
[snip]
>> 2.. how do I test for the existance of a method in a module without 
>> running it?

What the OP is calling a 'method' is more usually called a 'function' 
when it is defined at module level rather than class level.

> 
> 
> The object bound to the name used in the import statement is, well, an 
> object, so you can use the usual tests:
> 
> import mymodule
> try:
> mymodule.myfunction
> except AttributeError:
> print 'myfunction does not exist'
> 
> or use getattr(), or some of the introspection features available in the 
> "inspect" module.
> 

Ummm ... doesn't appear to scale well for multiple modules and multiple 
attributes & functions. Try something like this (mostly tested):

modules = ['foomod', 'barmod', 'brentstr', 'zotmod']
attrs = ['att1', 'att2', 'att3', 'MyString']
funcs = ['fun1', 'fun2', 'fun3']
# the above could even be read from file(s)
for modname in modules:
 try:
 mod = __import__(modname)
 except ImportError:
 print "module", modname, "not found"
 continue
 for attrname in attrs:
 try:
 attr = getattr(mod, attrname)
 except AttributeError:
 print "module %s has no attribute named %s" % \
 (modname, attrname)
 continue
 # check that attr is NOT a function (maybe)
 for funcname in funcs:
 pass
 # similar to above but check that it IS a function


BTW, question for the OP: what on earth is the use-case for this? Bulk 
checking of scripts written by students?

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


Re: Two questions on lambda:

2005-06-24 Thread Kristian Zoerhoff
On 6/24/05, Xavier Décoret <[EMAIL PROTECTED]> wrote:
> 
> For example, the code
> 
> # f = lambda : print "hello"
> # f()
> does not compile, although:
> 
> # def f():
> #   print "hello"
> # f()
> 
> does compile. Is there a particular syntax for lambda that I am missing
> or is it simply limited and I cannot do what I want with lambda.

lambda calls can only include functions; print is a statement, not a
function. Try this instead:

import sys
f = lambda : sys.stdout.writelines("Hello")
f()

However, if you're going to be binding the function to a name, there
is no need to use lambda at all; just def a function and be done with
it.

> In the same spirit, how can I do to compute intermediary values in the
> body of a lambda function. Let's say (dummy example):

I leave this to someone more expert than I.

-- 
Kristian

kristian.zoerhoff(AT)gmail.com
zoerhoff(AT)freeshell.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: webserver application (via Twisted?)

2005-06-24 Thread Peter Hansen
flupke wrote:
> I need to program and setup serveral webservices.
> If i were still using jsp, i would use Tomcat to make the several
> applications available on a given port.
> How can i accomplish this in Python?
> I was thinking about Twisted but it's not clear to me what parts i need 
> to make a webserver listen on a certain port and having it serve 
> different application based on the url that i received.
> 
> Any advice on this?

Yes, check the archives for the frequent past nearly identical questions 
and the detailed responses, or do a quick Google search for Python web 
frameworks.  There are perhaps dozens -- though less than a dozen really 
popular ones -- and most will do what you want, going by the most 
general interpretation of your question.  (If you're talking about 
duplicating whatever specific architecture appeals to you in Tomcat, I 
can't help you...)

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


Reminder: bug day on Saturday the 25th

2005-06-24 Thread A.M. Kuchling
The Python bug day is coming up tomorrow, Saturday June 25th, running from
1PM to 7PM UTC (9AM to 3PM Eastern).  Stop by the IRC channel (#python-dev
on irc.freenode.net) and join in!  For more info, see
.

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


Re: howto load and unload a module

2005-06-24 Thread Peter Hansen
John Machin wrote:
> Peter Hansen wrote:
[sample code]
> Ummm ... doesn't appear to scale well for multiple modules and multiple 
> attributes & functions. 

It certainly wouldn't! :-)  I was posting mainly to elicit more 
information, since clearly you wouldn't get far hardcoding all the names 
you were interested in.  (It's hard to judge a poster's level of 
expertise in Python without any example code from him.  That makes it 
too likely to go way above the head of the poster, and possibly provide 
a much more complex solution than he really needs.)

> Try something like this (mostly tested):
> 
> modules = ['foomod', 'barmod', 'brentstr', 'zotmod']
> attrs = ['att1', 'att2', 'att3', 'MyString']
> funcs = ['fun1', 'fun2', 'fun3']
> # the above could even be read from file(s)
> for modname in modules:
> try:
> mod = __import__(modname)
> except ImportError:
> print "module", modname, "not found"
> continue
> for attrname in attrs:
> try:
> attr = getattr(mod, attrname)
> except AttributeError:
> print "module %s has no attribute named %s" % \
> (modname, attrname)
> continue
> # check that attr is NOT a function (maybe)
> for funcname in funcs:
> pass
> # similar to above but check that it IS a function

Of course, one could simply hand the man a complete answer... ;-)

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


Re: Favorite non-python language trick?

2005-06-24 Thread utabintarbo
>with colour do begin
>red := 0; blue := 255; green := 0;
>end;
>
>instead of:
>
>colour.red := 0; colour.blue := 255; colour.green := 0;

Why not:

from color import *

red := 0
blue := 255
green := 0

...

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


Re: webserver application (via Twisted?)

2005-06-24 Thread garabik-news-2005-05
flupke <[EMAIL PROTECTED]> wrote:
> I need to program and setup serveral webservices.
> If i were still using jsp, i would use Tomcat to make the several
> applications available on a given port.
> How can i accomplish this in Python?
> I was thinking about Twisted but it's not clear to me what parts i need 
> to make a webserver listen on a certain port and having it serve 
> different application based on the url that i received.
> 
> Any advice on this?

I would use karrigell. Everyone is speaking about twisted, snakeletes
etc... but IMHO karrigell is unjustly underestimated - it is really
simple and clear framework.

-- 
 ---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Two questions on lambda:

2005-06-24 Thread Duncan Booth
Xavier Décoret wrote:

> Is there a particular syntax for lambda that I am missing 
> or is it simply limited and I cannot do what I want with lambda.

Lambda is deliberately limited. Just define a function.

The only downside to defining a function is that you have to think of a 
name for it, but that name is simply a variable like any other and can be 
rebound at will.

Any attempt to write an expression such as:

   f = lambda x : y=x*x,y+y

should instantly set off lots of alarm bells in your mind. Defining a 
lambda simply to assign it to a name is obviously wrong: it should be a 
function definition instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble subclassing str

2005-06-24 Thread Paul McGuire
>From purely Python terms, there is a distinction that one of these
classes (PaddedStr) is immutable, while the other is not.  Python only
permits immutable objects to act as dictionary keys, so this would one
thing to differentiate these two approaches.

But on a more abstract, implementation-independent level, this is a
distinction of inheritance vs. composition and delegation.  Inheritance
was one of the darling concepts in the early days of O-O programming,
with promises of reusability and development speed.  But before long,
it turned out that inheritance comes with some unfriendly baggage -
dependencies between subclasses and superclasses made refactoring more
difficult, and modifications to supertypes had unwanted effects on
subclasses.  Sometimes subclasses would use some backdoor knowledge of
the supertype data, thereby limiting flexibility in the superclass -
this phenomenon is often cited as "inheritance breaks encapsulation."

One check for good inheritance design is the Liskov Substitution
Principle (LSP) (Thanks for the Robert Martin link, Kent - you beat me
to it). Borrowing from the Wiki-pedia:
"In general, the principle mandates that at all times objects from a
class can be swapped with objects from an inheriting class, without the
user noticing any other new behaviour. It has effects on the paradigms
of design by contract, especially regarding to specification:
- postconditions for methods in the subclass should be more strict than
those in the superclass
- preconditions for methods in the subclass should be less strict than
those in the superclass
- no new exceptions should be introduced in the subclass"
(http://en.wikipedia.org/wiki/Liskov_substitution_principle)

One thing I like about this concept is that is fairly indepedent of
language or implementation features. I get the feeling that many such
rules/guidelines seem to be inspired by limitations or gimmicks that
are found in programming language X (usually C++ or Java), and then
mistakenly generalized to be universal O-O truths.

Looking back to PaddedStr vs. MyString, you can see that PaddedStr will
substitute for str, and for that matter, the MyString behavior that is
given could be a reasonable subclass of str, although maybe better
named StarredStr.  But let's take a slightly different MyString, one
like this, where we subclass str to represent a person's name:

class Person(str):
def __new__(cls,s,data):
self = str.__new__(cls,s)
self.age = data
return self

p = Person("Bob",10)
print p,p.age

This is handy enough for printing out a Person and getting their name.
But consider a father and son, both named "Bob".

p1 = Person("Bob",10)
p2 = Person("Bob",35)  # p1's dad, also named Bob
print p1 == p2  # prints 'true', should it?
print p1 is p2  # prints 'false'


Most often, I see "is-a" confused with "is-implemented-using-a".  A
developer decides that there is some benefit (reduced storage, perhaps)
of modeling a zip code using an integer, and feels the need to define
some class like:

class ZipCode(int):
def lookupState(self):
...

But zip codes *aren't* integers, they just happen to be numeric - there
is no sense in supporting zip code arithmetic, nor in using zip codes
as slice indices, etc.  And there are other warts, such as printing zip
codes with leading zeroes (like they have in Maine).

So when, about once a month we see on c.l.py "I'm having trouble
sub-classing ," I can't help but wonder if telling
the poster how to sub-class an XYZ is really doing the right thing.

In this thread, the OP wanted to extend str with something that was
constructable with two arguments, a string and an integer, as in s1 =
MyString("some text", 100).  I tried to propose a case that would be a
good example of inheritance, where the integer would be used to define
and/or constrain some str attribute.  A *bad* example of inheritance
would have been one where the 100 had some independent characteristic,
like a font size, or an age value to be associated with a string that
happens to contain a person's name.  In fact, looking at the proposed
MyClass, this seems to be the direction he was headed.

When *should* you use inheritance?  Well, for a while, there was such
backlash that the response was "Never".  Personally, I use inheritance
in cases where I have adopted a design pattern that incorporates it,
such as Strategy; otherwise, I tend not to use it.  (For those of you
who use my pyparsing package, it is loaded with the Strategy pattern.
The base class ParserElement defines an abstract do-nothing parsing
implementation, which is overridden in subclasses such as Literal,
Word, and Group.  All derived instances are treated like the base
ParserElement, with each subclass providing its own specialized
parseImpl or postParse behavior, so any subclass can be substituted for
the base ParserElement, satisfying LSP.)

I think the current conventional wisdom

Re: webserver application (via Twisted?)

2005-06-24 Thread Benedict Verheyen
flupke wrote:

Thanks Peter & Radovan for the answers

Regards,
Benedict

-- 
Benedict Verheyen   Debian User
http://www.heimdallitservices.bePublic Key 0x712CBB8D
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Two questions on lambda:

2005-06-24 Thread John Roth
"Xavier Décoret" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi,
>
> I cannot find the way to do generic lambda functions using the lambda 
> syntax in python. I am probably missing a point.

You are. Lambda is restricted to a _single expression_.

Your first example is a statement, not an expression. Your
second example attempts to do an assignment in the body
of a lambda (although that's not what the code actually says)
and assignment is a statement, not an expression.

Lambda is intended for very simple, one line functions. It's
also likely to go away in Python 3.0. Python, for better or
worse, is a multi-paradigm language combining the object
and procedural paradigms. It is not, and it is not intended
to be, a functional style language.

John Roth

>
> For example, the code
>
> # f = lambda : print "hello"
> # f()
>
> does not compile, although:
>
> # def f():
> # print "hello"
> # f()
>
> does compile. Is there a particular syntax for lambda that I am missing or 
> is it simply limited and I cannot do what I want with lambda.
>
> In the same spirit, how can I do to compute intermediary values in the 
> body of a lambda function. Let's say (dummy example):
>
> f = lambda x : y=x*x,y+y
>
>
> In languages like Caml, you can do:
>
> let f = function x -> let y=x*x in y+y;;
>
> Does the lambda : syntax in python allow for the same kind of constructs?
>
> Thanks. 

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


autoconfigure vss python question

2005-06-24 Thread lode leroy
Hi folks,

I'm trying to build a python module using MINGW on MSYS
the "configure" script is determining where python is installed as follows:

python.exe -c 'import sys; print sys.prefix'
c:\Python24

which is good on native windows (i.e. when invoked from CMD.EXE)

Is there a way to configure something in python or in the environment
so that when invoked from MSYS, it would behave as follows: (note the '/' 
vss '\')

python.exe -c 'import sys; print sys.prefix'
c:/Python24


thanks.


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


Re: Favorite non-python language trick?

2005-06-24 Thread Steven D'Aprano
On Fri, 24 Jun 2005 06:13:00 -0700, utabintarbo wrote:

>>with colour do begin
>>red := 0; blue := 255; green := 0;
>>end;
>>
>>instead of:
>>
>>colour.red := 0; colour.blue := 255; colour.green := 0;
> 
> Why not:
> 
> from color import *
> 
> red := 0
> blue := 255
> green := 0

Because colour is not a module, it is a record. Sorry, I assumed that
people would be familiar with Pascal records (similar to C structs) and
it wouldn't need explanation. My bad :-(

The closest example in Python would be:

def class Colour:
def __init__(self, blue=0, green=0, red=0):
self.blue = blue
self.green = green
self.red = red

which would become something like:

def class Colour:
def __init__(self, blue=0, green=0, red=0):
# pseudo-Python code borrowing concept "with" from Pascal
with self:
blue = blue
green = green
red = red

And now you can see why Python doesn't support this idiom.



-- 
Steven.

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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-24 Thread D H
Peter Hansen wrote:
> D H wrote:
> 
>> Peter Hansen wrote:
>>
>>> Bo Peng wrote:
>>>
 I need to pass a bunch of parameters conditionally. In C/C++, I can do
 func(cond1?a:b,cond2?c:d,.)

 Is there an easier way to do this in Python?
>>>
>>>
>>> Please read the FAQ to learn the answer and much other useful ...
>>
>>
>> The answer is no.  Use if statements.
> 
> 
> Actually that's just one possible answer.  Whether it's _the_ answer is 
> obviously again a matter of opinion, and as usual we differ.

Quit being such an idiot and refuting everything I say.  The answer is 
simply no, just use an if statement instead.


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


Re: webserver application (via Twisted?)

2005-06-24 Thread D H
flupke wrote:
> I need to program and setup serveral webservices.
> If i were still using jsp, i would use Tomcat to make the several
> applications available on a given port.
> How can i accomplish this in Python?
> I was thinking about Twisted but it's not clear to me what parts i need 
> to make a webserver listen on a certain port and having it serve 
> different application based on the url that i received.

See mod_python: http://www.modpython.org/
but there are literally dozens of other options in Python though:
http://wiki.python.org/moin/WebProgramming

If you want to it in your own standalone server, then I second the 
recommendation for Karrigell (which also can be run in mod_python as well).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-24 Thread Dave Brueck
D H wrote:
> Peter Hansen wrote:
>>D H wrote:
>>>Peter Hansen wrote:
Bo Peng wrote:
>>Actually that's just one possible answer.  Whether it's _the_ answer is 
>>obviously again a matter of opinion, and as usual we differ.
> 
> Quit being such an idiot and refuting everything I say.  The answer is 
> simply no, just use an if statement instead.

Please keep the discussion civil; please help keep c.l.py a nice place to visit.

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


Re: Favorite non-python language trick?

2005-06-24 Thread D H
Joseph Garvin wrote:
> I'm curious -- what is everyone's favorite trick from a non-python 
> language? And -- why isn't it in Python?

You can try out new features yourself now using various python 
extensions or descendants:
http://livelogix.net/logix/
- macros, no statement/expression distinction
http://students.ceid.upatras.gr/~sxanth/pyc/
- assignments are expressions, you can try other features never added
python like a ternary operator (x ? true action:false action)
http://boo.codehaus.org/
assignments are expressions, macros, static typing, no more "self"
required, ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Frame widget (title and geometry)

2005-06-24 Thread Shankar Iyer ([EMAIL PROTECTED])
Hi,

  I am still new to Python and Tkinter, so I apologize in advance if I do 
not word my question optimally.  I am trying to use a frame widget as the 
parent for other widgets.  There is a class with the header "class 
classtitle(Frame):" in a script called classtitle.py.  Having imported 
classtitle, I create a Frame widget within my gui using the command "w = 
Frame(self)."  Then, I grid this widget and issue the command "classinstance = 
classtitle.classtitle(w)."  When I attempt to execute this code, I receive an 
error claiming that w lacks geometry and title attributes that the code in 
classtitle.py attempts to access.  Does this mean that I cannot use a Frame 
widget as w in this situation?  Thanks for your help.

Shankar

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


Re: Favorite non-python language trick?

2005-06-24 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
>>with colour do begin
>>red := 0; blue := 255; green := 0;
>>end;
>>
>>instead of:
>>
>>colour.red := 0; colour.blue := 255; colour.green := 0;
> 
> Why not:
> from color import *
> 
> red := 0
> blue := 255
> green := 0

What do you think this actually does?

It doesn't do anything remotely resembling either of the things quoted 
above.  In fact, the "from color import *" line is pretty much useless here.

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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-24 Thread Richie Hindle

[Dave Brueck] 
> Please keep the discussion civil; please help keep c.l.py a nice place to 
> visit.

+1

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: webserver application (via Twisted?)

2005-06-24 Thread Jp Calderone
On Fri, 24 Jun 2005 12:35:40 GMT, flupke <[EMAIL PROTECTED]> wrote:
>I need to program and setup serveral webservices.
>If i were still using jsp, i would use Tomcat to make the several
>applications available on a given port.
>How can i accomplish this in Python?
>I was thinking about Twisted but it's not clear to me what parts i need
>to make a webserver listen on a certain port and having it serve
>different application based on the url that i received.
>
>Any advice on this?

Roughly,

from twisted.web import server, resource
from twisted.internet import reactor

root = resource.Resource()
root.putChild("app1", getApp1())
root.putChild("app2", getApp2())
...
site = server.Site(root)
reactor.listenTCP(80, site)
reactor.run()

You might also want to join the twisted-web mailing list: 
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web

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


Re: Favorite non-python language trick?

2005-06-24 Thread Doug Schwarz
In article <[EMAIL PROTECTED]>,
 "Enrico" <[EMAIL PROTECTED]> wrote:

> "Joseph Garvin" <[EMAIL PROTECTED]> ha scritto nel messaggio
> news:[EMAIL PROTECTED]
> > --This code won't run because it's in a comment block
> > --[[
> > print(10)
> > --]]
> >
> > --This code will, because the first two dashes make the rest a comment,
> > breaking the block
> > ---[[
> > print(10)
> > --]]
> >
> > So you can change whether or not code is commented out just by adding a
> > dash. This is much nicer than in C or Python having to get rid of """ or
> > /* and */. Of course, the IDE can compensate. But it's still neat :)
> 
> python:
> 
> """
> print 10
> """
> 
> and
> 
> #"""
> print 10
> #"""


It seems to me that this trick works in Python,too.

"""
print 10
#"""

and

#"""
print 10
#"""


You only have to change the first triple quote.

-- 
Doug Schwarz
dmschwarz&urgrad,rochester,edu
Make obvious changes to get real email address.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-24 Thread infidel
> def class Colour:
> def __init__(self, blue=0, green=0, red=0):
> # pseudo-Python code borrowing concept "with" from Pascal
> with self:
> blue = blue
> green = green
> red = red
>
> And now you can see why Python doesn't support this idiom.

Maybe it would make more sense if it was done a la Visual Basic

with self:
.blue = blue
.green = green
.red = red

requiring a dot to be typed removes the ambiguity and gives the IDEs a
chance to Intellisense-ify your coding.

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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-24 Thread D H
Dave Brueck wrote:
> Please keep the discussion civil; please help keep c.l.py a nice place 
> to visit.

You didn't see Peter Hansen's previous post to which I made my reply, so 
I'd like to extend your recommendation to *everyone* here.

Peter Hansen wrote:
 > Doug, please stop making an idiot of yourself ...[snipped more flames]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-24 Thread D H
infidel wrote:
>>def class Colour:
>>def __init__(self, blue=0, green=0, red=0):
>># pseudo-Python code borrowing concept "with" from Pascal
>>with self:
>>blue = blue
>>green = green
>>red = red
>>
>>And now you can see why Python doesn't support this idiom.
> 
> 
> Maybe it would make more sense if it was done a la Visual Basic
> 
> with self:
> .blue = blue
> .green = green
> .red = red
> 
> requiring a dot to be typed removes the ambiguity and gives the IDEs a
> chance to Intellisense-ify your coding.

Some made a python recipe emulating this I believe.  The python cookbook 
search engine is down though so I cannot find the link.
At one point Guido van Rossum was advocating this use of "with" as well, 
I believe: 
http://mail.python.org/pipermail/python-dev/2004-March/043545.html

But I don't think it is being considered now.  I think now "with" is 
being proposed for something more like VB and C#'s "using" statement. 
It automatically disposes of a resource when done with it: 
http://wiki.python.org/moin/WithStatement
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thanks for PIL (and other stuff)

2005-06-24 Thread TZOTZIOY
On 23 Jun 2005 19:12:03 -0700, rumours say that "jean-marc"
<[EMAIL PROTECTED]> might have written:

>So I wish it and its author(s) a good day, week, month, year and more!
>Really!

That is, "So long and thanks for all the PIL."
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-24 Thread Sergei Organov
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> On Fri, 24 Jun 2005 00:55:38 -0600, Joseph Garvin wrote:
> 
> > I'm curious -- what is everyone's favorite trick from a non-python 
> > language? And -- why isn't it in Python?
> 
> Long ago, I used to dabble in Forth. You could say, the entire Forth
> language was a trick :-) It was interesting to be able to define your own
> compiler commands, loop constructs and so forth.
> 
> One of the things I liked in Pascal was the "with" keyword. You could
> write something like this:
> 
> with colour do begin
> red := 0; blue := 255; green := 0;
> end;
> 
> instead of:
> 
> colour.red := 0; colour.blue := 255; colour.green := 0;
> 
> Okay, so maybe it is more of a feature than a trick, but I miss it and it
> would be nice to have in Python.

... that quickly becomes quite messy:

with A do begin
  .
  with B do begin
.
with C do begin
  x := y;
end;
  end;
end;

... and now you need to check the declarations of C, B, and A to
actually see what is assigned to what.

Worse yet, adding field 'x' to 'C' will (silently) break the code :(

I don't think it would be that nice to have it in Python.

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


Re: Favorite non-python language trick?

2005-06-24 Thread Tom Anderson
On Fri, 24 Jun 2005, Joseph Garvin wrote:

> Claudio Grondi wrote:
>
> So far we've got lisp macros and a thousand response's to the lua trick. 
> Anyone else have any actual non-python language tricks they like?

Higher-order functions like map, filter and reduce. As of Python 3000, 
they're non-python tricks. Sigh - i guess it's time for me to get to know 
list comprehensions a bit better.

The one thing i really do miss is method overloading by parameter type. I 
used this all the time in java, and it really notice the lack of it 
sometimes in python. No, it's not really possible in a typeless language, 
and yes, there are implementations based on decorators, but frankly, 
they're awful.

Yeah, and i'm with "if False:" for commenting out chunks of code.

tom

-- 
... but when you spin it it looks like a dancing foetus!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Frame widget (title and geometry)

2005-06-24 Thread Jeff Epler
It would help if you posted your code, as we're in the dark about
exactly what you tried to do and the error you received.

It sounds like you may be using the wrong type of widget for what you
want.  The terms used in Tk are different than in some other systems.

If you want a separate window with title bar etc, you want to create a
new instance of Tkinter.Toplevel.  It will have methods like wm_title
and wm_geometry.

Newer versions of Tk (8.4 and maybe 8.3) have a widget called
"labelframe" (called Tkinter.LabelFrame in python2.3 and newer) which is the
grooved-border-and-label container used to semantically group related
widgets.

"Frame" widgets are simply containers which are often useful for making
the screen layout work the way you want with pack and grid.

Jeff


pgpdBiMtDJV5v.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Thanks for PIL (and other stuff)

2005-06-24 Thread Rocco Moretti
jean-marc wrote:

> PS If I knew that Python had a anniversary date, I'd also write to
> thanks our BDFL (and authors)! But no such luck, so I'm restaining
> myself!
> ;-))

 From the FAQ:

> Here's a very brief summary of what started it all, written by Guido van 
> Rossum:
> 
> 
>
> During the 1989 Christmas holidays, I had a lot of time on my hand, so I 
> decided to give it a try. During the next year, while still mostly working on 
> it in my own time, Python was used in the Amoeba project with increasing 
> success, and the feedback from colleagues made me add many early improvements.
> 
> In February 1991, after just over a year of development, I decided to post to 
> USENET. The rest is in the Misc/HISTORY file.

Misc/HISTORY notes the source was uploaded to alt.sources

Google Searching alt.sources gives a posting date of Feb 20 1991, 11:22 
am for the message "Python 0.9.1 part 01/21", and the rest of the posts 
are spread out over 19-21 Feb 1991, according to Google. The text 
description in the body of the message gives a date of 19 February 1991.

If you're looking for an official "Birthday" of Python, you probably 
couldn't do much better than 19 February 1991.

(Happy 14th & 1/3ish Birthday Python!)

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


Re: Frame widget (title and geometry)

2005-06-24 Thread Eric Brunel
On Fri, 24 Jun 2005 10:21:01 -0400, Shankar Iyer ([EMAIL PROTECTED]) <[EMAIL 
PROTECTED]> wrote:

> Hi,
>
> I am still new to Python and Tkinter, so I apologize in advance if I do not
> word my question optimally.  I am trying to use a frame widget as the parent
> for other widgets.  There is a class with the header "class 
> classtitle(Frame):"
> in a script called classtitle.py.  Having imported classtitle, I create a 
> Frame
> widget within my gui using the command "w = Frame(self)."  Then, I grid this
> widget and issue the command "classinstance = classtitle.classtitle(w)."  When
> I attempt to execute this code, I receive an error claiming that w lacks
> geometry and title attributes that the code in classtitle.py attempts to 
> access.
> Does this mean that I cannot use a Frame widget as w in this situation?  
> Thanks
> for your help.

Please post a short script showing the behavior you get. Without this, we 
cannot help you much. The only thing I can tell you right now is that you 
obviously don't need to create a Frame via "w = Frame(self)": since you defined 
your classtitle class as a sub-class of frame, every instance of classtitle is 
also an instance of Frame, so you can use it as such:

>>> from Tkinter import *
>>>root = Tk()
>>> class MyClass(Frame):
... pass
...
>>> o = MyClass(root)
>>> o.grid()

just works. If you have to add anything in the constructor, do not forget to 
call the constructor for Frame in it, as in:

>>> class MyClass(Frame):
... def __init__(self, *args, **options):
... Frame.__init__(self, *args, **options)
... ## Other stuff...
...

If you do that, everything should be OK.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-24 Thread Roy Smith
Tom Anderson  <[EMAIL PROTECTED]> wrote:
> The one thing i really do miss is method overloading by parameter
> type.  I used this all the time in java

You do things like that in type-bondage languages like Java and C++
because you have to.  Can you give an example of where you miss it in
Python?

If you want to do something different based on the type of an
argument, it's easy enough to do:

def foo (bar):
if type(bar) == whatever:
   do stuff
else:
do other stuff

replace type() with isistance() if you prefer.

> No, it's not really possible in a typeless language, 

Python is not typeless.  It's just that the types are bound to the
objects, not to the containers that hold the objects.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python as client-side browser script language

2005-06-24 Thread jeoffwilks
Sorry to resurrect a slightly older topic, but I want to clarify some
points about how the browser DOM and the script language interact.

Paul Rubin wrote:
> Huh?  The language itself has to provide the sandbox.
> Remember that scripts have to be able to see
> certain DOM elements but not others, and some of them have to be
> read-only, etc.

Greg Ewing wrote:
> If the DOM objects are implemented as built-in Python
> types, there shouldn't be any difficulty with that.
> Python objects have complete control over which attributes
> can be read or written by Python code.

In web browsers, Javascript does not provide the sandbox. The browser
provides scripts with certain objects like "document" or "window" but
these are not native script objects at all. They're wrappers for
browser-native objects, usually written in C/C++ and exposed via an
ActiveX or XPCOM interface. (IE uses ActiveX, Mozilla uses XPCOM). The
interfaces to these browser-native objects enforce the security model
by restricting what the scripting language is allowed to do within the
browser context.

If you attempt any foul play with a browser-native object, it can
simply feed an exception back to the script wrapper, and your script
code fails. That's the sandbox.

Following are some relevant links for those interested in further
details:

DOM Intro (especially the section, DOM vs Javascript:)
"That is to say, [the script is] *written* in JavaScript, but it *uses*
the DOM to access the web page and its elements."
http://www.mozilla.org/docs/dom/domref/dom_intro.html

"Mozilla's DOM is coded almost entirely in C++. ...  When, in
JavaScript, a client tries to access a DOM object or a DOM method on a
DOM object, the JS engine asks XPConnect to search for the relevant C++
method to call."
http://www.mozilla.org/docs/dom/mozilla/hacking.html

"The DOM makes extensive use of XPCOM. In fact, to do anything with the
DOM implementation you need XPCOM."
http://www.mozilla.org/docs/dom/mozilla/xpcomintro.html

Talking to XPCOM in Python
"The techniques for using XPCOM in Python have been borrowed from
JavaScript - thus, the model described here should be quite familiar to
existing JavaScript XPCOM programmers."
http://public.activestate.com/pyxpcom/tutorial.html

So in theory you should be able to create a python script interpreter,
at least for Mozilla. In practice you'd either need to be an expert
with the Mozilla source code, XPCOM, and Python... or you'd find
yourself becoming an expert by necessity.

---

Incidentally when people don't understand the difference between DOM
objects and Javascript objects, they end up with lots of memory leaks:
http://jgwebber.blogspot.com/2005_01_01_jgwebber_archive.html

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


Running Python scripts under W2K with I/O redirection

2005-06-24 Thread sub1ime_uk
I apologise if this is a well known problem. I've searched and can't
find a clear description or fix. Hope someone can help.

I am running my Python scripts under Windows 2000 using Python 2.4
Build 243 from Activestate.

If I want to specify a file as standard input to my script I can just
enter a command like:

  H:\> pyscript.py file.inp

and that's what I get. All ok so far.

However if I enter commands like:

  H:\> type file.inp | pyscript.py

or

  H:\> pyscript.py < file.inp

It doesn't work. I've also tried the variant of parsing for a command
line argument of '-' or 'filename' and then specifically either copying
the sys.stdin file object or opening the file specified, then using
that file object. Same problem.

Interestingly enough, if I specify my commands as:

  H:\> type file.inp | python pyscript.py

or

  H:\> python pyscript.py < file.inp

It all works the (unix-like) way I wanted it to. This leads me to
suspect there is something wrong in the way that Python is being
invoked by Windows in my problem situation rather than an inherent
fault within Python itself.

Does anyone have any idea what the problem could be and how to fix it?
I know its a really minor niggle but it'd make this poor deprived
unix-guy-forced-into-windows-servitude very happy.

Thanks,  sub1ime_uk

sub1ime_uk (at) yahoo (dot) com

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


Re: help!

2005-06-24 Thread Johannes Findeisen
On Fri, 2005-06-24 at 14:14 +0200, Andreas Kostyrka wrote:
> On Fri, Jun 24, 2005 at 02:49:01PM +0300, Eser Çetinkaya wrote:
> > 
> > 
> > In your documentation, it is written :
> >   "
> >   os.path.getatime(path)
> > Return the time of last access of path. The return value is a number 
> > giving the number of seconds since the epoch (see the time 
> >  module). Raise os.error if the file does not exist or is 
> > inaccessible. New in version 1.5.2. Changed in version 2.3: If 
> > os.stat_float_times() returns True, the result is a floating point number. 
> > "
> > 
> > what do you mean by "access" ?  this function gives same outputs with the " 
> > os.path.getmtime(path) "  
> > What can change an acess time of a path different from modification?
> > Is there any mistakes in the implementation or am i missing some points?
> > 
> Just out of curiosity, does the filesystem support seperate a/m/c 
> times?

Hello Andreas,

some filesystems do support that. From the ext2 specification
( http://e2fsprogs.sourceforge.net/ext2intro.html ):

"As a response to these problems, two new filesytems were released in
Alpha version in January 1993: the Xia filesystem and the Second
Extended File System. The Xia filesystem was heavily based on the Minix
filesystem kernel code and only added a few improvements over this
filesystem. Basically, it provided long file names, support for bigger
partitions and support for the three timestamps."
   

Regards

--
Johannes Findeisen

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

Re: Favorite non-python language trick?

2005-06-24 Thread D H
Roy Smith wrote:
> Tom Anderson  <[EMAIL PROTECTED]> wrote:
> 
>>The one thing i really do miss is method overloading by parameter
>>type.  I used this all the time in java
> 
> 
> You do things like that in type-bondage languages like Java and C++
> because you have to.  Can you give an example of where you miss it in
> Python?

Well it's coming to a future Python version, so apparently there are 
many who can use it:
http://wiki.python.org/moin/Python3.0Suggestions#head-7df9d7035174644fdae024ed4a5ea0960a003ef5
I don't know if you'll have method overloading, but there will be type 
checking.  It's not actually compile-time "static typing" though.  The 
type checking still happens at run-time similar to your isinstance 
example, making code run slightly slower than a normal python method:
"Type checking is going to slow down your code." -GVR 2005 keynote, 
http://www.sauria.com/%7Etwl/conferences/pycon2005/20050324/The%20State%20of%20Python.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Two questions on lambda:

2005-06-24 Thread Christophe Delord
hello,

On Fri, 24 Jun 2005 14:48:16 +0200, Xavier Décoret wrote:

> Hi,
> 
> In the same spirit, how can I do to compute intermediary values in the
> 
> body of a lambda function. Let's say (dummy example):
> 
> f = lambda x : y=x*x,y+y
> 
> 
> In languages like Caml, you can do:
> 
> let f = function x -> let y=x*x in y+y;;
> 
> Does the lambda : syntax in python allow for the same kind of
> constructs?

You can define another lambda function with a default value for the y
parameter. For instance:

f = lambda x: (lambda y=x*x: y+y)()


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


Re: Running Python interpreter in Emacs

2005-06-24 Thread Philippe C. Martin
Hi,

Since I'm a Linux user, I went through the following procedure:

I installed emacs 20.7.1 and Python 2.4
I installed python-mode 1.0A into site-lisp
I added c:\python24 to my path

I put this .emacs on c:\ (see further down - I'm sure you don't need half of
it)

And everyhing is working fine: python mode is recognized and Ctr-C-C opens a
*Python Output* buffer with the results from my script:

print 1 ==> 1

Hope that helps,

Regards,


Philippe

*
(custom-set-variables
  ;; custom-set-variables was added by Custom -- don't edit or cut/paste it!
  ;; Your init file should contain only one such instance.
 '(auto-compression-mode t nil (jka-compr))
 '(case-fold-search t)
 '(current-language-environment "UTF-8")
 '(default-input-method "rfc1345")
 '(global-font-lock-mode t nil (font-lock))
 '(nil nil t)
 '(outline-minor-mode t)
 '(pc-select-meta-moves-sexps t)
 '(pc-select-selection-keys-only t)
 '(pc-selection-mode t t)
 '(save-place t nil (saveplace))
 '(show-paren-mode t nil (paren))
 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify)))
 '(transient-mark-mode t))

;(mouse-wheel-mode t)


(setq indent-tabs-mode nil)
;;(speedbar)

(custom-set-faces
  ;; custom-set-faces was added by Custom -- don't edit or cut/paste it!
  ;; Your init file should contain only one such instance.
 )


;(setq any mode-customization variables you want here)
(autoload 'visual-basic-mode "visual-basic-mode" "Visual Basic mode." t)
(autoload 'python-mode "python-mode" "Python mode." t)

(setq auto-mode-alist (append '(("\\.\\(py\\)$" . 
 python-mode)) auto-mode-alist))

(setq auto-mode-alist (append '(("\\.\\(frm\\|bas\\|cls\\)$" . 
 visual-basic-mode)) auto-mode-alist))


*



Rex Eastbourne wrote:

> Hi Skip and Philippe. I added the path for Python to PATH, but I still
> get the same message (when I try executing the current buffer, I get
> the message: "The system cannot find the path specified."
> 
> Philippe, I have the above lines of code in my .emacs file.
> 
> As for my environment, I'm running Emacs 21.4 on Windows XP.
> 
> Thanks a lot!

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


Re: Two questions on lambda:

2005-06-24 Thread Sean McIlroy
def PRINT(x): print x
f = lambda: PRINT("hello")

###

def let(x,y):
globals()[x] = y
return True

f = lambda x: let('y',x*x) and y+y

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


Parallel execution (CGI)

2005-06-24 Thread mmf
Hi!

I am using Python for CGI scripting. I had the following script:

#!/usr/bin/python
import sys
print 'Content-type: text/html\r\n\r\n'
print 'starting...'
sys.stdout.flush()
x = 99
y = 5478
counter = 0
while counter < 1000:
z = x^y
counter += 1
print 'finished!'
sys.stdout.flush()

I saved it in as test1.py - and tried to load it over HTTP. So
everything is fine.

But now I saw a very strange behaviour: I sent two parallel requests to
the script (for example by sending two requests in two browser windows
almost at the same time).

My problem: The requests to the script seem NOT to be done in parallel:
The first script prints "starting..." and after a short time
"finished". And then in the other browser window the second request
shows "starting...".

But I expected that in both browser windows "starting" will be shown
almost at the same time because the two requests are done in parallel.

The strange behaviour goes on:
If copied the test1.py and saved it as test2.py. Now I retried my test
and sent two requests - but to these two identical files (that only
differ in their filename). The the two requests seem to be done in
parallel...

(It tried my test on Fedora and Gentoo Linux, with Python 2.2 and
Python 2.4, with different webservers (Apache and others), and with
several different browsers - I always was the same.)

What am I doing wrong?

Best regards,
Markus Franz

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


Re: Favorite non-python language trick?

2005-06-24 Thread George Sakkis
"Joseph Garvin" wrote:

> I'm curious -- what is everyone's favorite trick from a non-python
> language? And -- why isn't it in Python?

Although it's an optimization rather than language trick, I like the
inline functions/methods in C++. There has been a thread on that in the
past (http://tinyurl.com/8ljv5) and most consider it as useless and/or
very hard to implement in python without major changes in the language
(mainly because it would introduce 'compile-time' lookup of callables
instead of runtime, as it is now). Still it might be useful to have for
time-critical situations, assuming that other optimization solutions
(psyco, pyrex, weave) are not applicable.

George

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


Re: trouble subclassing str

2005-06-24 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "Paul McGuire" <[EMAIL PROTECTED]> wrote:
[ ... lots of interesting discussion removed ... ]

> Most often, I see "is-a" confused with "is-implemented-using-a".  A
> developer decides that there is some benefit (reduced storage, perhaps)
> of modeling a zip code using an integer, and feels the need to define
> some class like:
> 
> class ZipCode(int):
> def lookupState(self):
> ...
> 
> But zip codes *aren't* integers, they just happen to be numeric - there
> is no sense in supporting zip code arithmetic, nor in using zip codes
> as slice indices, etc.  And there are other warts, such as printing zip
> codes with leading zeroes (like they have in Maine).

I agree, but I'm not sure how easily this kind of reasoning
can be applied more generally to objects we write.  Take for
example an indexed data structure, that's generally similar
to a dictionary but may compute some values.  I think it's
common practice in Python to implement this just as I'm sure
you would propose, with composition.  But is that because it
fails your "is-a" test?  What is-a dictionary, or is-not-a
dictionary?  If you ask me, there isn't any obvious principle,
it's just a question of how we arrive at a sound implementation --
and that almost always militates against inheritance, because
of liabilities you mentioned elsewhere in your post, but in the
end it depends on the details of the implementation.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-24 Thread Riccardo Galli
On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote:

>> Bo Peng wrote:
>>
>>> I need to pass a bunch of parameters conditionally. In C/C++, I can
>>> do func(cond1?a:b,cond2?c:d,.)
>>>
>>> Is there an easier way to do this in Python?
>>
>>
> The answer is simply no, just use an if statement instead.

That's not true.
One used form is this:
result = cond and value1 or value2

which is equal to
if cond:
   result=value1
else:
   result=value2


another form is:

result = [value2,value1][cond]


the first form is nice but value1 must _always_ have a true value (so not
None,0,'' and so on), but often you can handle this.

Bye,
Riccardo

-- 
Riccardo Galli
Sideralis Programs
http://www.sideralis.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-24 Thread Jeffrey Maitland
1 trick I liked in C++ was for For loops.

{
for(int i = 0; i < 100; i++){
 //do stuff
}
} 

wrapping the for loop in { } makes the i a local variable and then you
can use it again in the code if not  you will get a variable already
defined error.

As a side note python already keeps it a local variable, as most of us
know, and even if it did we can redifne it if we needed with ease.

Jeff
 
On 6/24/05, D H <[EMAIL PROTECTED]> wrote:
> Roy Smith wrote:
> > Tom Anderson  <[EMAIL PROTECTED]> wrote:
> >
> >>The one thing i really do miss is method overloading by parameter
> >>type.  I used this all the time in java
> >
> >
> > You do things like that in type-bondage languages like Java and C++
> > because you have to.  Can you give an example of where you miss it in
> > Python?
> 
> Well it's coming to a future Python version, so apparently there are
> many who can use it:
> http://wiki.python.org/moin/Python3.0Suggestions#head-7df9d7035174644fdae024ed4a5ea0960a003ef5
> I don't know if you'll have method overloading, but there will be type
> checking.  It's not actually compile-time "static typing" though.  The
> type checking still happens at run-time similar to your isinstance
> example, making code run slightly slower than a normal python method:
> "Type checking is going to slow down your code." -GVR 2005 keynote,
> http://www.sauria.com/%7Etwl/conferences/pycon2005/20050324/The%20State%20of%20Python.html
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-24 Thread D H
Riccardo Galli wrote:
> On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote:
> 
> 
>>>Bo Peng wrote:
>>>
>>>
I need to pass a bunch of parameters conditionally. In C/C++, I can
do func(cond1?a:b,cond2?c:d,.)

Is there an easier way to do this in Python?
>>>
>>>
>>The answer is simply no, just use an if statement instead.
> 
> 
> That's not true.
> One used form is this:
> result = cond and value1 or value2

So anywhere someone uses x?y:z you recommend they use "x and y or z" 
instead, or else "[y,z][x]", but not:

if x:
val = y
else:
val = z

I still would recommend just using an if statement, even though it is 
not easier to type than a ternary expression.  It is the most readable 
and understandable equivalent in Python.  And since his question was 
about an easier way to do it in Python, and I don't believe your 
alternative are any easier either, I believe the answer is still no.
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for Python Finite State Machine Implementations

2005-06-24 Thread Leonard J. Reder
Hello,

Although posted this a few weeks ago I still have gotten much feedback 
so I want to put this out again and see if the response gets a bit more 
interesting.

I have been searching on the web for a while now for a specific Python 
implementation of an FSM.  More specifically what I am looking
for is a Python implementation of the so called UML Harel State Machine
notion of a state machine.  These are multi-threaded capable state
machines with hierarchical representation capability (nested
instances of state machines).  They also have a unique conditional 
trigger symbol scheme for event representation and state machine 
transitions.

I have seen some great implementations of simple FSMs and some 
interesting descriptions of how generator/yeild python keywords can be 
used.  I think python has all the pieces to make a Heral implementation.

Does anyone know of a Python implementation of FSM that comes close to 
this functionality?  Any comments or recommendation for FSM packages 
that I could add this functionality to would also be welcome.  I 
certainly think someone has done something that approaches this already.

All replies are very much appreciated.  If I get enough response I will 
post a summary of findings to this group.

Thanks for reading this and any replies.

Regards,
Len

-- 

Leonard J. Reder
Jet Propulsion Laboratory
Interferometry Systems and Technology Section 383
Email: [EMAIL PROTECTED]
Phone (Voice): 818-354-3639
Phone (FAX): 818-354-4357
Mail Address:
Mail Stop: 171-113
4800 Oak Grove Dr.
Pasadena, CA. 91109
---
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >