Re: Optional Static Typing

2004-12-24 Thread Stephen Thorne
On 24 Dec 2004 21:35:24 -0800, Luis M. Gonzalez <[EMAIL PROTECTED]> wrote:
> I don't understand why this discussion on optional static typing came
> up right at this moment.

Because Guido made some notes on it.

http://www.artima.com/weblogs/viewpost.jsp?thread=85551

merry christmas.
Stephen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Optional Static Typing

2004-12-24 Thread Luis M. Gonzalez
I don't understand why this discussion on optional static typing came
up right at this moment.
As far as I know, it has been discussed many times in the past, and
there even was a SIG that simply died... but it seems that it never was
something of much interest to python developers (that's my impression,
I might be wrong).

Now, that the Pypy project is steadily advancing (and which is aimed at
making Python faster while keeping it dynamic and simple), why has this
topyc been raised?

Also there's starkiller, which deals with agressive type inference and
compilation to native code. If these projects are serious and are well
headed, then I don't know why we are talking now of static typing.

Lets say that Pypy and/or Starkiller end up as succesful projects, what
would be the advantage of having static typing in Python?

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


Re: Lambda going out of fashion

2004-12-24 Thread Skip Montanaro

Mike> Perl 6.0 is going to include even more drastic changes. It will
Mike> also include a Perl 5.x interpreter, and will have to be switched
Mike> to 6.0 mode by a magic cookie of some kind in the source. Possibly
Mike> Python 3.0 could do something similar. 

-1

Things are complex enough as it is.  Maintaining two interpreters that have
to somehow comingle would be worse.  Maintain Python 2.x as a separate
release for a period of time after Python 3.0 is released (a couple years,
anyway, maybe longer), but don't mix the two.

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


Re: Lambda going out of fashion

2004-12-24 Thread Terry Reedy

"Andrew Dalke" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Terry Reedy wrote:
>> As far as I know, apply(func, args) is exactly equivalent to 
>> func(*args).
>
> After playing around a bit I did find one difference in
> the errors they can create.

Ok, add 'assuming that func and args are a valid callable and sequence 
respectively.'  Error messages are not part of the specs, and may change 
for the same code from version to version.

 def count():
> ...   yield 1
> ...
 apply(f, count())
> Traceback (most recent call last):
>  File "", line 1, in ?
> TypeError: apply() arg 2 expected sequence, found generator
 f(*count())
> Traceback (most recent call last):
>  File "", line 1, in ?
> TypeError: len() of unsized object

>
> That led me to the following
>
 class Blah:
> ...   def __len__(self):
> ... return 10
> ...   def __getitem__(self, i):
> ... if i == 0: return "Hello!"
> ... raise IndexError, i
> ...
 blah = Blah()
 len(*blah)
> 6
 apply(len, *blah)

To be equivalent to len(*blah), this should be apply(len, blah), no *.

>>> apply(len, blah)
6 #Py2.2

> Traceback (most recent call last):
>  File "", line 1, in ?
> TypeError: len() takes exactly one argument (6 given)

>
> Is that difference a bug?

In your input, yes ;-)

Terry J. Reedy




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


Re: Optional Static Typing - Haskell?

2004-12-24 Thread Donn Cave
Quoth [EMAIL PROTECTED] (Alex Martelli):
| Donn Cave <[EMAIL PROTECTED]> wrote:
...
| > He didn't dwell much on it, but there was some mention of type
| > inference, kind of as though that could be taken for granted.
| > I guess this would necessarily be much more limited in scope
| > than what Haskell et al. do.
|
| Assuming that by "he" you mean GvR, I think I saw that too, yes.  And
| yes, a language and particularly a typesystem never designed to
| facilitate inferencing are hard-to-impossible to retrofit with it in as
| thorough a way as one that's designed around the idea.  (Conversely,
| making a really modular system work with static typing and inferencing
| is probably impossible; in practice, the type inferencer must examine
| all code, or a rather copious summary of it... it can't really work
| module by module in a nice, fully encapsulated way...).

Well, I would assume that a modules in a static system would present
a typed external interface, and inference would apply only within the
module being compiled.

for example, Objective CAML revised syntax -

  $ cat mod.ml
  module T =
struct
   type op = [On | Off];
   value print t a = match t with
  [ On -> print_string a | Off -> () ];
   value decide t a b = match t with
  [ On -> a | Off -> b ];
end;

  $ ocamlc -i -pp camlp4r mod.ml
  module T :
sig
  type op = [ On | Off ];
  value print : op -> string -> unit;
  value decide : op -> 'a -> 'a -> 'a;
end;

This is fairly obvious, so I'm probably missing the point,
but the compiler here infers types and produces an interface
definition.  The interface definition must be available to
any other modules that rely on this one, so they are relieved
of any need to examine code within this module.

There might be tricky spots, but I imagine the Objective CAML
folks would object to an assertion like "making a really modular
system work with static typing and inferencing is probably
impossible"!

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


Re: BASIC vs Python

2004-12-24 Thread has
Andrew Dalke wrote:
> /F
> > import random, winsound
>
> Now if it only worked for my mac ...
This might help:

http://www.stanford.edu/~andyszy/pyper/

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


Re: Creating Image Maps

2004-12-24 Thread Aaron
Thanks for the responses guys!

The first option you provided sounds great, Steve. I think I'm gonna try
it that way.



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


Re: IDLE problem :-(

2004-12-24 Thread Daniel Bickett
This is less of a bug and more of an inconvenience, on your part. It
happens because IDLE has a tailored shell allowing your cursor to
venture beyond the prompt, and across the text that the window
consists of (much like a loaded file in a text editor)

 Thus, the beginning of each line is not limited to the beginning of
the prompt, and 'home' sends you beyond it. The only 'work around', so
to speak, I can think to recommend is simply using a different shell
for your purposes, i.e. python.exe (on windows).

Daniel Bickett

On Sat, 25 Dec 2004 09:55:10 +1030, Ishwor <[EMAIL PROTECTED]> wrote:
> I don't know if this has been a problem with other people using IDLE
> but when i press the home key then the cursor jumps to the beginning
> of the line and not after the prompt. If google prints the right
> indentation then here how i want the IDLE prompt to work ->
> 
>  |>>> |(r,b,g).__class__
>  ^  ^
>  ^  ^-> want cursor here instead.
> cursor
> goes
> here
> 
> Any work around??
> Thank you.
> --
> cheers,
> Ishwor Gurung
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Axon 1.0

2004-12-24 Thread Michael Sparks
Hi,


Axon is the core set of modules in Kamaelia[1], and is essentially a set
of tools for managing concurrency inside a single thread.  Whilst it is a
pre-requisite for Kamaelia, it can be used independently as well.

Rather than the usual statemachine (or state machine derived) approach it
uses communicating generators. The design of the system is inspired very
heavily by asynchronous hardware verification systems. (Which leads to
similarities with CSP & unix pipelines)

[1] Kamaelia is BBC R&D testbed for developing media network protocols.
(It takes it's name from an internal BBC R&D project aimed at looking
how we scale internet delivery of the BBC's TV & Radio output.)

Sourceforge page with Axon release:
http://sourceforge.net/projects/kamaelia/

Installation is the usual "python setup.py install" dance, and the API
should be fairly stable, and has evolved over a period of time, hence the
1.0 release version. The project became test infected rather late in the
day, so some of test suite has been retrofitted if it looks a bit odd!

Kamaelia's website:
http://kamaelia.sourceforge.net/

(Explains context and there's a presentation that contains a simplified
implementation using decorators, which might help show use cases)

I've copied much of the README at the end of this mail for the curious.
(License is the Mozilla tri-license : MPL1.1, GPL2.0, LGPL2.1)

Merry Christmas! (Hopefully someone will find this a nice christmas toy :)


Michael.

Axon is the core of Kamaelia. The contents of this directory must be
installed before the rest of Kamaelia can be used. It can also be used
independently of Kamaelia.

The install procedure is python's usual dance:

   * python setup.py install

Documentation is held in two places:
   * The usual 'pydoc name' - probably worth starting with:
 pydoc Axon.Component

   * The test suite is designed to allow you to get low level API behaviour
 information - "should X,Y, Z work? If so, what happens?". It's a partly
 retrofitted test suite, but some is TDD. (TDD took over late in the
 project) As a result, for example, passing a -v flag result in the
 docstring for each test to be dumped in a form that allows collation,
 and summarisation. (For an example of what we expect to automate from
 the test suite, see the end of this README file)

Sample producer/consumber & wrapper component system:

/-- testComponent ---\
||
|  +-- Producer +  +-- Consumer +|
|  ||result|--->|source| |result|--->|_input||
|  ++  ++|
||
\/

The testComponent creates 2 subcomponents, creates the links in place, and
takes the output from the consumer and links it to its own private/internal
_input inbox. When it recieves a value from the consumer, it reports this
fact and ceases operation.

   Producer sends values to its result outbox
   Consumer takes values from its source, does some work and sends results to
  its outbox

(It's probably worth noting that an introspection system would be possible
to write/nice to see that would be able to derive the above diagram from
the running system)

Example code:

class Producer(component):
   Inboxes=[]
   Outboxes=["result"]
   def __init__(self):
  self.__super.__init__()
   def main(self):
  i = 100
  while(i):
 i = i -1
 self.send("hello", "result")
 yield  1

class Consumer(component):
   Inboxes=["source"]
   Outboxes=["result"]
   def __init__(self):
  self.__super.__init__()
  self.count = 0
  self.i = 30
   def doSomething(self):
  print self.name, "Woo",self.i
  if self.dataReady("source"):
 self.recv("source")
 self.count = self.count +1
 self.send(self.count, "result")

   def main(self):
  yield 1
  while(self.i):
 self.i = self.i -1
 self.doSomething()
 yield 1

class testComponent(component):
   Inboxes=["_input"]
   Outboxes=[]
   def __init__(self):
  self.__super.__init__()
  self.producer = Producer()
  self.consumer = Consumer()
  self.addChildren(self.producer, self.consumer)
  self.link((self.producer, "result"), (self.consumer, "source"))
  linkage(self.consumer,self,"result","_input", self.postoffice)

   def childComponents(self):
  return [self.producer, self.consumer]

   def mainBody(self):
  while len(self.inboxes["_input"]) < 1:
 yield 1
  result = self.recv("_input")
  print "Consumer finished with result:", result, "!"

r = scheduler()
p = testComponent()
children = p.childComponents()
p.activate()
for p in children:
   p.activate()
scheduler.ru

Re: Clearing the screen

2004-12-24 Thread Jeff Epler
I don't know about idle, but the "real" python supports the
PYTHONSTARTUP environment variable.
   PYTHONSTARTUP
  If  this is the name of a readable file, the Python commands in
  that file are executed before the first prompt is displayed  in
  interactive  mode.  The file is executed in the same name space
  where interactive commands are executed so that objects defined or
  imported  in  it  can be used without qualification in the
  interactive session.  You can also change the  prompts sys.ps1 and
  sys.ps2 in this file.

Jeff


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

Re: Clearing the screen

2004-12-24 Thread Ishwor
On 24 Dec 2004 15:33:26 -0800, Lars <[EMAIL PROTECTED]> wrote:
> Hi Iswor,
> 
> If I understand you correctly then your program is writing output to a
> console/terminal window and you want to clear that window.
> I don't know of any library methods for that, but you might just do:

well i am not doing any console i/o. Just simple one. i am trying to
clear the IDLE (one of python IDE distributed with the original
distribution) screen which is pretty easy but having to do
>>>import cls
>>> cls()
everytime is boring (2 lines of boredom!!) so what i want is to be
able to do just
>>>cls()
and nothing more or even less!! ;-) 

> 
> os.system("cls")  #for windows
> or
> os.system("clear")   #for unix
yeah i have used the 'os' module's system() method but that wasn't what i meant.

> Not the most advanced solution though.
;-) Thanx anyway mate. 

[snip]
-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: feature suggestion

2004-12-24 Thread John Machin
flexibal wrote:
> hi there.
>
> i didnt know if i should post it at python-dev or here, so i'll start
> here. i'd like to suggest a new language feature for python that
allows
> you to explicitly declare a variable.
>
> as we all know, just doing
> v = 5
> declares a new variable named 'v'...

Does it? Who other than yourself comprise the "we" to whom you refer?

> but we are people, and we do make
> typos... and it's very disturbing to find your program crashing after
> two weeks of operation, over a NameError... because a certain branch
in
> your code, that was previously never taken, had finally been taken.

Google for "code coverage".

>
> i've written several large-scale projects in python by now... i find
it
> excellent for automated testing and other infrastructural needs

You need to test that your testing equipment works.

> ... but
> mistyped variable-, function-, class-, and module- names been a PITA
> for me ever since i've started to use python.
>
> python is a scripting language after all, and should preserve its
> scripting nature. but adding features that help you verify your
python
> code should also be included.
>
> BASIC has the "OPTION EXPLICIT" feature that forces you to explicitly
> declare all variables, and i see no reason why python should have a
> similar mechanism.

Most Python developers would agree with what you wrote, but not with
what the context shows you meant. Have you ever considered reading what
you have written before submitting it for execution? Google for "desk
checking".

>
> either you start python with some commandline switch, or with a
> language construct, you should be able to turn on explicit variable
> declaration.
>
> first proposal:
[snip]
> second proposal:
> 
> syntactic verification, at parsing time. for example:
>
> my-prog.py:
> -
>
> ##decl x
> ##decl y, z
> x = 5
> y = 6
> z = 8
> a = 6
>
>
> when this program will be ran with the -strict option, like 6th line
> will generate a SyntaxError: name 'a' not explicitly declared.

and also SyntaxError: name 's' declared but never used

Your proposal needs some augmentation:

(1) Have an environment variable DWIM_LEVEL -- if the edit distance
(with variable substitution penalties depending on keyboard proximity)
between a "not declared" name and a "declared but not used" name is
within the requested tolerance, then Python should assume equivalence
and continue silently.

(2) Recursively, this should be applied to the environment variable
itself, lest one type (say) SWIM_LEVEL or DIM_LEVEL.

(3) Have an ALTERNATE_METHOD_NAME option to cater for known problems
like "center" vs "centre", "-ise" vs "-ize", etc
I look forward to the discussion of your PEP.

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


Re: Python Interactive Shell - outputting to stdout?

2004-12-24 Thread Avi Berkovich
Hey,
I can't make it work, I don't get any data from either stdout nor stderr.
If I send lines and then close the stdin pipe, I may get an exception 
message from several lines up.

I tried manually reading from the stdout pipe, but it just blocks and 
hangs no matter what I send over via the stdin pipe.

This behavior isn't presented by the command line interpreter by any chance.
Any suggestions?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-24 Thread Benji York
Andrew Dalke wrote:
Terry Reedy wrote:
As far as I know, apply(func, args) is exactly equivalent to func(*args).

After playing around a bit I did find one difference in
the errors they can create.

def count():
...   yield 1
... 

apply(f, count())
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: apply() arg 2 expected sequence, found generator
f(*count())
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: len() of unsized object
No question that they report different errors in the face of being given 
unsupported input.


That led me to the following

blah = Blah()
len(*blah)
6
apply(len, *blah)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: len() takes exactly one argument (6 given)
Is that difference a bug?
They do two different things.  I think you have a spurious * in the call 
to apply.  The apply above is equivalent to

>>> len('H', 'e', 'l', 'l', 'o', '!')
Which gives the same error:
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: len() takes exactly one argument (6 given)
If the * is removed, it works correctly:
>>> apply(len, blah)
6
--
Benji York
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Clearing the screen

2004-12-24 Thread Lars
Hi Iswor,

If I understand you correctly then your program is writing output to a
console/terminal window and you want to clear that window.
I don't know of any library methods for that, but you might just do:

os.system("cls")  #for windows
or
os.system("clear")   #for unix
Not the most advanced solution though.
---
Happy holidays! 
~Lars

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


Re: list Integer indexing dies??

2004-12-24 Thread Mike Meyer
Ishwor <[EMAIL PROTECTED]> writes:

> On Fri, 24 Dec 2004 05:44:50 -0600, Mike Meyer <[EMAIL PROTECTED]> wrote:
>> Ishwor <[EMAIL PROTECTED]> writes:
>> 
>> > On 23 Dec 2004 14:28:37 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>> > My experience as a learner here is that there should be some
>> > automagics & say like "okay you want to do indexing on integers (
>> > context dependent); i'll give you the index of 0th position in that
>> > integer" ???
>> 
>> Python doesn't do things automagically. The rules for pythonic
>> behavior include "Explicit is better than implicit" and "In the face
>> of ambiguity, refuse the tempation to guess." Both of those are
>> violated by automatic conversions and the like.
>> 
>
> Well *shrugs* that was just an opionion though a bad one from a
> beginner :-)... No hard feeling pythoner friends. ;-) and Merry
> Christmas to you all ;-)
> Then gingerbread is ready at
> http://www.mediatinker.com/blog/archives/008798.html 

I'm aware that it was an opinion from a beginner. I thought it was
worth pointing out *why* this was a bad opinion in Python. I certainly
didn't intend to offend or insult anyone by doing so.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gridbaglayout

2004-12-24 Thread Ishwor
heh? whats this gridbaglayout in Python-list?? Is this what my grandpa
calls "christmas fever"?? ;-)



On Fri, 24 Dec 2004 12:47:26 -0500, Sells, Fred <[EMAIL PROTECTED]> wrote:
> gridbag is a pain.  google for tablelayout which is easier (to me)
> 
> -Original Message-
> From: Diez B. Roggisch [mailto:[EMAIL PROTECTED]
> Sent: Monday, December 20, 2004 1:17 PM
> To: python-list@python.org
> Subject: Re: gridbaglayout
> 
> [EMAIL PROTECTED] wrote:
> 
> > Friends - I have tried to do abolute positioning using gridbaglayout,
> > but am having no success in jython. One book I have been referencing
> > says that it only works with JPanels. Could someone post a snippet of
> > code that works for a button? I am so close so just a hint would help.
> 
> Google for java-examples and translat to jython. Ist straight forward.
> --
> Regards,
> 
> Diez B. Roggisch
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE problem :-(

2004-12-24 Thread Ishwor
I don't know if this has been a problem with other people using IDLE
but when i press the home key then the cursor jumps to the beginning
of the line and not after the prompt. If google prints the right
indentation then here how i want the IDLE prompt to work ->

 |>>> |(r,b,g).__class__
 ^  ^
 ^  ^-> want cursor here instead.
cursor
goes
here

Any work around??
Thank you.
-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant way to cwd?

2004-12-24 Thread M.E.Farmer
Ignore my last post to much eggnog I guess. I must have parsed it to
quickly. 

M.E.Farmer

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


staying alive

2004-12-24 Thread rosen georgiev
well, hello
i'm trying to write a script that listens for HAL messages 
(http://www.freedesktop.org/wiki/Software_2fhal) on D-BUS 
(http://www.freedesktop.org/wiki/Software_2fdbus).
the problem i have is to keep the script alive. the way i do it now is with a 
call to gtk.main() after all the init is done - and it works perfectly. but i 
can't start the app if X isn't running or as another user.
so with what should i replace gtk.main()!?
i tryed (i agree it's pretty dum :)
while 1:
   time.sleep(1)
and it (surprice) does not work
i also tryed somethings with threads but with no luck.
in both cases the app is running but it does not reseive the messages - the 
handler functions do not get called

so, if anyone can help - please do :)
10Q

-
SMS известяване за получено писмо - http://promo.abv.bg/new_sms.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant way to cwd?

2004-12-24 Thread M.E.Farmer
Hello,
Seems you found os.chdir(), but you missed os.getcwd()
;)
M.E.Farmer

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


Clearing the screen

2004-12-24 Thread Ishwor
Hi i use IDLE to code Python in my machine. What i haven't been able
to do is call an in-built function called clear()/cls()/clr() because
it mightn't exist. so what i did is coded my own function called cls()
as such
>>> def cls():
for i in range(1,40):
print " ";

now that does the job very nicely and i get cleared screen but what i
really want to achieve it everytime i start IDLE, without importing
any module, i want to be able to do just cls() and be able to clear
the screen. Is that achievable? Does that have mean i have to tinker a
bit with in-builts??

Thank you.

-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


ioctl() help needed for video4linux

2004-12-24 Thread Kyler Laird
I want to know which input one of my V4L devices is using.  This is
done using the VIDIOC_G_INPUT ioctl.  I'm trying to figure out how
to do it in Python.

I found the pyv4l.
http://pyv4l.sourceforge.net/
It hasn't been updated in awhile.  It doesn't know about
VIDIOC_G_INPUT.  I tried creating it with this.
foo = VIDIOCGINPUT = video4linux._IOR('v', 38, 'i')
I was even able to get ioctl() to go with this.
i = struct.pack("i",0)
bar = fcntl.ioctl(fd, foo, i)
I don't get anything out of it though.

Any clues?

Thank you.

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


Re: Lambda going out of fashion

2004-12-24 Thread Mike Meyer
Nick Coghlan <[EMAIL PROTECTED]> writes:

> jfj wrote:
> Python 3.0 will be a case of "OK, let's take the things we learned
> were good and keep them, and throw away the things we realised were
> bad"
>
> Undoubtedly, the two languages will co-exist for quite some time.

Perl 6.0 is going to include even more drastic changes. It will also
include a Perl 5.x interpreter, and will have to be switched to 6.0
mode by a magic cookie of some kind in the source. Possibly Python 3.0
could do something similar. Use the same byte code engine, and a
compiler switch that enables the gotchas. Or maybe
"from __past__ import gotchas"

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-24 Thread Andrew Dalke
Terry Reedy wrote:
> As far as I know, apply(func, args) is exactly equivalent to func(*args).

After playing around a bit I did find one difference in
the errors they can create.

>>> def count():
...   yield 1
... 
>>> apply(f, count())
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: apply() arg 2 expected sequence, found generator
>>> f(*count())
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: len() of unsized object
>>> 

That led me to the following

>>> class Blah:
...   def __len__(self):
... return 10
...   def __getitem__(self, i):
... if i == 0: return "Hello!" 
... raise IndexError, i
... 
>>> blah = Blah()
>>> len(*blah)
6
>>> apply(len, *blah)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: len() takes exactly one argument (6 given)
>>>

Is that difference a bug?

Andrew
[EMAIL PROTECTED]

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


Re: Python To Send Emails Via Outlook Express

2004-12-24 Thread ian
Hey guys, I'm just thankful the answer has been found and hope this
helps someone else. To everyone (especially Lenard) that responded to
my request for help, thank you!!
Merry Christmas everyone!!!
God bless
Ian

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


Re: list Integer indexing dies??

2004-12-24 Thread Ishwor
On Fri, 24 Dec 2004 05:44:50 -0600, Mike Meyer <[EMAIL PROTECTED]> wrote:
> Ishwor <[EMAIL PROTECTED]> writes:
> 
> > On 23 Dec 2004 14:28:37 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> > My experience as a learner here is that there should be some
> > automagics & say like "okay you want to do indexing on integers (
> > context dependent); i'll give you the index of 0th position in that
> > integer" ???
> 
> Python doesn't do things automagically. The rules for pythonic
> behavior include "Explicit is better than implicit" and "In the face
> of ambiguity, refuse the tempation to guess." Both of those are
> violated by automatic conversions and the like.
> 

Well *shrugs* that was just an opionion though a bad one from a
beginner :-)... No hard feeling pythoner friends. ;-) and Merry
Christmas to you all ;-)
Then gingerbread is ready at
http://www.mediatinker.com/blog/archives/008798.html 
;-)

[snip]

-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables and modules

2004-12-24 Thread John Machin

[EMAIL PROTECTED] wrote:
> I have a newby type question on how global variables work between
> modules.
>
> I have a module test2.py that defines a global variable as well as
two
> functions to operate on that variable.  A script test1.py imports the
> three names and prints out values of the global between operations,
and
> the results aren't what I expected.
[snip]
> I am looking for a way to share data between modules.  Can
> you advise me on my error?

Yes. Your error is that you are looking at global variables as "a way
to share data between modules". The advice is "Don't do that". Limited
use of global variables whose values are updated is barely tolerable
within a single module that will be executed by a single thread of a
single process. Otherwise you can end up with monstrosities like
database "forms" applications with hundreds of globals. Google for
concepts like "modularity" and "information hiding". Then read about
OOP.

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


python-dev Summary for 2004-11-01 through 2004-11-15

2004-12-24 Thread Brett C.
python-dev Summary for 2004-11-01 through 2004-11-15

This is a summary of traffic on the `python-dev mailing list`_ from November 
01, 2004 through November 15, 2004.  It is intended to inform the wider Python 
community of on-going developments on the list.  To comment on anything 
mentioned here, just post to `comp.lang.python`_ (or email 
python-list@python.org which is a gateway to the newsgroup) with a subject line 
mentioning what you are discussing. All python-dev members are interested in 
seeing ideas discussed by the community, so don't hesitate to take a stance on 
something.  And if all of this really interests you then get involved and join 
`python-dev`_!

This is the fifty-second summary written by Brett Cannon (Happy Holidays).
To contact me, please send email to brett at python.org ; I do not have the 
time to keep up on comp.lang.python and thus do not always catch follow-ups 
posted there.

All summaries are archived at http://www.python.org/dev/summary/ .
Please note that this summary is written using reStructuredText_ which can be 
found at http://docutils.sf.net/rst.html .  Any unfamiliar punctuation is 
probably markup for reST_ (otherwise it is probably regular expression syntax 
or a typo =); you can safely ignore it, although I suggest learning reST; it's 
simple and is accepted for `PEP markup`_ and gives some perks for the HTML 
output.  Also, because of the wonders of programs that like to reformat text, I 
cannot guarantee you will be able to run the text version of this summary 
through Docutils_ as-is unless it is from the `original text file`_.

.. _PEP Markup: http://www.python.org/peps/pep-0012.html
The in-development version of the documentation for Python can be found at
http://www.python.org/dev/doc/devel/ and should be used when looking up any
documentation on new code; otherwise use the current documentation as found at
http://docs.python.org/ .  PEPs (Python Enhancement Proposals) are located at 
http://www.python.org/peps/ .  To view files in the Python CVS online, go to 
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ .  Reported bugs and 
suggested patches can be found at the SourceForge_ project page.

The `Python Software Foundation`_ is the non-profit organization that holds the 
intellectual property for Python.  It also tries to forward the development and 
use of Python.  But the PSF_ cannot do this without donations.  You can make a 
donation at http://python.org/psf/donations.html .  Every penny helps so even a 
small donation (you can donate through PayPal or by check) helps.

.. _python-dev: http://www.python.org/dev/
.. _SourceForge: http://sourceforge.net/tracker/?group_id=5470
.. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev
.. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python
.. _Docutils: http://docutils.sf.net/
.. _reST:
.. _reStructuredText: http://docutils.sf.net/rst.html
.. _PSF:
.. _Python Software Foundation: http://python.org/psf/
.. contents::
.. _last summary: http://www.python.org/dev/summary/2004-10-16_2004-10-31.html
.. _original text file: 
http://www.python.org/dev/summary/2004-11-01_2004-11-15.ht

=
Summary Announcements
=
I am hoping to be caught up with my summary backlog by the end of the month. 
Here is to hoping.

=
Summaries
=

2.4 released

`Python 2.4`_ has been released!  Read the `What's New`_ for 2.4 to see what 
the major changes are since 2.3 .

.. _Python 2.4: http://www.python.org/2.4/
.. _What's New: http://www.python.org/doc/2.4/whatsnew/whatsnew24.html
Contributed threads:
  - `TRUNK FROZEN for 2.4b2 release from UTC 3rd November (tomorrrow) 
`__
  - `RELEASED Python 2.4, beta 2 
`__
  - `TRUNK UNFROZEN 
`__

-
Code coverage of the regression tests
-
Walter DÃrwald has a code coverage tool that runs once a month on Python's 
regression test at http://coverage.livinglogic.de/ .  There was some issue with 
the 'trace' module having partially broken in 2.4 .  The coverage was then run 
using ``Lib/test/regrtest.py -T`` to get more accurate numbers.

Contributing threads:
  - `Code coverage tool updated 
`__


Garbage collecting weakref callbacks

Tim Peters discovered that in 2.4 if a weakref's callback is still reachable 
but the referent and weakref itself are unreachable (Tim's example had an 
instance that contained a weakref to itself) that the callback is not called 
during garbage collection.  This se

Extension with factory

2004-12-24 Thread CarlosP
Hi!

I'm writing a C/C++ extension to python. I need to add two python types
which will be implemented as C++ classes. One of the classes acts as
(besides other functions) a factory for the other. Specifically, one is
Package and the other Unit, the createUnit method of Package lets you
create Units which in turn cannot be created independently (I mean from
"outside" the Package). The python object structures are defined as:

typedef struct {
PyObject_HEAD
Package* package;
} CPackage

typedef struct {
PyObject_HEAD
Unit* cunit;
} CUnit

And the python types structures are:

static PyTypeObject CPackage_type = {

}

static PyTypeObject CUnit_type = {

}

So I'm providing a tp_new implementation for CPackage_type as usual.
But I'm not sure how to cope with creation of CUnits. A Unit instance
should be created by Package.createUnit in the C++ heap using the new
operator. This instance should be wrapped as a CUnit and returned from
CPackage_methods_createUnit.

How should I do that? If I provided a tp_new for CUnit_type and invoked
it from CPackage_methods_createUnit, the tp_new would take PyObjects as
args and I would not be able to pass it the Unit* returned by
Package.createUnit which should be asigned to CUnit->cunit to be
wrapped as explained before. In pseudo code:

PyObject* CPackage_methods_createUnit(PyObject *self, PyObject *args) {
char *name;
if (!PyArg_ParseTuple(args, "s", &name)) return NULL;
Unit *unit = ((CPackage*)self)->cpackage->createUnit(name);
return createCUnitFromUnit(unit);
}

Reformulating the question, how should I implement createCUnitFromUnit?
Thank you in advance.
Regards,
Carlos

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


Re: Newbie namespace question

2004-12-24 Thread Alex Martelli
Peter Hansen <[EMAIL PROTECTED]> wrote:

> I'm not sure what you think that does, but I don't
> think it does it.

QOTW +1 !!!


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


Re: Python To Send Emails Via Outlook Express

2004-12-24 Thread Steve Holden
Max M wrote:
Lenard Lindstrom wrote:
[EMAIL PROTECTED] writes:
[sixty or more lines, mostly code ...]
Looks good.
Lenard Lindstrom

Nice quoting
So what is this, some kind of competition? If you really though Lenard's 
quoting was a sin (since I took your remarks to be sardonic), how much 
more so was your gratuitous repetition thereof?

Far more pleasant to either a) ignore a gaff by a possibly 
less-experienced usenet correspondent than yourself, or b) point out the 
error without repeating it, as I hope I have done here.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


More elegant way to cwd?

2004-12-24 Thread Kamilche
Is there a more elegant way to change the working directory of Python
to the directory of the currently executing script, and add a folder
called 'Shared' to the Python search path?

This is what I have. It seems like it could be shorter, somehow.

# Switch Python to the current directory
import os, sys
pathname, scriptname = os.path.split(sys.argv[0])
pathname = os.path.abspath(pathname)
os.chdir(pathname)
s = os.path.realpath('..')
s = os.path.join(s, 'Shared')
sys.path.append(s)

Thanks for any enhancements you can suggest!

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


Re: Optional Static Typing

2004-12-24 Thread Scott David Daniels
Rahul wrote:
1.def gcd(a,b) expects (int,int)
I presume by this syntax you mean something like:
def gcd(a, b) expects (int, int):
if b > a:
a, b = b, a
while a > b > 0:
a, b = b, a % b
return a
Here the function is not enforcing type checking. The compiler should
only generate warning when someone passes something which is not an int
and should not generate an error.Maybe the person calling the function
knows what he is doing and wants to pass the unexpected type.
But if this is the case, why is it different from?:
def gcd(a, b): # expects (int, int)
return a * b
2.Another possibility is to let the function decide if the type is not
what it is expecting. Maybe the function recvs some kind of flag which
tells it that the type passed is not what it was expecting. So it can
throw an error if it is really critical.
Again, why make the test at all if you don't want to act on it?
 assert  aborts if it is checked at all, but with __debug__
defined as 1, it passes.  Perhaps you are proposing that expects be
used in that context.
3.In my post i am not stressing on adding 'expects' as keyword or
something. Only that type should not be enforced and 'expects' makes
this clear.
You need to explain why anyone would want to write expects at all.
If you are expecting the code generation to change, you'd better
enforce, rather than advise, unless you are defining points at which
to do code specialization on types.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional Static Typing - Haskell?

2004-12-24 Thread Alex Martelli
Donn Cave <[EMAIL PROTECTED]> wrote:

> Quoth [EMAIL PROTECTED] (Alex Martelli):
> ...
> | Haskell's a great language, but beware: its static typing is NOT
> | optional -- it's rigorous.  It can INFER types for you (just like, say,
> | boo), that's a different issue.  It also allows bounded genericity at
> | compile time (like, say, C++'s templates without the hassles), and
> | that's yet another (typeclasses are a great mechanism, btw).
> 
> He didn't dwell much on it, but there was some mention of type
> inference, kind of as though that could be taken for granted.
> I guess this would necessarily be much more limited in scope
> than what Haskell et al. do.

Assuming that by "he" you mean GvR, I think I saw that too, yes.  And
yes, a language and particularly a typesystem never designed to
facilitate inferencing are hard-to-impossible to retrofit with it in as
thorough a way as one that's designed around the idea.  (Conversely,
making a really modular system work with static typing and inferencing
is probably impossible; in practice, the type inferencer must examine
all code, or a rather copious summary of it... it can't really work
module by module in a nice, fully encapsulated way...).


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


Re: Python To Send Emails Via Outlook Express

2004-12-24 Thread Max M
Lenard Lindstrom wrote:
[EMAIL PROTECTED] writes:

Hi Lenard,
You just beat me to it.
Suprise, suprise, I discovered the answer myself this time.
I have modified the script to allow the attachment(s) to still be
passed as a string.
Some error checking is also done to verify the attachment file exists.
I have also modified it so it can be used for multiple email addresses.
Here is the updated working script ...
-
import os
from ctypes import *
FLAGS = c_ulong
LHANDLE = c_ulong
LPLHANDLE = POINTER(LHANDLE)
# Return codes
SUCCESS_SUCCESS = 0
# Recipient class
MAPI_ORIG = 0
MAPI_TO = 1
NULL = c_void_p(None)
class MapiRecipDesc(Structure):
_fields_ = [('ulReserved', c_ulong),
('ulRecipClass', c_ulong),
('lpszName', c_char_p),
('lpszAddress', c_char_p),
('ulEIDSize', c_ulong),
('lpEntryID', c_void_p),
]
lpMapiRecipDesc = POINTER(MapiRecipDesc)
class MapiFileDesc(Structure):
_fields_ = [('ulReserved', c_ulong),
('flFlags', c_ulong),
('nPosition', c_ulong),
('lpszPathName', c_char_p),
('lpszFileName', c_char_p),
('lpFileType', c_void_p),
]
lpMapiFileDesc = POINTER(MapiFileDesc)
class MapiMessage(Structure):
_fields_ = [('ulReserved', c_ulong),
('lpszSubject', c_char_p),
('lpszNoteText', c_char_p),
('lpszMessageType', c_char_p),
('lpszDateReceived', c_char_p),
('lpszConversationID', c_char_p),
('flFlags', FLAGS),
('lpOriginator', lpMapiRecipDesc), # ignored?
('nRecipCount', c_ulong),
('lpRecips', lpMapiRecipDesc),
('nFileCount', c_ulong),
('lpFiles', lpMapiFileDesc),
]
lpMapiMessage = POINTER(MapiMessage)
MAPI = windll.mapi32
MAPISendMail=MAPI.MAPISendMail
MAPISendMail.restype = c_ulong  # Error code
MAPISendMail.argtypes = (LHANDLE,   # lhSession
c_ulong,   # ulUIParam
lpMapiMessage, # lpMessage
FLAGS, # lpFlags
c_ulong,   # ulReserved
)
def SendMail(recipient, subject, body, attachfiles):
"""Post an e-mail message using Simple MAPI
recipient - string: address to send to (multiple address sperated
with a semicolin)
subject - string: subject header
body - string: message text
attach - string: files to attach (multiple attachments sperated
with a semicolin)
Example usage
import simplemapi
simplemapi.SendMail("[EMAIL PROTECTED];[EMAIL PROTECTED]","My
Subject","My message body","c:\attachment1.txt;c:\attchment2")
"""
# get list of file attachments
attach = []
AttachWork = attachfiles.split(';')
#verify the attachment file exists
for file in AttachWork:
if os.path.exists(file):
attach.append(file)
attach = map( os.path.abspath, attach )
nFileCount = len(attach)
if attach:
MapiFileDesc_A = MapiFileDesc * len(attach)
fda = MapiFileDesc_A()
for fd, fa in zip(fda, attach):
fd.ulReserved = 0
fd.flFlags = 0
fd.nPosition = -1
fd.lpszPathName = fa
fd.lpszFileName = None
fd.lpFileType = None
lpFiles = fda
else:
# No attachments
lpFiles = cast(NULL, lpMapiFileDesc) # Make NULL
# Get the number of recipients
RecipWork = recipient.split(';')
RecipCnt = len(RecipWork)
# Formulate the recipients
MapiRecipDesc_A = MapiRecipDesc * len(RecipWork)
rda = MapiRecipDesc_A()
for rd, ra in zip(rda, RecipWork):
rd.ulReserved = 0
rd.ulRecipClass = MAPI_TO
rd.lpszName = None
rd.lpszAddress = ra
rd.ulEIDSize = 0
rd.lpEntryID = None
recip = rda
# send the message
msg = MapiMessage(0, subject, body, None, None, None, 0,
cast(NULL, lpMapiRecipDesc), RecipCnt, recip,
nFileCount, lpFiles)
rc = MAPISendMail(0, 0, byref(msg), 0, 0)
if rc != SUCCESS_SUCCESS:
raise WindowsError, "MAPI error %i" % rc
---

Looks good.
Lenard Lindstrom
Nice quoting
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables and modules

2004-12-24 Thread Alex Martelli
Brian van den Broek <[EMAIL PROTECTED]> wrote:

> I'm quite fond of the
> 
> import really_long_module_name as rlmn
   ...
> I don't think the relevant section of Nutshell mentions this idiom. 
> However, I don't have my copy with me (seasonal travel, and all), so 
> apologies if my memory leads me astray.

Apologies accepted -- it's right on p. 117, at the first mention of the
import statement.  Maybe I'm not giving it enough prominence, though,
nor advice about how to use it...


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


Re: BASIC vs Python

2004-12-24 Thread Alan Gauld
On Fri, 24 Dec 2004 12:30:15 +, Alan Kennedy
<[EMAIL PROTECTED]> wrote:

> [Alan Gauld]
>  > I dunno. Here in the UK there was a small home computer called (I
>  > think) the Oric(*) 
> I'm afraid your memory fails you ...
> 
> The Oric-1 had a keyboard with *actual* keys, and came in two memory 
> 
> I think you're mixing up the Oric with the Jupiter Ace 

Seems to be, I plead old age :-)

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python To Send Emails Via Outlook Express

2004-12-24 Thread Lenard Lindstrom
[EMAIL PROTECTED] writes:

> Hi Lenard,
> You just beat me to it.
> Suprise, suprise, I discovered the answer myself this time.
> 
> I have modified the script to allow the attachment(s) to still be
> passed as a string.
> Some error checking is also done to verify the attachment file exists.
> 
> I have also modified it so it can be used for multiple email addresses.
> 
> Here is the updated working script ...
> -
> 
> import os
> from ctypes import *
> 
> FLAGS = c_ulong
> LHANDLE = c_ulong
> LPLHANDLE = POINTER(LHANDLE)
> 
> 
> # Return codes
> SUCCESS_SUCCESS = 0
> # Recipient class
> MAPI_ORIG = 0
> MAPI_TO = 1
> 
> 
> NULL = c_void_p(None)
> 
> 
> class MapiRecipDesc(Structure):
> _fields_ = [('ulReserved', c_ulong),
> ('ulRecipClass', c_ulong),
> ('lpszName', c_char_p),
> ('lpszAddress', c_char_p),
> ('ulEIDSize', c_ulong),
> ('lpEntryID', c_void_p),
> ]
> lpMapiRecipDesc = POINTER(MapiRecipDesc)
> 
> 
> class MapiFileDesc(Structure):
> _fields_ = [('ulReserved', c_ulong),
> ('flFlags', c_ulong),
> ('nPosition', c_ulong),
> ('lpszPathName', c_char_p),
> ('lpszFileName', c_char_p),
> ('lpFileType', c_void_p),
> ]
> lpMapiFileDesc = POINTER(MapiFileDesc)
> 
> 
> class MapiMessage(Structure):
> _fields_ = [('ulReserved', c_ulong),
> ('lpszSubject', c_char_p),
> ('lpszNoteText', c_char_p),
> ('lpszMessageType', c_char_p),
> ('lpszDateReceived', c_char_p),
> ('lpszConversationID', c_char_p),
> ('flFlags', FLAGS),
> ('lpOriginator', lpMapiRecipDesc), # ignored?
> ('nRecipCount', c_ulong),
> ('lpRecips', lpMapiRecipDesc),
> ('nFileCount', c_ulong),
> ('lpFiles', lpMapiFileDesc),
> ]
> lpMapiMessage = POINTER(MapiMessage)
> 
> 
> MAPI = windll.mapi32
> 
> 
> MAPISendMail=MAPI.MAPISendMail
> MAPISendMail.restype = c_ulong  # Error code
> MAPISendMail.argtypes = (LHANDLE,   # lhSession
> c_ulong,   # ulUIParam
> lpMapiMessage, # lpMessage
> FLAGS, # lpFlags
> c_ulong,   # ulReserved
> )
> 
> 
> def SendMail(recipient, subject, body, attachfiles):
> """Post an e-mail message using Simple MAPI
> 
> 
> recipient - string: address to send to (multiple address sperated
> with a semicolin)
> subject - string: subject header
> body - string: message text
> attach - string: files to attach (multiple attachments sperated
> with a semicolin)
> 
> Example usage
> import simplemapi
> 
> simplemapi.SendMail("[EMAIL PROTECTED];[EMAIL PROTECTED]","My
> Subject","My message body","c:\attachment1.txt;c:\attchment2")
> 
> 
> """
> 
> # get list of file attachments
> attach = []
> AttachWork = attachfiles.split(';')
> 
> #verify the attachment file exists
> for file in AttachWork:
> if os.path.exists(file):
> attach.append(file)
> 
> 
> attach = map( os.path.abspath, attach )
> nFileCount = len(attach)
> 
> if attach:
> MapiFileDesc_A = MapiFileDesc * len(attach)
> fda = MapiFileDesc_A()
> for fd, fa in zip(fda, attach):
> fd.ulReserved = 0
> fd.flFlags = 0
> fd.nPosition = -1
> fd.lpszPathName = fa
> fd.lpszFileName = None
> fd.lpFileType = None
> lpFiles = fda
> else:
> # No attachments
> lpFiles = cast(NULL, lpMapiFileDesc) # Make NULL
> 
> # Get the number of recipients
> RecipWork = recipient.split(';')
> RecipCnt = len(RecipWork)
> 
> # Formulate the recipients
> MapiRecipDesc_A = MapiRecipDesc * len(RecipWork)
> rda = MapiRecipDesc_A()
> for rd, ra in zip(rda, RecipWork):
> rd.ulReserved = 0
> rd.ulRecipClass = MAPI_TO
> rd.lpszName = None
> rd.lpszAddress = ra
> rd.ulEIDSize = 0
> rd.lpEntryID = None
> recip = rda
> 
> # send the message
> msg = MapiMessage(0, subject, body, None, None, None, 0,
> cast(NULL, lpMapiRecipDesc), RecipCnt, recip,
> nFileCount, lpFiles)
> 
> 
> rc = MAPISendMail(0, 0, byref(msg), 0, 0)
> if rc != SUCCESS_SUCCESS:
> raise WindowsError, "MAPI error %i" % rc
> ---

Looks good.

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


Re: Execute code after death of all child processes

2004-12-24 Thread Terry Reedy

"Markus Franz" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

I am a little puzzled about your variable declaration and use:

> import sys, os, time
> texts = ['this is text1', 'this is text 2']

You don't seem to use 'texts',

> for current_text in env_sources[0:]:

or define 'env_sources',

> pid = os.fork()
> if pid == 0:
> time.sleep(2)
> print current_text
> break

so I don't see how this could run (even with indents inserted back).  What 
am I missing?

Terry J. Reedy 



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


RE: gridbaglayout

2004-12-24 Thread Sells, Fred
gridbag is a pain.  google for tablelayout which is easier (to me)

-Original Message-
From: Diez B. Roggisch [mailto:[EMAIL PROTECTED]
Sent: Monday, December 20, 2004 1:17 PM
To: python-list@python.org
Subject: Re: gridbaglayout


[EMAIL PROTECTED] wrote:

> Friends - I have tried to do abolute positioning using gridbaglayout,
> but am having no success in jython. One book I have been referencing
> says that it only works with JPanels. Could someone post a snippet of
> code that works for a button? I am so close so just a hint would help.

Google for java-examples and translat to jython. Ist straight forward.
-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list

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


Re: feature suggestion

2004-12-24 Thread moma
Do not miss the discussion topic/thread:
  "Optional Static Typing"  (from 12/23/2004)
The referral article is very interesting, even for a newbie.
Introduction of (optional) types will "legitimate" the Python language 
even more, while it keeps the fast scripting nature unspoilt.


flexibal wrote:
hi there.
i didnt know if i should post it at python-dev or here, so i'll start
here. i'd like to suggest a new language feature for python that allows
you to explicitly declare a variable.
as we all know, just doing
v = 5
declares a new variable named 'v'... but we are people, and we do make
typos... and it's very disturbing to find your program crashing after
two weeks of operation, over a NameError... because a certain branch in
your code, that was previously never taken, had finally been taken.
i've written several large-scale projects in python by now... i find it
excellent for automated testing and other infrastructural needs... but
mistyped variable-, function-, class-, and module- names been a PITA
for me ever since i've started to use python.
python is a scripting language after all, and should preserve its
scripting nature. but adding features that help you verify your python
code should also be included.
BASIC has the "OPTION EXPLICIT" feature that forces you to explicitly
declare all variables, and i see no reason why python should have a
similar mechanism.
either you start python with some commandline switch, or with a
language construct, you should be able to turn on explicit variable
declaration.
first proposal:
===
import sys
sys.is_strict = True
decl("x")
x = 5
y = 6
StrictError: name 'y' not explicitly declared
the syntactic format can be debated, of course. here 'decl' is used as
a built-in function that adds the name 'x' to a list of
"explicitly-declared-variables", and when setattr is called, it makes
sure the variable's name is within this list.
this is also fit for dynamic code, but suffers from still having to
execute the code before it is enforced. problems will remain in things
like:
decl("x")
x = 5
if x == 6:
y = 7
second proposal:

syntactic verification, at parsing time. for example:
my-prog.py:
-
##decl x
##decl y, z
x = 5
y = 6
z = 8
a = 6
when this program will be ran with the -strict option, like 6th line
will generate a SyntaxError: name 'a' not explicitly declared.
this strategy can verify all sorts of dead-branches, as demonstrated
above, but is not fit for dynamic code.
---
personally, i like the second proposal more, because it adds no new
language constructs, only a new commandline switch and meta-comments,
and is totally backwards compatible.


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


Re: Optional Static Typing - Haskell?

2004-12-24 Thread Donn Cave
Quoth [EMAIL PROTECTED] (Alex Martelli):
...
| Haskell's a great language, but beware: its static typing is NOT
| optional -- it's rigorous.  It can INFER types for you (just like, say,
| boo), that's a different issue.  It also allows bounded genericity at
| compile time (like, say, C++'s templates without the hassles), and
| that's yet another (typeclasses are a great mechanism, btw).

He didn't dwell much on it, but there was some mention of type
inference, kind of as though that could be taken for granted.
I guess this would necessarily be much more limited in scope
than what Haskell et al. do.

Donn Cave, [EMAIL PROTECTED]


---== Posted via Newsfeed.Com - Uncensored Usenet News ==--
   http://www.newsfeed.com   The #1 Newsgroup Service in the World!
-= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =-
-- 
http://mail.python.org/mailman/listinfo/python-list


Out of Office AutoReply: Mail Delivery (failure david.bate@slcc.edu)

2004-12-24 Thread David Bate
Title: Out of Office AutoReply: Mail Delivery (failure [EMAIL PROTECTED])






I will be out of the office starting November Dec. 21st  and will return on Jan 5th.  



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

Re: odbc script

2004-12-24 Thread Benji York
Michele Petrazzo wrote:
Of course, if you want to help me to make it db-api 2 compatible, you
are welcome!
Unfortunately I don't have much time to volunteer, but when you embark 
on the road to DB API 2.0 compliance I have a fairly extensive test 
suite you can have.
--
Benji York
--
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables and modules

2004-12-24 Thread Brian van den Broek
Alex Martelli said unto the world upon 2004-12-24 03:23:
<[EMAIL PROTECTED]> wrote:

If you really must, consider using a container object.  The most
suitable container object for these tasks is often a module.  I.e.,
code, in test1:
import test2
and then refer to test2.glbl throughout.  I.e., forget 'from', use
'import'.
As I wrote in Python in a Nutshell, p. 120, last paragraph before
"Module Loading":
"""
In general, the import statement is a better choice than the from
statement.  I suggest you think of the from statement [...] as [a]
convenience meant only for occasional use in interactive Python
sessions.  If you always access module M with the statement import M,
and always access M's attributes with explicit syntax M.A, your code
will be slightly less concise, but far clearer and more readable.
"""
I don't know how I could have put this advice more strongly or more
directly (I continue with explanations about the cases in which 'from'
is instead appropriate, chiefly getting single modules from packages).
Giving strong direct advice, rather than just reference info, in a book
of the "in a Nutshell" series, is not common, but I do it quite a bit;
after all, "how does Python work exactly", e.g. the fact that 'from X
import Y' is almost the same as 'Y = X.Y', is pretty simple to explain,
and so takes up little space -- OTOH, the consequences of this, such as
"thus, generally, don't use 'from', use 'import'" may not be obvious to
readers, so I point them out directly.
Of course, that doesn't help much if people don't _read_ it;-).
Alex
Hi all,
I'm quite fond of the
import really_long_module_name as rlmn
idiom. I use it all the time for some utility modules that I have 
developed, where I like the module to have a descriptive name, but I 
don't feel like burning line-length on retyping it all the time. If you 
adopt a standard set of abbreviations ('fu' for 'fileutils', etc.) you 
get less typing while preserving the advantages of clarity and 
readability that the unmodified import provides. (And, of course, both 
protect your namespace from the clobbering that will eventually arise 
with use of from.)

I don't think the relevant section of Nutshell mentions this idiom. 
However, I don't have my copy with me (seasonal travel, and all), so 
apologies if my memory leads me astray.

For what its worth, I'm glad for the advice in Nutshell. It transforms 
the book from a useful thing for those who like dead-tree references 
into a text one can actually read (as opposed to merely consult quickly).

Best to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: odbc script

2004-12-24 Thread Michele Petrazzo
Steve Holden wrote:
you might want to look at www.egenix.com and think 
about installing the mxODBC module, which I have used with very good 
results.

regards
 Steve
If you want, I have created realpyodbc, that is a class for create an
interface between python and odbc with ctypes's help . For now it is not
db-api 2 compatible, but I use it in production and have no problems.
You can try it here:
www.unipex.it/vario/RealPyOdbc.py
Of course, if you want to help me to make it db-api 2 compatible, you
are welcome!
Michele
--
http://mail.python.org/mailman/listinfo/python-list


Re: Koolaid (was Re: Optional Static Typing)

2004-12-24 Thread Tim Jarman
In article <[EMAIL PROTECTED]>,
 Peter Hansen <[EMAIL PROTECTED]> wrote:

> 
> P.S.: The ironic thing about all this is that it was
> actually something called "Flavor Aid", made by a
> company called Jel Sert (http://www.jelsert.com),
> and not Kool-Aid at all.  What would be even funnier
> is if the expression doesn't derive from the Jonestown
> suicides and I've always just assumed it did...

I always thought it was a reference to the Illuminatus! trilogy 
(http://tinyurl.com/5uhrz) by Robert Shea & Robert Anton Wilson. At 
least, I'm pretty sure that's where I came across it. Maybe they were 
referencing Jamestown?

Now if only I could think of a connection between this and Python...

-- 
Remove luncheon meat to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows XP - cron or scheduler for Python?

2004-12-24 Thread Michele Petrazzo
Emilio wrote:
I have gone through the pain of trying to use those commands and use
other available cron clients for Windows to find they are expensive, or
have bugs and are not stable. So I wrote a very simple yet powerful
script that handles all the basic functionality of Cron. It has been
stable and used in production for about a year. The source code is in
Python and you can read it, it is a simple page. I have also created a
version for Windows with an installer that doesn't even require Python
installed in the target machine.
You can find the project here:
http://sourceforge.net/projects/pycron
Emilio.
I find your project useful, but it's not a full "operation planned"
replacement. (I hope I have translate correctly from Italian "Operazioni
pianificate", you'll find it into the control panel).
It's mean that lack the service function. For example, if the pc is
lighted, but no logged-in, pycron don't work!
Why don't add this function? I think that is simple to make with py2exe
help.
If you want I can create a simple GUI that can help the users that have
no knowledge whit contrab sintax.
Michele
--
http://mail.python.org/mailman/listinfo/python-list


Re: odbc for solid

2004-12-24 Thread Michele Petrazzo
flupke wrote:
Hi,
at work we use a solid database and i need to develop an application 
that accesses it. Problem is the drivers: i only have some dll's lying 
around and jar.
On winsdows i could get by by using ODBC and the dll's to access the 
solid database but i want to eventually run it on a linux server.
Solid doesn't seem to have a driver specifically for Linux so i'm stuck 
here. Is there any way i can still use Linux and have access to solid?
Maybe i need to revert to jython so i can use the jar?

Thanks for any info
Benedict
I have create RealPyOdbc, that is a class made in pure python that
create a simple interface from python to odbc with the use of ctypes.
Of course, it work on every system where ctypes work (win, linux, mac).
It has no db-api 2.0 compatible (my free time is very low), but the work
for make it compatible is very low.
You can see it here:
www.unipex.it/vario/RealPyOdbc.py
In the future, when I'll finish it (make the db-api 2), I'll open a
sf.net project.
I hope it will help you.
Bye,
Michele Petrazzo
--
http://mail.python.org/mailman/listinfo/python-list


Re: character set gobbledy-gook ascii translation ...

2004-12-24 Thread Jeff Epler
>>> email.Header.decode_header("=?us-ascii?Q?Re=3A=20=5Bosg=2Duser=5D=20Culling=20problem?=")
[('Re: [osg-user] Culling problem', 'us-ascii')]
>>> email.Header.decode_header("=?gb2312?B?cXVlc3Rpb24gYWJvdXQgbG9hZGluZyBmbHQgbGFyZ2UgdGVycmFpbiA=?=")
[('question about loading flt large terrain ', 'gb2312')]
>>> help(email.Header.decode_header)
Help on function decode_header:

decode_header(header)
Decode a message header value without converting charset.

Returns a list of (decoded_string, charset) pairs containing each of
the decoded parts of the header.  Charset is None for non-encoded
parts of the header, otherwise a lower-case string containing the
name of the character set specified in the encoded string.

An email.Errors.HeaderParseError may be raised when certain decoding
error occurs (e.g. a base64 decoding exception).

Jeff


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

Re: editing XML via DOM

2004-12-24 Thread Uche Ogbuji

jaco wrote:
> Hi,
>
> I'm new to Python and XML but still I want to create something that
> includes creating and editing XML using Python.
>
> Now I'm looking for a little example program that does (some of) this
to
> set me on my way.
>
> Is there something like this available or can somebody give me some
> example lines that creates and saves some XML data?

Start with:

http://www.xml.com/pub/a/2002/11/13/py-xml.html

then see:

http://www.xml.com/pub/a/2003/10/15/py-xml.html

Overall, there is a lot on DOM throughout the series:

http://www.xml.com/pub/at/24


--
Uche OgbujiFourthought, Inc.
http://uche.ogbuji.nethttp://4Suite.orghttp://fourthought.com
Use CSS to display XML -
http://www.ibm.com/developerworks/edu/x-dw-x-xmlcss-i.html
Full XML Indexes with Gnosis -
http://www.xml.com/pub/a/2004/12/08/py-xml.html
Be humble, not imperial (in design) -
http://www.adtmag.com/article.asp?id=10286UBL 1.0 -
http://www-106.ibm.com/developerworks/xml/library/x-think28.html
Use Universal Feed Parser to tame RSS -
http://www.ibm.com/developerworks/xml/library/x-tipufp.html
Default and error handling in XSLT lookup tables -
http://www.ibm.com/developerworks/xml/library/x-tiplook.html
A survey of XML standards -
http://www-106.ibm.com/developerworks/xml/library/x-stand4/
The State of Python-XML in 2004 -
http://www.xml.com/pub/a/2004/10/13/py-xml.html

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


Re: Optional Static Typing

2004-12-24 Thread Michael Sparks
Rocco Moretti wrote:
...
> Is there a group of people for whom static typing truly helps? 

Yes. Python doesn't at present compile down to a binary executable. (Py2exe
don't really count since that's "just" tacking on a VM on the side (he says
dimissively regarding something he thinks is cool :) )

The closest I can get to this at present is pyrex - which essentially
performs a translation from a very python like language to C, which you
then compile, and if you do things right can produce standalone modules.
Type declarations there are optional, and if omitted falls back to a python
object. If they are included however, you can gain performance boosts for
certain kinds of work. (Most often though you're simply interfacing to C
code.)

ie the groups that could benefit are those that currently go to C/C++
extensions for performance boosts. (and of course those who just want
binary executables :) (In the absence of Starkiller being released that
is...)

Regards,


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


Re: FutureWarning

2004-12-24 Thread Peter Hansen
Egor Bolonev wrote:
=
C:\Documents and Settings\┼уюЁ\My  
Documents\Scripts\octopus_eye\1\oct_eye_db.py:
213: FutureWarning: hex()/oct() of negative int will return a signed  
string in P
ython 2.4 and up
  if hex(binascii.crc32(data))[0] == '-':
=
hex() will return numbers like -0xa1?
Python 2.4 is out already, so it's easy to check:
c:\>python
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> hex(-55)
'-0x37'
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional Static Typing

2004-12-24 Thread Nick Coghlan
Mike Meyer wrote:
Which raises what, to me, is the central question. If we have optional
static typing, can I get a performance enhancement out of it? If not,
why bother?
I had some thoughts along the same lines, so I dug up PEP 246 and looked at how 
it could be enhanced to potentially support compile time code optimisation 
through static type declarations.

The write up is here:
http://boredomandlaziness.skystorm.net/2004/12/type-checking-in-python.html
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables and modules

2004-12-24 Thread dkeeney

Thank you to both of you for your assistance.

Using the qualified 'test2.glbl' form of the variable name gives the
result I need.  The concepts of binding and rebinding, as programming
concerns, are new to me;  I will have to study that further.
Thank you again, and Merry Christmas.

David

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


Re: How about "pure virtual methods"?

2004-12-24 Thread Steve Holden
Alex Martelli wrote:
[...]
Sorry for the toy-ness of the
example, but I don't want to post for hundreds of lines.
[...]
Can we take it this is some kind of early New Year's resolution?
happy-christmas-ly y'rs  - steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating Image Maps

2004-12-24 Thread Steve Holden
Aaron wrote:
I know this is a thing used primarily on websites..but since python can do
anything ;)
I'm trying to make a clickable image map for my wxPython program.
Basically, I know how to organize the images into one large image in a
panel, but how do I make the individual pieces clickable like webpage
links(in wxPython)? The goal is to add an event handler that displays the
image piece in a different panel, along with attributes. Which I could do
if only I could make the pieces clickable
Any ideas?
Also, if you have any hard to find links on the general area I'm talking
about, I'd like to learn as much as possible.
Basically, your approach can be completely different under wxPython - 
you can use a single image, and then query the mouse click events to 
determine which location (and therefore which portion of the image) was 
clicked.

You *could* use separate images as well, in which case you would need to 
provide callback functions to be called for clicks on the various 
sub-portions.

Take a look at the docs for wxEvent, and see if that leads you to 
something you can understand.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


character set gobbledy-gook ascii translation ...

2004-12-24 Thread Darran Edmundson
I'm parsing a file with the mailbox and email modules and
come across subject headers like:
   =?us-ascii?Q?Re=3A=20=5Bosg=2Duser=5D=20Culling=20problem?=
and
   =?gb2312?B?cXVlc3Rpb24gYWJvdXQgbG9hZGluZyBmbHQgbGFyZ2UgdGVycmFpbiA=?=
I've looked at the Charset class but can't figure out how to use it to
convert the above strings to a human readable form.  Generally, I 
imagine that
there is no guarantee that an encoded string can be rendered meaningfully
in ASCII - but these are posts to an English language mai list so it should
be possible for this restricted case.

I can guess the translation in the first example above but I'm
hoping there is a Python module that'll do it for me.
Any help is much appreciated.
Cheers,
Darran.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple Inheritance __slots__ problem

2004-12-24 Thread Alex Martelli
Nitin Shukla <[EMAIL PROTECTED]> wrote:

> Hello,
> 
> Can anyone tell why am I getting this error and how to work around this
> problem.
> 
> >>> class Klass(object):
> ...   __slots__ = ( 'x' )
> ...
> >>> class Klass1(object):
> ...   __slots__ = ( 'y' )
> ...
> >>> class Klass(Klass, Klass1):
> ...   __slots__ = ( 'z' )
> ...
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: multiple bases have instance lay-out conflict

You're getting this error because there is no way to merge the layout of
those slots.

> I need to define slots in these classes and also need to inherit them in
> Derived class.

You never NEED to define slots anywhere: it's just a memory
optimization, that's all there is to it -- you're saving the size of a
dict per instance, a few tens of bytes per instance.  Just remove the
slots all around: how many millions of instances of these classes do you
have alive at the same time?  Identify the leaf class which has the many
millions of instances and reinstate slots there, only, if you really
truly can't spare the RAM.


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


RE: FutureWarning

2004-12-24 Thread Batista, Facundo
Title: RE: FutureWarning





[Egor Bolonev]


#- =
#- C:\Documents and Settings\+уюЁ\My 
#- Documents\Scripts\octopus_eye\1\oct_eye_db.py:
#- 213: FutureWarning: hex()/oct() of negative int will return
#- a signed 
#- string in P
#- ython 2.4 and up
#-    if hex(binascii.crc32(data))[0] == '-':
#- =
#- hex() will return numbers like -0xa1?



Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
...
>>> hex(-3)
'-0x3'
>>> 


.   Facundo


  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA.


La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje.

Muchas Gracias.



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

Re: Python and Delphi

2004-12-24 Thread Jarek Zgoda
Kristofer Carlson wrote:
I'm curious about the long term trends chart on the TIOBE Programming 
Community Index chart at http://www.tiobe.com/tpci.htm.  It shows the 
prevalence of Delphi and Python have tracked roughly equivalent usage paths 
for some years now.  Does anyone know why, or is this just an interesting 
but insignificant anomaly?
I tend to accept this as coincidence, not an anomaly[1].
[1] If we call something "anomaly", we should also define "norm" for 
purpose of comparison.

--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional Static Typing - Haskell?

2004-12-24 Thread Alex Martelli
Neal D. Becker <[EMAIL PROTECTED]> wrote:

> I've just started learning about Haskell.  I suggest looking at this for an
> example.
> 
> A good intro: http://www.haskell.org/tutorial

Haskell's a great language, but beware: its static typing is NOT
optional -- it's rigorous.  It can INFER types for you (just like, say,
boo), that's a different issue.  It also allows bounded genericity at
compile time (like, say, C++'s templates without the hassles), and
that's yet another (typeclasses are a great mechanism, btw).

Languages with really optional static typing can be found; I think the
premier example is still Dylan -- a kind of commonlisp without infix
notation, unfortunately very out of fashion nowadays but still available
(some good books, too).

I love the explanations of Van Roy and Haridi, p. 104-106 of their book,
though I may or may not agree with their conclusions (which are
basically that the intrinsic difference is tiny -- they point to Oz and
Alice as interoperable languages without and with static typing,
respectively), all the points they make are good.  Most importantly, I
believe, the way dynamic typing allows real modularity (harder with
static typing, since type discipline must be enforced across module
boundaries), and "exploratory computing in a computation model that
integrates several programming paradigms".

"Dynamic typing is recommended", they conclude, "when programs must be
as flexible as possible".  I recommend reading the Agile Manifesto to
understand why maximal flexibility is crucial in most real-world
application programming -- and therefore why, in said real world rather
than in the more academic circles Dr. Van Roy and Dr. Hadidi move in,
dynamic typing is generally preferable, and not such a tiny issue as
they make the difference to be.  Still, they at least show more
awareness of the issues, in devoting 3 excellent pages of discussion
about it, pros and cons, than almost any other book I've seen -- most
books have clearly delineated and preformed precedence one way or the
other, so the discussion is rarely as balanced as that;).


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


FutureWarning

2004-12-24 Thread Egor Bolonev
=
C:\Documents and Settings\┼уюЁ\My  
Documents\Scripts\octopus_eye\1\oct_eye_db.py:
213: FutureWarning: hex()/oct() of negative int will return a signed  
string in P
ython 2.4 and up
  if hex(binascii.crc32(data))[0] == '-':
=
hex() will return numbers like -0xa1?
--
http://mail.python.org/mailman/listinfo/python-list


Re: feature suggestion

2004-12-24 Thread Scott David Daniels
flexibal wrote:
hi there.
i didnt know if i should post it at python-dev or here, so i'll start
here. 
Good choice.  Python-dev is not a location for you to propose work for
other people to do for you.
BASIC has the "OPTION EXPLICIT" feature that forces you to explicitly
declare all variables, and i see no reason why python should have a
similar mechanism.
What you are looking for is "pychecker" -- use google and find that;
you will be able to find many of the code problems you talk about
here.
syntactic verification, at parsing time. for example:
my-prog.py:
-
##decl x
##decl y, z
x = 5
y = 6
z = 8
a = 6  ### causes and error
This is _not_ a syntax error, syntax can be checked locally, without
memory.  "a = 6" is not a syntax error because you can tell exactly
valid what form the statement has, and the form of every expression
in the statement.  "a = 6 5" _is_ a syntax error; there is no way to
interpret "6 6" as an expression, and there is no way to interpret 
" 6" as a statement.  So, even if your proposal were to
be implemented, it would probably be an "access to undeclared
identifier" error.

--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


RE: feature suggestion

2004-12-24 Thread Jimmy Retzlaff
flexibal wrote:
...
> as we all know, just doing
> v = 5
> declares a new variable named 'v'... but we are people, and we do make
> typos... and it's very disturbing to find your program crashing after
> two weeks of operation, over a NameError... because a certain branch
in
> your code, that was previously never taken, had finally been taken.
...

PyChecker (http://pychecker.sourceforge.net/) will help you spot this
kind of thing. For example consider typo.py:

def f():
x = 1
y = 1
if 0 == 1:
print a
else:
print x+y

When you run PyChecker on typo.py it will issue the following warning:

typo.py:5: No global (a) found

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


Re: Optional Static Typing

2004-12-24 Thread Rahul
Hi.
Well i am a newbie to python and maybe not qualified enough to make a
comment on proposals to changes in python. My previous programming
experience has been in Java and C. So maybe you will forgive me if i
make any outlandish comments.

But anyway here goes:

I think instead what should be done is:

1.def gcd(a,b) expects (int,int)

Here the function is not enforcing type checking. The compiler should
only generate warning when someone passes something which is not an int
and should not generate an error.Maybe the person calling the function
knows what he is doing and wants to pass the unexpected type.

2.Another possibility is to let the function decide if the type is not
what it is expecting. Maybe the function recvs some kind of flag which
tells it that the type passed is not what it was expecting. So it can
throw an error if it is really critical.

3.In my post i am not stressing on adding 'expects' as keyword or
something. Only that type should not be enforced and 'expects' makes
this clear.

Rahul Garg

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


Re: Unicode entries on sys.path

2004-12-24 Thread Just
In article <[EMAIL PROTECTED]>,
 vincent wehren <[EMAIL PROTECTED]> wrote:

> Just wrote:
> > In article <[EMAIL PROTECTED]>,
> >  "Martin v. Lowis" <[EMAIL PROTECTED]> wrote:
> > 
> > 
> >>>Hm, maybe more a windows question than a python question...
> >>
> >>The real question here is: why does Python not support arbitrary
> >>Unicode strings on sys.path? It could, in principle, atleast on
> >>Windows NT+ (and also on OSX). Patches are welcome.
> > 
> > 
> > Works for me on OSX 10.3.6, as it should: prior to using the sys.path 
> > entry, a unicode string is encoded with Py_FileSystemDefaultEncoding. 
> 
> For this conversion "mbcs" will be used on Windows machines, implying 
> that such conversions are made using the current system Ansi codepage.
> (As a matter of interest: What is this on OSX?).

UTF-8.

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


RE: feature suggestion

2004-12-24 Thread Batista, Facundo
Title: RE: feature suggestion





[flexibal]


#- we do make
#- typos... and it's very disturbing to find your program crashing after
#- two weeks of operation, over a NameError... because a 
#- certain branch in
#- your code, that was previously never taken, had finally been taken.
#- 
#- i've written several large-scale projects in python by 
#- now... i find it
#- excellent for automated testing and other infrastructural 
#- needs... but
#- mistyped variable-, function-, class-, and module- names been a PITA
#- for me ever since i've started to use python.


All the paths in your code should be tested by unittest *before* putting he software in production.


Actually, they should be tested *before* writing the code itself.


I'm a big -1 on including static definitions to prevent errors. The only advantage I see to them is to speed enhancements (a la Pyrex).

.   Facundo


  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA.


La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje.

Muchas Gracias.



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

Re: Koolaid (was Re: Optional Static Typing)

2004-12-24 Thread Scott David Daniels
Tim Churches wrote:
Peter Hansen <[EMAIL PROTECTED]> wrote:
I always thought the connotation was more that those who
"drank the Kool-Aid" were unthinking drones, following what
others told them to do.
I thought it was an allusion to "The Electric Kool-Aid Acid test" by Tom Wolfe - see 
http://en.wikipedia.org/wiki/The_Electric_Kool_Aid_Acid_Test
I am pretty sure that it was a Jonestown reference.  I was living in
Menlo Park, CA around the time of Jonestown, and "drank the Kool-Aid"
came into coin as a (shocking at the time) reference after Jonestown,
and I knew a number of people who hung out at Keysey's place and a
few "on the bus" types -- none of them ever used the "drank the Kool-
Aid" phrase before Jonestown to my knowledge.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Koolaid (was Re: Optional Static Typing)

2004-12-24 Thread Robert Kern
Tim Churches wrote:
Peter Hansen <[EMAIL PROTECTED]> wrote:
John Roth wrote:
"Rocco Moretti" <[EMAIL PROTECTED]> wrote:
The question is, should Guido state "TDD is the one true way to 
program in Python.", or should concessions be made in the language 
design for those who don't "drink the TDD Kool-aide".
Neither one. I hope you didn't mean  that people
who advocate TDD are suicidal fanatics, because
that's exactly what "drink the  kool-aid" means.
I always thought the connotation was more that those who
"drank the Kool-Aid" were unthinking drones, following what
others told them to do.

I thought it was an allusion to "The Electric Kool-Aid Acid test" by Tom Wolfe - see 
http://en.wikipedia.org/wiki/The_Electric_Kool_Aid_Acid_Test
First Google hit for "drank the Kool-aid":
http://www.wordspy.com/words/drinktheKool-Aid.asp
"""
Notes:
This phrase comes from the 1978 "Jonestown massacre" in which members of 
the Peoples Temple cult committed suicide by drinking cyanide-laced 
Kool-Aid (although some say the drink of choice was actually Flav-R-Aid).
"""

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


feature suggestion

2004-12-24 Thread flexibal
hi there.

i didnt know if i should post it at python-dev or here, so i'll start
here. i'd like to suggest a new language feature for python that allows
you to explicitly declare a variable.

as we all know, just doing
v = 5
declares a new variable named 'v'... but we are people, and we do make
typos... and it's very disturbing to find your program crashing after
two weeks of operation, over a NameError... because a certain branch in
your code, that was previously never taken, had finally been taken.

i've written several large-scale projects in python by now... i find it
excellent for automated testing and other infrastructural needs... but
mistyped variable-, function-, class-, and module- names been a PITA
for me ever since i've started to use python.

python is a scripting language after all, and should preserve its
scripting nature. but adding features that help you verify your python
code should also be included.

BASIC has the "OPTION EXPLICIT" feature that forces you to explicitly
declare all variables, and i see no reason why python should have a
similar mechanism.

either you start python with some commandline switch, or with a
language construct, you should be able to turn on explicit variable
declaration.

first proposal:
===
>>> import sys
>>> sys.is_strict = True
>>> decl("x")
>>> x = 5
>>> y = 6
StrictError: name 'y' not explicitly declared

the syntactic format can be debated, of course. here 'decl' is used as
a built-in function that adds the name 'x' to a list of
"explicitly-declared-variables", and when setattr is called, it makes
sure the variable's name is within this list.

this is also fit for dynamic code, but suffers from still having to
execute the code before it is enforced. problems will remain in things
like:

decl("x")
x = 5
if x == 6:
y = 7

second proposal:

syntactic verification, at parsing time. for example:

my-prog.py:
-

##decl x
##decl y, z
x = 5
y = 6
z = 8
a = 6


when this program will be ran with the -strict option, like 6th line
will generate a SyntaxError: name 'a' not explicitly declared.

this strategy can verify all sorts of dead-branches, as demonstrated
above, but is not fit for dynamic code.

---

personally, i like the second proposal more, because it adds no new
language constructs, only a new commandline switch and meta-comments,
and is totally backwards compatible.






-Tomer

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


Re: Unicode entries on sys.path

2004-12-24 Thread vincent wehren
Just wrote:
In article <[EMAIL PROTECTED]>,
 "Martin v. Lowis" <[EMAIL PROTECTED]> wrote:

Hm, maybe more a windows question than a python question...
The real question here is: why does Python not support arbitrary
Unicode strings on sys.path? It could, in principle, atleast on
Windows NT+ (and also on OSX). Patches are welcome.

Works for me on OSX 10.3.6, as it should: prior to using the sys.path 
entry, a unicode string is encoded with Py_FileSystemDefaultEncoding. 
For this conversion "mbcs" will be used on Windows machines, implying 
that such conversions are made using the current system Ansi codepage.
(As a matter of interest: What is this on OSX?). This conversion is 
likely to be useless for unicode directory names containing characters 
that do not have a mapping to a character in this particular codepage.

The technique described by Martin may solve the problem for what in this 
case are Japanese characters, but what if I have directory names from 
another language group, such as simpliefied Chinese, as well?

The only way to get around this is to allow - as Martin suggests - 
arbitrary unicode strings in sys.path on those platforms that may have 
unicode file names.

--
Vincen Wehren
I'm not sure how well it works together with zipimport, though.

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


Re: BASIC vs Python

2004-12-24 Thread Alan Kennedy
[Alan Gauld]
> I dunno. Here in the UK there was a small home computer called (I
> think) the Oric(*) which had a membrane keyboard, 4K or RAM and
> ran Forth.It had a small cult following before dying out. It
> looked a bit like the early Sinclair/Timex ZX81 and I think the
> developers came from that stable.
>
> (*)I suspect the name was a dedication to a populat SciFi series
> of the time, Blake's 7, which had a computer called Orac...
I'm afraid your memory fails you ...
The Oric-1 had a keyboard with *actual* keys, and came in two memory 
sizes, 16K and 48K (I had the 48K :-). It was a lovely little machine, 
and included all kinds of goodies, like a 6522 VIA 

http://www.old-computers.com/museum/computer.asp?st=1&c=180
I think you're mixing up the Oric with the Jupiter Ace 
http://www.old-computers.com/museum/computer.asp?st=1&c=147
seasons-greetings-ly y'rs,
--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional Static Typing - Haskell?

2004-12-24 Thread Neal D. Becker
I've just started learning about Haskell.  I suggest looking at this for an
example.

A good intro: http://www.haskell.org/tutorial

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


Re: converting octal strings to unicode

2004-12-24 Thread TZOTZIOY
On 23 Dec 2004 18:41:57 -0800, rumours say that [EMAIL PROTECTED]
might have written:

>I have several ascii files that contain '\ooo' strings which represent
>the octal value for a character. I want to convert these files to
>unicode, and I came up with the following script. But it seems to me
>that there must be a much simpler way to do it. Could someone more
>experienced suggest some improvements?

(hope I cancelled the previous off-by-one-backslash post...)

your_string = "\\326du"
decoded_string = your_string.decode("string_escape")
unicode_text = unicode(decoded_string, "latin-1")
-- 
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: Execute code after death of all child processes

2004-12-24 Thread Mike Meyer
[EMAIL PROTECTED] (Markus Franz) writes:

> Hallo!
>
>
> I have a problem with this little script written in Python:
>
>
> import sys, os, time
> texts = ['this is text1', 'this is text 2']
> for current_text in env_sources[0:]:
>   pid = os.fork()
>   if pid == 0:
>   time.sleep(2)
>   print current_text
>   break
>
> As you is create some child processes depending on the number of vars
> in ?texts?. My problem is: How can I run some code after all child
> processes have been finished? (The code should be run only in the
> parent process.)
>
> I tried:
>
> import sys, os, time
> texts = ['this is text1', 'this is text 2']
> for current_text in env_sources[0:]:
>   pid = os.fork()
>   if pid == 0:
>   time.sleep(2)
>   print current_text
>   break
> os.waitpid(-1, 0)
> print 'this is the end'
>
> But this didn't work, 'this is the end' will be showed several times.

import sys, os, time
texts = ['this is text1', 'this is text2']
for current_text in env_sources[0:]:
pid = os.fork()
if pid == 0:
time.sleep(2)
print current_text
break
if pid != 0:
os.waitpid(-1, 0)
print 'this is the end'

Basically, make sure that none of the children run the waitpid and
last print.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Multiple Inheritance __slots__ problem

2004-12-24 Thread Nitin Shukla
Hello,

Can anyone tell why am I getting this error and how to work around this
problem.

>>> class Klass(object):
... __slots__ = ( 'x' )
...
>>> class Klass1(object):
... __slots__ = ( 'y' )
...
>>> class Klass(Klass, Klass1):
... __slots__ = ( 'z' )
...
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: multiple bases have instance lay-out conflict

I need to define slots in these classes and also need to inherit them in
Derived class.

Nitin


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


Re: Optional Static Typing

2004-12-24 Thread Mike Meyer
"John Roth" <[EMAIL PROTECTED]> writes:

> <[EMAIL PROTECTED]> wrote in message
> This may sound a bit
> cynical, but most real uber-programmers have either
> Lisp or Smalltalk in their backgrounds, and
> frequently both one. Neither of those languages
> have static typing, and they simply don't need it.

LISP has type declarations. Everybody I know doing production work in
LISP uses them. It's the only way to get reasonable performance out of
LISP compiled code.

Which raises what, to me, is the central question. If we have optional
static typing, can I get a performance enhancement out of it? If not,
why bother?

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about "pure virtual methods"?

2004-12-24 Thread Mike Meyer
Noam Raphael <[EMAIL PROTECTED]> writes:

>> Noam Raphael <[EMAIL PROTECTED]> writes:
> Of course, even in statically typed languages, you can't enforce
> an implementation to do what it should (too bad - it would have made
> debugging so much easier...)

That's what DbC languages are for. You write the contracts first, then
the code to fullfill them. And get exceptions when the implementation
doesn't do what the contract claims it does.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list Integer indexing dies??

2004-12-24 Thread Mike Meyer
Ishwor <[EMAIL PROTECTED]> writes:

> On 23 Dec 2004 14:28:37 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> My experience as a learner here is that there should be some
> automagics & say like "okay you want to do indexing on integers (
> context dependent); i'll give you the index of 0th position in that
> integer" ???

Python doesn't do things automagically. The rules for pythonic
behavior include "Explicit is better than implicit" and "In the face
of ambiguity, refuse the tempation to guess." Both of those are
violated by automatic conversions and the like.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading and Writing

2004-12-24 Thread Mike Meyer
Sir Galahad the chaste <[EMAIL PROTECTED]> writes:

> Hi,
>
> [EMAIL PROTECTED] wrote:
>> How should I: Open a Text file, read from it, modify it, print to
>> another .txt?
>> For instance: Read a string, sort it, write the sorted string.
>
> What do you mean by "sorting"? If you want to sort the lines contained
> in a file, you could do something like this.
>
> $ cat in.txt
> foo
> bar
> baz
> ham
> spam
> $ cat process.py
> #!/usr/bin/env python
> lines = open("in.txt").readlines()

Some people consider it bad style to leave opened files lieing around,
so this shold be:

f = open("in.txt")
lines = f.readlines()
f.close()

> lines.sort()
> out = open("out.txt", "w")
> for line in lines:
>  out.write(line)

Those two should be
out.writelines(lines)

> out.close()

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PHP vs. Python

2004-12-24 Thread Duncan Booth
Paul Rubin wrote:

> I've never heard of any large sites being done in Python, with or
> without scaling.  By a large site I mean one that regularly gets 100
> hits/sec or more.  There are many sites like that out there.  Those
> are the ones that need to be concerned about scaling.

How exactly would you know which large sites are using Python? The PHP 
sites tend to advertise their use of PHP by file extensions on every URL, 
but a lot of Python sites don't.

I don't know how to tell how many hits a random site has, but there are 
certainly some big users out there. For example Viacom uses Zope for many 
of its CBS and UPN websites. LastMinute.com, who definitely hit your large 
site definition, were working with Zope as well although so far as I know 
nothing has yet reached their live site.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list Integer indexing dies??

2004-12-24 Thread Duncan Booth
Antoon Pardon wrote:

> Suppose I write a number in octal notation.
> 
> What should 035[0] cough up? Be carefull it should
> cough up the same as 29[0].
> 

given that 035==0035 I say they 
should both cough up 0 for any positive index of course.
-- 
http://mail.python.org/mailman/listinfo/python-list


Execute code after death of all child processes

2004-12-24 Thread Markus Franz
Hallo!


I have a problem with this little script written in Python:


import sys, os, time
texts = ['this is text1', 'this is text 2']
for current_text in env_sources[0:]:
pid = os.fork()
if pid == 0:
time.sleep(2)
print current_text
break

As you is create some child processes depending on the number of vars
in ?texts?. My problem is: How can I run some code after all child
processes have been finished? (The code should be run only in the
parent process.)

I tried:

import sys, os, time
texts = ['this is text1', 'this is text 2']
for current_text in env_sources[0:]:
pid = os.fork()
if pid == 0:
time.sleep(2)
print current_text
break
os.waitpid(-1, 0)
print 'this is the end'

But this didn't work, 'this is the end' will be showed several times.

Can you help me?

Tanks.


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


Re: [PIL] is there a downloadable docs for PIL

2004-12-24 Thread Egor Bolonev
On Fri, 24 Dec 2004 10:00:39 +0100, Michel Claveau - abstraction  
meta-galactique non triviale en fuite perpetuelle.  
<[EMAIL PROTECTED]> wrote:

Is that ?  http://www.pythonware.com/products/pil/pil-handbook.pdf
yes. thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: BASIC vs Python

2004-12-24 Thread Alex Martelli
Tim Jarman <[EMAIL PROTECTED]> wrote:

> In article <[EMAIL PROTECTED]>,
>  Alan Gauld <[EMAIL PROTECTED]> wrote:
> 
> > I dunno. Here in the UK there was a small home computer called (I
> > think) the Oric(*) which had a membrane keyboard, 4K or RAM and
> > ran Forth.It had a small cult following before dying out. It
> > looked a bit like the early Sinclair/Timex ZX81 and I think the
> > developers came from that stable.
> 
> I believe my learned friend refers to the Jupiter Ace.

Yep -- I still have one stashed away somewhere.  Not sure where the
'oric' recollection may have come from, though.


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


Re: hidding the "console" window + system global shortcut keys

2004-12-24 Thread Nick Coghlan
Consider looking into Cygwin or MSYS if you want Windows access to *nix tools.
To hide the console window, use a .pyw extension on your Python scripts and/or 
run them with pythonw instead of python.

For the last, Mark Hammond's win32 extensions will probably be needed, but other 
than that, I have no idea :)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


ANNOUNCE: pyIrcServer 0.0.4.0-alpha is out!

2004-12-24 Thread Lethalman
(first, sorry for my poor English)
pyIrcServer (or pyIS) is a powerful and very personalizable IRCd. You 
can use it on several platforms that can run Python 
 (like Linux, Windows, MAC, and others) and set 
up a very personalizable config. pyIS is runnable as you download it, 
just a click and it's ready! This is possible because its code is 
interpreted, so you don't need to compile the sources.

You can add or remove features by changing modules, classes and utils. 
The modules expand the classes, and the classes expand the entire IRCd. 
You can totally change the aspect of your IRCd by changing classes and 
modules, and in order to be very configurable, the configuration file too.

RELEASE NOTES:
We made many features and fixed some bugs. The 0.0.3.x package has been 
discountinued because of the new improvements and updates for Python 2.4.x.

The most important things we changed are:
· First of all there's a simple implementation of link to servers and 
multiprotocols.
· Now you can add, remove and reload modules /on the fly/ by using the 
/ENGINE command directly from IRC.
· The code has been cleaned and decorated to let developers make good 
looking scripts.

DOWNLOAD: 
http://download.iosn.it/files/pyircserver/alpha.pkg/0.0.4.x/pyIrcServer-0.0.4.0-alpha.tar.gz
CHANGELOG: 
http://cvs.iosn.it/viewcvs/pyircserver/pyircserver/ChangeLog?view=markup

HOMEPAGE: http://pyircserver.iosn.it
IOSN PAGE: https://www.iosn.it/projects/pyircserver
NEWSLETTER: http://lists.iosn.it/mailman/listinfo/pyircserver-news
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode entries on sys.path

2004-12-24 Thread Just
In article <[EMAIL PROTECTED]>,
 "Martin v. Lowis" <[EMAIL PROTECTED]> wrote:

> > Hm, maybe more a windows question than a python question...
> 
> The real question here is: why does Python not support arbitrary
> Unicode strings on sys.path? It could, in principle, atleast on
> Windows NT+ (and also on OSX). Patches are welcome.

Works for me on OSX 10.3.6, as it should: prior to using the sys.path 
entry, a unicode string is encoded with Py_FileSystemDefaultEncoding. 
I'm not sure how well it works together with zipimport, though.

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


Re: [PIL] is there a downloadable docs for PIL

2004-12-24 Thread Michel Claveau - abstraction meta-galactique non triviale en fuite perpetuelle.
Is that ?  http://www.pythonware.com/products/pil/pil-handbook.pdf




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


Re: Optional Static Typing

2004-12-24 Thread Alex Martelli
John Roth <[EMAIL PROTECTED]> wrote:
   ...
> question: static typing is an answer. What's the question?
> (That's a paraphrase.)
> 
> The answer that everyone seems to give is that it
> prevents errors and clarifies the program.
   ...
> Most of the kinds of error that static typing is supposed
> to catch simply don't persist for more than a minute when
> you do test driven development.

...which is exactly the point of the famous post by Robert ("Uncle Bob")
Martin on another artima blog,
http://www.artima.com/weblogs/viewpost.jsp?thread=4639 .


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


Re: Keyword arguments - strange behaviour?

2004-12-24 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:
   ...
> the default params are evaluated at the definition. However, I still
> can't give a nice looking solution on how to re-write a function to
> have empty mutable values as default arguments: eg.
> 
> def method(a,b,opt1=[],opt2=None,opt3="",opt4={})
> 
> How could I re-write this (especially if there are perhaps 20 optional
> parameters,any number of which may have mutable defaults) without
> writing 20 "if opt1 is None: opt1=[]" statements?

I don't have the recipe I mentioned at hand, but what about:

def makebrianhappy(f):
saved_defaults = f.func_defaults
def with_fresh_defaults(*a, **k):
f.func_defaults = copy.deepcopy(saved_defaults)
return f(*a, **k)
with_fresh_defaults.__name__ = f.__name__
return with_fresh_defaults

@ makebrianhappy
def method(a, b, opt1=[], opt2=None, opt3="", opt4={}):
   ...

I've added spaces after commas to make ME happy too (lack of such spaces
is my least favourite Python irritation;-), but I guess the semantics of
this (UNTESTED) code would work even without that;-).


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


Re: Optional Static Typing

2004-12-24 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> Adding Optional Static Typing to Python looks like a quite complex
> thing, but useful too:
> http://www.artima.com/weblogs/viewpost.jsp?thread=85551
> 
> I have just a couple of notes:

Guido doesn't read this group; if you want him to read your notes, post
them as comments to Artima.

_My_ personal note is that I'm now even gladder I got myself Van Roy's
and Haridi's excellent "Concepts, Techniques and Models of Computer
Programming" book as a Christmas self-gift, and my motivation for
studying it in depth is renewed and refreshed...


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


Re: Keyword arguments - strange behaviour?

2004-12-24 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:
   ...
> I'm really looking for a neat way to do the following:
> 
> def method(a,b,opt1=None,opt2=None,opt3="",opt4=None):
> if opt1 is None: opt1=[]
> if opt2 is None: opt2={}
> if opt4 is None: opt4=[]
> 
> Python syntax is normally so neat but this just looks a mess if there
> are lots of parameters.

There's a decorator for that in the Cookbook (sorry, don't recall the
recipe number, but, it's on the site, and it got into the 2nd edition
which we're still expecting to have on paper at PyCon) -- basically
wrapping a function with a wrapper that does a copy.deepcopy on the
defaults values at each call (efficiency of course goes down the drain,
but you _did_ say "apart from efficiency"!-).


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


Re: Global variables and modules

2004-12-24 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:
   ...
> and here is the test script, test1.py
> -
> 
> from test2 import glbl, inc_glbl, get_glbl

Think of this as roughly equivalent to:

import locl
glbl = test2.glbl

and so on.  That is, after the 'from test2 import', the two names
test1.glbl and test2.glbl refer to the same object.  But if you now
rebind name test2.glbl to refer to a distinct object, that of course has
no effect on name test1.glbl.

> I would expect the three values to be ( 25, 26, 26 ), but what I get is

Why?  Take an equivalent:

a = 25
b = a
a = 26

would you now expect name b to be magically rebound to 26?  If so, then
you have a very peculiar mental model for name/value correspondences,
one that doesn't happen to hold in any language I know, surely not in
Python.  To repeat a commonly used metaphor: think of names as post-it
notes that may be attached to some piece of furniture, and moved from
one to another.  The notes are NOT attached to each other, but rather to
the objects: moving one post-it does not affect other post-its.

> It seems that the references to 'glbl' are seeing a local copy, rather

No copy whatsoever is involved.  After the assignment (binding) you do
with 'from test2 import', names test1.glbl and test2.glbl refer to the
same object (value).  If you now rebind either name, the other is
unaffected.

> than the original.  This is not what the literature says should be
> happening.

If you can point to sentences in "the literature" which have misled you
into believing a different behavior would be expected, I'll do my best
to fix those sentences (as a book and article author, editor, reviewer,
and Python contributor).  While the Python docs, including books &c, are
far from perfect, I doubt there is any such blooper left in them.

> I am looking for a way to share data between modules.  Can

If you really must, consider using a container object.  The most
suitable container object for these tasks is often a module.  I.e.,
code, in test1:

import test2

and then refer to test2.glbl throughout.  I.e., forget 'from', use
'import'.

As I wrote in Python in a Nutshell, p. 120, last paragraph before
"Module Loading":
"""
In general, the import statement is a better choice than the from
statement.  I suggest you think of the from statement [...] as [a]
convenience meant only for occasional use in interactive Python
sessions.  If you always access module M with the statement import M,
and always access M's attributes with explicit syntax M.A, your code
will be slightly less concise, but far clearer and more readable.
"""

I don't know how I could have put this advice more strongly or more
directly (I continue with explanations about the cases in which 'from'
is instead appropriate, chiefly getting single modules from packages).

Giving strong direct advice, rather than just reference info, in a book
of the "in a Nutshell" series, is not common, but I do it quite a bit;
after all, "how does Python work exactly", e.g. the fact that 'from X
import Y' is almost the same as 'Y = X.Y', is pretty simple to explain,
and so takes up little space -- OTOH, the consequences of this, such as
"thus, generally, don't use 'from', use 'import'" may not be obvious to
readers, so I point them out directly.

Of course, that doesn't help much if people don't _read_ it;-).


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


Dubious Python WAS: Re: Lambda going out of fashion

2004-12-24 Thread Brian van den Broek
Fernando Perez said unto the world upon 2004-12-23 14:42:
Alex Martelli wrote:

I don't know what it IS about lambda that prompts so much dubious to
absurd use, but that's what I observed.  I don't know if that plays any
role in Guido's current thinking, though -- I have no idea how much
"dubious Python" he's had to struggle with.

Just a side comment, unrelated to the lambda issue: it just occurred to me that
it might be very useful to have a collection of 'dubious python' available
somewhere.  Just as it is great for everyone to see good code in action, it is
equally enlightening to see examples of bad practices (preferably with an
explanation of why they are bad and the good alternatives).  

I suspect after your CB2 experience, you are in a uniquely well-qualified
position to have such a collection handy.  Whether you feel inclined to spend
the necessary time assembling it for public consumption is a different
story :)  But I think it would be a very valuable resource, and a great way to
point newbies to 'mandatory reading' before they travel down the same blind
alleys for the n-th time.
Cheers, and happy holidays,
f
Hi all,
+1
I would find this really useful!
I'm much more likely to be among the benefited than the benefactors. 
This could be a lot of work for one person. Thus, it seems like a good 
thing for a wiki, so as to spread the weight around. With that in mind, 
I created . I hope this seems 
like a good idea to others, particularly those more able to extend it 
than I. (I'd also be grateful if others could remove any feet than I 
might have inadvertently put into my mouth on the wiki page.)

Best to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: String backslash characters

2004-12-24 Thread Leif K-Brooks
PD wrote:
Hello,
I am new to python, but i am quite curious about the following.
suppose you had
print '\378'
which should not work because \377 is the max. then it displays two
characters (an 8 and a heart in my case...). What else does'nt quite
make sense is that if this is an octal why is an 8 accepted?
It's not doing quite what you think. The '\37' is seen as octal, but 
since '8' isn't a valid octal digit, it's seen as the literal character '8'.

In other words, these two lines are equivalent:
>>> '\378'
'\x1f8'
>>> '\37' + '8'
'\x1f8'
--
http://mail.python.org/mailman/listinfo/python-list