proxy for xmlrpc calls

2006-08-12 Thread Xavier
I'm attempting to write a proxy for xmlrpc calls.

I'm starting from this code;

class MagicObject:

 def __call__(self,*args,**kwargs):
 return MagicObject.__dict__['_stop'](self,self.n,*args,**kwargs)

 def __getattr__(self,name):
 if name in ('__str__','__repr__'): return lambda:'instance of 
%s at %s' % (str(self.__class__),id(self))
 if not self.__dict__.has_key('n'):self.n=[]
 self.n.append(name)
 return self

 def _stop(self,n,*args,**kwargs):
 self.n=[]
 return self.default(n,*args,**kwargs)

 def default(self,n,*args,**kwargs):
 return 'stop',n,args,kwargs



 >>c=MagicObject()
 >>x=c.beubeb.z(1,2,3,a='bbb')
 >>print x
('stop', ['beubeb', 'z'], (1, 2, 3), {'a': 'bbb'})

I did not write this, the source is here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435757

I want to expand this to do something like;

 >>a=MagicObject()
 >>x = a.b.c.d

Then on the last __getattr__ send a call over xmlrpc.
How do I determine when the last __getattr__ will be?

With method calls you know to send a call on xmlrpc when you hit 
__call__.  But if you're dealing with a getting nested attributes
what do you do?  How do I know when there are no more attributes?
I thought about getting the source code from
the correct frame, but I don't think thats a good solution.

Any ideas?
Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Serial I/O problem with pywin32 ?

2008-09-03 Thread Xavier
Hi,

I try to access to a Bluetooth GPS data-logger with Python. I use
pySerial.

Sending and receiving little messages (~100 char) works fine. However,
when I ask the GPS to dump the trails, it returns some Mbytes and here
is the problem : in the stream of bytes, I randomly losts chunks of
~100bytes.

I tried USPP and pyBlueZ instead of pySerial : same problem.

It doesn't like it is a bufferoverun bug from me because :
 - the GPS seems to wait when I do not read the stream,
 - there is never more than 200 inWainting() characters,
 - my code to test it is quite simple :

  seriallink = serial.Serial("COM40")
  fileName = "data.dump"
  out = open(fileName, 'w')
  while 1:
c = seriallink.read()
out.write(" %0.2X" % ord(c))
print "*",
  out.close()

(with pyBluez :
sock=BluetoothSocket( RFCOMM )
sock.connect(("00:0A:...", 1)))

I tried my program on two different PC with two Bluetooth dongle,
(with pySerial, USPP, pyBluez).
The same things are :
 - windows
 - the GPS (which works fine with the dumper program of the
constructor)
 - pyWin32

I've found another guy with a similar problem :
http://www.generation-nt.com/reponses/rs232-entraide-142097.html
He says:
 - no problem with little messages
 - lost of one byte every hour when receiving a lot of data

Any known problems with pywin32 and serial I/O when downloading a big
stream of data ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Serial I/O problem with pywin32 ?

2008-09-03 Thread Xavier
I tried under Linux... same problem.
So... it may comes from my little lines of code... or from my GPS.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Serial I/O problem with pywin32 ?

2008-09-15 Thread Xavier
Hi

I have resolved my problem by checking paquets.
It seems that it is a problem of the GPS (it's a very cheap GPS
Datalogger).

> Could be hardware flow control. See this sometimes on the bluetooth
> connections that are using Serial Port Protocol and the hardware flow
> control hasn't been physically implemented.

It seems it is the problem.
The policy seems to be :
 - ask the GPS for the data
 - touch wood
 - retry with the missing chunks
Even the official driver is doing this.

> Do you lose data after exactly the same amount of data has
> been received?

Not. The lost are randomized but it's chunks, ex :
300 consecutive bytes ok
30 consecutive bytes lost
250 bytes ok
40 bytes lost
800 bytes ok
50 bytes lost
...
--
http://mail.python.org/mailman/listinfo/python-list


multiprocessing.connection with ssl

2009-11-30 Thread Xavier
Hello

I've hacked multiprocessing.connection (in a basic way) to allow ssl
encryption using ssl.wrap_socket.

Anybody knows how i can contribute this to main developers?

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


Re: Creating a simple CGI Script

2012-08-02 Thread Xavier Combelle

In server.py you made a mistake in the declaration of the cgi directory
it should be
handler.cgi_directories = ["/"]


Le 02/08/2012 20:20, Smaran Harihar a écrit :

Hi,

I am trying to create a simple CGI Script and following this tutorials 
 
but unfortunately my output is only printing the cgi file as it is on 
the browser.


I have already provided the py scripts with the executable functions.

This is my server.py  and this is 
mytest_cgi.py 


--
Thanks & Regards
Smaran Harihar



This body part will be downloaded on demand.


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


Re: Batching HTTP requests with httplib (Python 2.7)

2012-09-17 Thread Xavier Combelle

instead of

Le 14/09/2012 12:56, Dwight Hutto a écrit :

service_num_list = [num for num in range(0,5)]
for service_num in service_num_list:
eval("web_service_call%i(%i)" % (service_num,service_num))



service_num_list = [num for num in range(0,5)]
for service_num in service_num_list:
locals()["web_service_call%i" % (service_num,)](service_num)

would be safer eval is really bad

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


Re: Help with Python/ArcPy

2012-12-12 Thread Xavier Ho
You can always try http://stackoverflow.com/search?q=ArcPY, or post your
question there.

Cheers,
Xav



On 13 December 2012 08:07, Michelle Couden wrote:

>  Does anyone know of a website or forum  where there is help for ArcPY
> (Python) programmers? ESRI’s (GIS) resource center Forums are very busy and
> my questions go days without an answer. Any suggestions would be great.
> Thanks!!
>
> ** **
>
> ** **
>
> ** **
>
> *Michelle Couden*
>
> TPP-T GIS Cartographer
>
> Certified GIS Analyst
>
> (512) 486-5136
>
> Fax (512)486-5153
>
> [email protected]
>
> ** **
>
> Mind the road, not your business.
>
> [image: Logo]
>
> ** **
>
> ** **
>
> ** **
>
> ** **
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
<>-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3.2 can't extract tarfile produced by 2.7

2012-12-26 Thread Xavier Combelle

You probably want to write

of = open("DUMP.tbz", "wb")

and

gf =open("DUMP.tbz", "rb")
--
http://mail.python.org/mailman/listinfo/python-list


Python 2 multiprocessing examples in docs.python.org

2013-01-31 Thread Xavier Ho
Hey all,

I ran the example code on multiprocessing.  On the "Pool example", an
assertion failed with "testing garbage collection".

Traceback (most recent call last):
  File "test.py", line 314, in 
test()
  File "test.py", line 295, in test
assert not worker.is_alive()
AssertionError

The relevant example code reads:

pool = multiprocessing.Pool(2)
DELTA = 0.1
processes = pool._pool
ignore = pool.apply(pow3, [2])
results = [pool.apply_async(time.sleep, [DELTA]) for i in range(100)]

results = pool = None

time.sleep(DELTA * 2)

for worker in processes:
assert not worker.is_alive()

My questions are 1) How does that GC test work, and 2) Does that mean my GC
isn't working as fast as it should have been?

The machine's Python:

xav ❖ /tmp  > python
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

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


Re: Upgrading from 2.7 to 3.x

2012-04-25 Thread Xavier Ho
What operating system are you running?

Cheers,
Xav



On 26 April 2012 13:08, deuteros  wrote:

> I'm fairly new to Python I have version 2.7 installed on my computer.
> However
> my professor wants us all to use the latest version of Python. How do I go
> about upgrading? Do I just install the new version? Do I have to do
> anything
> with the old version already installed?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fun python 3.2 one-liner

2011-03-29 Thread Xavier Ho
http://www.ideone.com/infch
^ Result of the below code

On 29 March 2011 19:50, Raymond Hettinger  wrote:

> from collections import Counter
> from itertools import product
>
> print('\n'.join('*'*(c//2000) for _,c in sorted(Counter(map(sum,
> product(range(6), repeat=8))).items(
>
>
> almost-normally-yours,
>
> Raymond
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to put form and display its result(data from database) on the same window?

2005-12-07 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> Hi Guys,
> 
> I have designed a web application. In its one window I put a form. User
> can click submit button of this form to run a pathon script to get data
> from database. Then User get a new window which display the result. Now
> I want to put the form and display data on the same window. How I can
> do this?
> 
> If I use frameset, I need to put form in a html file and put data in a
> table in scond html file. How I  can do this?
> 
> 
> Any help is appreciated.
> 
> 
> 
> LLI
> 

Submit to the file holding the form, and display the data only when 
informations came from the form, no need to use framesets here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find the type ...

2005-12-09 Thread Xavier Morel
Lad wrote:
> Hello
> How can I find out in Python whether the operand is integer or a
> character  and change from char to int ?
> Regards,
> L.
> 
You may want to try the "type" command.
And there is no character type in cPython (unless you're using ctypes 
that is)

There is not much point though, you can use the "int" construct on your 
expression, Python'll try to convert the expression to an integer by 
itself (and throw an exception if it can't)

 >>> a = 3
 >>> int(a)
3
 >>> a = "3"
 >>> int(a)
3
 >>> a = "e"
 >>> int(a)

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 int(a)
ValueError: invalid literal for int(): e
 >>>

You can even do base conversions with it:

 >>> a="0xe"
 >>> int(a)

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 int(a)
ValueError: invalid literal for int(): 0xe
 >>> int(a,16) # Silly me, 0xe is not a decimal
14
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to detect the presence of a html file

2005-12-09 Thread Xavier Morel
Phoe6 wrote:
> Operating System: Windows
> Python version: 2.4
> 
> I have bookmarks.html and wumpus.c under my c:
> 
> When I tried to check the presence of the bookmarks.html, I fail.
> 
 os.path.isfile('c:\bookmarks.html')
> False
 os.path.isfile('c:\wumpus.c')
> True
> 
 os.path.exists('c:\wumpus.c')
> True
 os.path.exists('c:\bookmarks.html')
> False
> 
 os.access('c:\bookmarks.html',os.F_OK)
> False
> 
> I can assure you that c:\bookmarks.html exists! and I opened this and
> checked it in the browser as well.
> 
> Why is this behavior? And How Should I check for the presence of this
> file?
> 
> Any help appreciated.
> 
> Thanks!
> Senthil
> 

Have you tried escaping the "\"?

try
 >>> os.path.exists('c:\\bookmarks.html')

'\w' is not a special sequence and therefore gets automagically 
translated to the escaped "\\w", but "\b" is equivalent to "\x08" and 
your functions therefore see the string "c;\x08ookmarks.html".

If you don't want to escape your strings, use rawstrings (prepend your 
strings with "r", "c:\bookmarks.html" therefore becomes
r"c:\bookmarks.html")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal: Inline Import

2005-12-09 Thread Xavier Morel
Shane Hathaway wrote:
> Thoughts?

 >>> import re; name_expr = re.compile('[a-zA-Z]+')
 >>> name_expr
<_sre.SRE_Pattern object at 0x00F9D338>
 >>>

the import statement can be called anywhere in the code, why would you 
add strange syntactic sugar that doesn't actually bring anything?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another newbie question

2005-12-10 Thread Xavier Morel
Mike Meyer wrote:
> And you've once again missed the point. The reason you don't
> manipulate the attributes directly is because it violates
> encapsulation, and tightens the coupling between your class and the
> classes it uses. It means you see the implementation details of the
> classes you are using, meaning that if that changes, your class has to
> be changed to match.
> 
One of Python's greatnesses is that a property is, for all means an 
purposes, a fully virtual instance attribute/member.

If you follow the KISS principle, as long as your (naive? probably) 
implementation of the class has "real" attributes and their manipulation 
is meaningful & makes sense from an external point of view, just leave 
it at that. If you happen to change the implementation for whatever 
reason and happen to remove the real attributes, just create virtual 
attributes with a property and be done with it.

Wrapping everything just because you can and considering that 
encapsulation is only truly done if you never happen to touch what's 
under the hood (even without knowing it) is the Java Way, this is Python.

In Python, the interface of an object instance is always virtualized 
because you can never know if you're manipulating "real" attributes or 
property-spawned virtual attributes. _that_, in my opinion, is not 
knowing about the implementation details.

While a Java object is mineral (set in stone) and trying to abstract 
everything from the start (and generate 50 pages documentation for each 
class to be sure that you didn't miss anything) kind of makes sense, a 
Python object is an organic, morphing, living entity. Don't abstract 
everything and over-engineer from the start just because you can and 
because you'd do it in Java or C#, only abstract (from your point of 
view) when you *have to*. And remember that "Java's Object Oriented 
Programming" is not the only one worth using, even though some people 
would like to make you believe it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Two questions on lambda:

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

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

For example, the code

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

does not compile, although:

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

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

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

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


In languages like Caml, you can do:

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

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

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


VIAGRRÁ-Good for your life

2005-08-19 Thread Xavier Burger



Hello,
 
Welto PharmcyByMail ST0RE - Save huge 70% on all the 0rders with us.come 
 
We are there whi only stoch gives this great deal to you!
 
VlALLlS VALy other drugplAGRRA ClUUM and mans in our sho
 
r NEW PRlCESCheck out ou
 
Have a nice day.
-- 
http://mail.python.org/mailman/listinfo/python-list

How to Mock a mongodb

2015-02-07 Thread Xavier Pegenaute

Dear,

I am trying to mock the use of a mongo db and I am having some trouble. 
Appears that I am not able to return a desired value from 
mongo.find().count(). I made a proof of concept to try to reduce 
complexity of the real problem.


You can find the code which is going to be tested in [1], and the code 
of the test case in [2].


Do you know exactly wat's wrong with it?, or may you point me to some 
direction?


Thanks,
Xavi
[1] - http://pastebin.com/0vGqsURk
[2] - http://pastebin.com/6Y6K4dUn
--
https://mail.python.org/mailman/listinfo/python-list


How to Mock a mongodb

2015-02-07 Thread Xavier Pegenaute

Dear,

I am trying to mock the use of a mongo db and I am having some trouble. 
Appears that I am not able to return a desired value from 
mongo.find().count(). I made a proof of concept to try to reduce 
complexity of the real problem.


You can find the code which is going to be tested in [1], and the code 
of the test case in [2].


Do you know exactly wat's wrong with it?, or may you point me to some 
direction?


Thanks,
Xavi
[1] - http://pastebin.com/0vGqsURk
[2] - http://pastebin.com/6Y6K4dUn
--
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] Awesome bug of the week

2014-08-13 Thread Xavier Ho
Haha!


On 14 August 2014 14:54, Steven D'Aprano  wrote:

> Nothing to do with Python, but awesome: "OpenOffice won't print on
> Tuesdays".
>
> https://bugs.launchpad.net/ubuntu/+source/cupsys/+bug/255161/comments/28
>
>
>
> --
> Steven
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Execute a command on remote machine in python

2011-11-15 Thread Xavier Ho
It sounds like Fabric is what you're after. We use it at work and it's the
best thing since ssh. ;]

http://docs.fabfile.org/en/1.3.2/index.html

(Actually, it uses ssh internally and allows you to do remote shell-like
programming in a pythonic fashion.)

Cheers,
Xav



On 15 November 2011 22:04, Roark  wrote:

> Hi,
>
> I am first time trying my hands on python scripting and would need
> some guidance from the experts on my problem.
>
> I want to execute a windows command within python script from a client
> machine on a remote target server, and would want the output of the
> command written in a file on client machine. What is the way it could
> be achieved.
>
>
> Thanks in advance,
> Roark.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Comparing None and ints

2012-01-16 Thread Xavier Ho
Hello,

I discovered this strange property by accident:

Python 2.7.2 (default, Nov 21 2011, 17:25:27)
[GCC 4.6.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> None < 0
True
>>> None == 0
False
>>> None > 0
False
>>> int(None)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: int() argument must be a string or a number, not 'NoneType'

What was the rationale behind this design?  Specifically, (None < 0)
== Trueand(None == 0) == False
?

Personally I would have expected an exception on all tests above.

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


Re: Comparing None and ints

2012-01-16 Thread Xavier Ho
Good to see Python3 got rid of that confusion :]

Cheers,
Xav



On 17 January 2012 16:50, Chris Angelico  wrote:

> On Tue, Jan 17, 2012 at 5:47 PM, Xavier Ho  wrote:
> > What was the rationale behind this design?  Specifically, (None < 0) ==
> True
> > and (None == 0) == False?
> >
> > Personally I would have expected an exception on all tests above.
>
> Compare with Python 3:
>
> >>> None<0
> Traceback (most recent call last):
>   File "", line 1, in 
>None<0
> TypeError: unorderable types: NoneType() < int()
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Recording live video stream from IP camera issue

2013-02-06 Thread Xavier Ho
On 6 February 2013 23:12, Sam Berry  wrote:

> I have no vast knowledge of python, but i came across this code to capture
> video from my IP camera
>
> This code works, however when i try to playback the .avi file in VLC
> player...


I've been working with several IP cameras with Python and OpenCV.  It's a
bit of a hassle, but it is not difficult.

However I will say that VLC can open a network location and save the video
at the same time.  If all you want to do is capture and save, Python is not
necessary.

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


Re: Recording live video stream from IP camera issue

2013-02-06 Thread Xavier Ho
On 7 February 2013 00:12, Sam Berry  wrote:

> Hi,
>
> This is for a university project.
>
> My issue is that i have built an App using pythons Kivy module, and i need
> to be able to stream and record from an IP camera upon request.
>
> I have just used the VLC.exe to stream the video feed. But it is the
> recording i am having problems with.
>
> I'l look into OpenCV, thanks for the help!
>
> Sam
>

I see.  In that case, cv2.VideoCapture(ip_address) should return you a
video object, which you can check for status and use its .read() method to
fetch a frame. :]

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


Re: Recording live video stream from IP camera issue

2013-02-17 Thread Xavier Ho
Hi Sam,

Did you compile your OpenCV with gstreamer?  That's where I'd look first.

Cheers,
Xav


On 18 February 2013 01:15, Sam Berry  wrote:

> Hi Xav,
>
> Iv been looking into OpenCV, i can easily stream my laptops webcam using
> this code.
>
> import cv2
>
> cv2.namedWindow("preview")
>
> vc = cv2.VideoCapture(0)
>
> if vc.isOpened(): # try to get the first frame
> rval, frame = vc.read()
> else:
> rval = False
>
> while rval:
> cv2.imshow("preview", frame)
> rval, frame = vc.read()
> key = cv2.waitKey(20)
> if key == 27: # exit on ESC
> break
>
> However using the cv2.Videocapture(ip_address) method will not load my IP
> camera video feed into the new window. I can view the stream in any web
> browser or VLC using the IP address
> http://192.168.1.72:1025/videostream.cgi?user=&pwd=&resolution=8.
>
> Did you have this issue? Is there some lines of code i may need to add?
>
> Any help would be appreciated!
>
> Thanks, Sam
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to quickly set up a multithreaded server that can handle http file post.

2013-03-11 Thread Xavier L.

On 13-03-11 10:42 AM, Shiyao Ma wrote:

Today I come across a problem.
Basically, my need is that I want to launch a http server that can not
only support get but also support post (including post file).
My first idea is to use -m http.sever. However, it only supports get.
Later I find some one extended basehttpserver and made it  support post.
However it is not multithreaded.

Is it easy to write a RELIABLE (I mean under normal cases) multithreaded
server that suits my need.
Also, are there any already invented wheel I can use?

Thx


--
My gpg pubring is available via: gpg --keyserver subkeys.pgp.net
 --recv-keys 307CF736

More on: http://about.me/introom

The best would be to use an existing webserver, such as Apache, Nginx, 
Lighttpd, etc. with python running as a fcgi or cgi script.


Those webservers have been tested for longer and there is no need to 
reinvent the wheel.


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


Re: how do you make a loop run in reverse?

2013-03-26 Thread Xavier Ho
There is a built-in function that reverses an iterable.  Have a look at the
documentation.

xav


On 27 March 2013 10:59,  wrote:

> So i have a set of for loops that create this :
>
> ***
> ***   ***   ***   ***   ***   ***   ***
> ***   ***   ***   ***   ***   ***   ***
>***   ***   ***   ***   ***   ***   ***
>***   ***   ***   ***   ***   ***   ***
> ***
>
>  *
> ***
>*
>   ***
>  *
>
> but i want to nest all the loops under one BIG loop that'll run in reverse
> to make this:
>
> ***
> ***   ***   ***   ***   ***   ***   ***
> ***   ***   ***   ***   ***   ***   ***
>***   ***   ***   ***   ***   ***   ***
>***   ***   ***   ***   ***   ***   ***
> ***
>
>  *
> ***
>*
>   ***
>  *
>   ***
>*
> ***
>  *
> ***
>***   ***   ***   ***   ***   ***   ***
>***   ***   ***   ***   ***   ***   ***
> ***   ***   ***   ***   ***   ***   ***
> ***   ***   ***   ***   ***   ***   ***
> ***
>
> Is this possible?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Functional vs. Object oriented API

2013-04-10 Thread Xavier Ho
Hi Max,

In Python, we prefer readability over anything else.  The simpler you can
write it, the better it can be understood.

That said, I've never considered using (i, j, k) as a vector component
before.  I've always done something akin to:

>>> vector = Vector(2, 4, 6)
>>> print (vector.normalize().y)

However, if you use the mathematical definition of a vector, with standard
symbols:

v = x*i + y*j + z*k

Then I believe vector.j is a much choice.  As long as your documentation
states it's read-only, I think most mathematicians will love that notation.

.

As far as dot products go, there isn't really a big difference between the
two forms you have there.  Both are equally as readable.

When C++ was invented people had already debated about the two forms.
 There isn't a general consensus on this debate, but most would probably
agree that overloading the * operator of a vector to do dot product is a
bad idea, since some people want cross product, or per-component
multiplication.  At the end of the day, dot() or dot_product() is more
readable, and it doesn't matter if you have it as a function in or outside
of a vector's class.

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


Re: double underscore attributes?

2005-12-10 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> Could someone explain the use of __add__ (and similar double underscore
> attributes) and what their use is.
> 
> Bob
> 
Methods with double leading and trailing underscores are basically 
"magic methods" with specific meanings for the Python interpreter.

You're not supposed to use them directly (in most cases) as they are 
wrapped by syntactic sugar or part of protocol's implementation.

__add__, for example, is the definition of the "+" operator, using 
"(5).__add__(8)" is exactly the same as using "5+8".

To get a list of most of these magic methods, check the Python 
documentation on the "operator" module.

These magic methods allow you to emulate numbers, sequences, iterators, 
or even callables (allowing you to use an object as a function). Be 
really careful with them though, one of the things that plagued (and 
still plague) C++ is the abuse of operators overloading and modification 
of their meaning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Great books on Python?

2005-12-11 Thread Xavier Morel
Tolga wrote:
> I am not unfamiliar to programming but a newbie in Python. Could you
> recommend me (a) great book(s) to start with? Free online books or
> solid books are welcome.
> 
> Thanx in advance.
> 
I'd call Dive Into Python a reference, it's an extremely clear yet 
pythonic book, and it's available online for free.

And I guess that you already checked it, but the Python's Tutorial is -- 
of course -- imperative.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO in Python? ^^

2005-12-11 Thread Xavier Morel
Matthias Kaeppler wrote:
> Why would I want to use an attribute in Python, where I would use 
> getters and setters in Java? I know that encapsulation is actually just 
> a hack in Python (common, "hiding" an implementation detail by prefixing 
> it with the classname so you can't access it by its name anymore? Gimme 
> a break...), but is that a reason to only write white box classes? ^^
> 
> - Matthias
> 

If you've ever written non-trivial code in Java, you can't deny that 
most of the classes are littered by pages and pages of

--
protected FooClass foo;
FooClass getFoo() {
return foo;
}
void setFoo(FooClass foo) {
this.foo = foo;
}
--

This is more or less equivalent to a simple
--
public FooClass foo;
--
but allows you to change the implementation details of the class without 
having to bork your whole interface later.

Now, you have no reason to do this in python, you can use a regular 
"real" attribute, and if you need to change the  implementation details, 
you can remove the real attribute and replace it with a virtual 
attribute through properties without changing the class' interface.
--
 >>> class Bar(object):
def __init__(self):
self.foo = 5


 >>> bar = Bar()
 >>> bar.foo
5
 >>>
 >>> # now let's change the Bar class implementation and split foo in 
boo and far
 >>>
 >>> class Bar(object):
def __init__(self):
self.boo = 2
self.far = 3
def _getfoo(self):
return self.boo + self.far
foo = property(_getfoo)


 >>> bar = Bar()
 >>> bar.foo
5
--
And this is completely transparent for anyone using the Bar class, they 
don't give a damn about what happens inside.

You can also use it to add checks on the allowed values, for example
--
 >>> class Bar(object):
def __init__(self):
self._foo = 5
def _getfoo(self):
return self._foo
def _setfoo(self,foo):
if not 0 <= foo <= 10:
raise ValueError("foo's value must be between 0 and 10 
(included)")
self._foo = foo
foo = property(_getfoo, _setfoo)


 >>> bar = Bar()
 >>> bar.foo
5
 >>> bar.foo = 2
 >>> bar.foo
2
 >>> bar.foo = 20

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 bar.foo = 20
   File "", line 8, in _setfoo
 raise ValueError("foo's value must be between 0 and 10 (included)")
ValueError: foo's value must be between 0 and 10 (included)
 >>>
--
or everything else you'd use Java's getters/setters for, but without 
having to over-engineer your classes and wrap everything just because 
the language doesn't allow you to change your mind if you ever realize 
you made mistakes in the previous implementations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Displaying error message in a try except?

2005-12-11 Thread Xavier Morel
Fredrik Lundh wrote:
  > assuming that "true" means "the message you would get if you hadn't
 > used a try/except", the traceback module is what you want:
 >
 > you can also inspect the exception status via the sys.exc_info() call.
 > e.g.
 >
There is also the third way of catching an exception explicitly and 
printing it's arguments and class (doesn't give exactly the same 
information, but gives relevant informations nonetheless)

--
 >>> try:
1/0
except ZeroDivisionError, e:
print e
print e.args
print repr(e)


integer division or modulo by zero
('integer division or modulo by zero',)

--

(catching Exception instead of ZeroDivisionError would yield the same 
result, but would also act as an Exception trap that voids any exception 
raised)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is incredible!

2005-12-12 Thread Xavier Morel
Luis M. Gonzalez wrote:
> You are not the first lisper who fell inlove with Python...
> Check this out:
> http://www.paulgraham.com/articles.html
> 
Paul Graham is not in love with Python though, he's still very much in 
love with Lisp.

He merely admits being unfaithful to Lisp from time to time (and clearly 
states that Python is one of the non-Lisp languages he likes best).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IsString

2005-12-13 Thread Xavier Morel
Tom Anderson wrote:
> In what sense are the names-bound-to-references-to-objects not variables?
> 

In the sense that a variable has various meta-informations (at least a 
type) while a Python name has no information. A Python name would be 
equivalent to a C void pointer, it can mean *any*thing and has no 
value/meaning by itself, only the object it references has.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "0 in [True,False]" returns True

2005-12-13 Thread Xavier Morel
Mike Meyer wrote:
> But this isn't necessarilly true:  is perfectly legal.
> 
>   http://mail.python.org/mailman/listinfo/python-list


Re: Horribly noobful string question

2005-12-13 Thread Xavier Morel
Fredrik Lundh wrote:
> "SeNTry" wrote:
> 
>> My first post here as I just begin to learn programming in general and
>> python in particular.  I have all the noobie confused questions, but as I
>> work thru the tutorials I'm sure I'll find most my answers.
>>
>> This one is eluding me tho... I am working in the tutorials, writing scripts
>> as presented and then modifying and expanding on my own to try to learn.
>> I'm working with one that asks the user to 'guess a number I'm thinking',
>> and with simple while loop, flow control and operands, returning an answer
>> to guess again or you got it.  I've added a 'playagain' function I've got
>> working, but what I want is to stop the program from crashing when someone
>> enters a string value instead of a int value.  I know strings are immutable,
>> and they can be changed to an int equivalent, but I just want the script to
>> recognize the input as a string and print a simple "that's not a number, try
>> again' type of message.  I can't find the syntax to include in the
>> if/elif/else block to include a line that says something like,
> 
> assuming you're using raw_input() to get the guess, you always
> have a string (in python's sense of that word).
> 
> what you seem to want is to check if the string contains a number
> or not.  here's one way to do this:
> 
> guess = raw_input("make a guess: ")
> if guess == secret:
> print "congratulations!"
> elif not guess.isdigit():
> print "that's not a number! please guess again!"
> ...
> 

that, or just write something like

guess = raw_input("Make your guess > ")
try:
if int(guess) == secret:
# ok
except ValueError:
# no good
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how can i change the default python?

2005-12-13 Thread Xavier Morel
Koray Bostancı wrote:
> Hi all,
> 
> When i type python in terminal it runs the python2.3 interpreter, but i
> want to use 2.4 and Python2.4 package is already installed.
> 
> How can i change the default python in my system? I searched google for
> a little but couldn't find.
> 
> Using Debian GNU/Linux.
> 
> 
> koray

"python" is usually merely a link on your "main" python distribution 
(it's the same for many other things, gcc for example).

python (and all the python versions) are in /usr/bin for the deb'.

To rebind it, just remove the current link

$ rm /usr/bin/python

then create a new symbolic link to /usr/bin/python2.4

$ ln -s /usr/bin/python2.4 /usr/bin/python

(you may have to use *sudo* to perform these operations BTW)

Voila, you're done, calling python now starts the python2.4 interpreter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IsString

2005-12-13 Thread Xavier Morel
Steven D'Aprano wrote:
> name = "spam spam spam spam"
> 
> the value of the variable "name" is a pointer, and not a string. Riiight.
> 
Yes, it's a reference to an object of type string holding the value 


> def increment(n):
> """Add one to the argument changing it in place."""
> # In Pascal, I would need the var keyword to get this behaviour,
> # but Python is call by reference so all variables are passed 
> # by reference.
> n += 1
> 
> x = 1
> increment(x)
> assert x == 2
> 
> but that doesn't work in Python either.
> 

That example is mightily flawed since Python's integers are immutable 
objects.

Here, python creates a new integer object of value "n+1" and binds the 
_local_ name "n" to this new object. n isn't bound to it's initial 
object anymore (the one x is bound to), and therefore can't modify it.

Now use a mutable type instead of an immutable int and you'll notice a 
pass-by-reference behavior.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I load python script into Html ??

2005-12-13 Thread Xavier Morel
Shouldn't have hit the "send" button so fast...

Addendum: the script element doesn't have any language attribute, the 
attribute you're supposed to use is "type" and it takes the MIME type of 
your script as a value.

s/language="javascript"/type="text/javascript"/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I load python script into Html ??

2005-12-13 Thread Xavier Morel
PatPoul wrote:
> I want to do the same thing as
> 
> 
> but with a python script  :
> 
> 
> ==
> if xxx.py :
> def mytest():
>   alert("test")
>   window.document.write('test')
> ==
> and test.html :
> 
> 
> 
> 
> mytest()
> 
> 
> ==
> 
> I always got this error :
> NameError : name 'mytest' is not defined
> 
> Thx ... 
> Patrick Poulin
> 
Long story short, no.

The browser needs binding to the language, and either the ability to use 
the external interpreter or embed an interpreter, and no browser 
currently has that kind of thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why and how "there is only one way to do something"?

2005-12-15 Thread Xavier Morel
Aahz wrote:
> In article <[EMAIL PROTECTED]>,
> Steve Holden  <[EMAIL PROTECTED]> wrote:
>> (Part of) Python's credo (which you can read in context by typing
>>
>> import this
>>
>> at an interactive command prompt) is "There should be one (and 
>> preferably only one) way to do it".
> 
> Actually, I've gotten used to doing
> 
> python -c 'import this'
Which can be built even more easily with

$ python -m this
(no quotes needed btw)

It's usually useful to pipe it through grep too, in order to get only 
the piece of zen knowledge you need.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuples

2005-12-15 Thread Xavier Morel
Tuvas wrote:
> Let's say I make a program something like follows:
> 
> x=[]
> x.append([1,2,3])
> x.append([4,5,6])
> print x
> print x[0]
> print x[0][1]
> x[0][1]=5
> 
> Okay, everything works here as expected except the last line. Why won't
> this work? Thanks for the help!
> 
Works for me, do you have more informations?

 >>> x = list()
 >>> x.append([1,2,3])
 >>> x.append([4,5,6])
 >>> print x
[[1, 2, 3], [4, 5, 6]]
 >>> print x[0]
[1, 2, 3]
 >>> print x[0][1]
2
 >>> x[0][1] = 5
 >>> print x[0][1]
5
 >>>

Now if you're really using tuples, that last line won't work because 
tuples are immutable e.g. you can't modify a tuple's elements after the 
tuple's creation

 >>> y = list()
 >>> y.append((1,2,3))
 >>> y.append((4,5,6))
 >>> print y
[(1, 2, 3), (4, 5, 6)]
 >>> print y[0]
(1, 2, 3)
 >>> print y[0][1]
2
 >>> y[0][1] = 5

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 y[0][1] = 5
TypeError: object does not support item assignment
 >>>

And the reason is explicitly stated (tuples don't support item assignment)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RoR like (was : SPE 0.8.1.b Python IDE...)

2005-12-15 Thread Xavier Morel
Adrian Holovaty wrote:
> bruno at modulix wrote:
>> RoR is not an IDE, it's a web framework. The closest things in Python
>> are TurboGears (good Ajax/js support via Mochikit), Subway (never
>> tested), and Django (no Ajax support AFAIK).
> 
> Note that "no Ajax support" is misleading. Of course you can use Ajax
> with Django, just as you can use it with *any* Web framework. That's
> because Ajax is a browser-side technology (JavaScript), not a
> server-side technology (Python). Django is just as capable of producing
> JavaScript as it is of producing (X)HTML or whatever else.
> 
> Hope that clears things up!
> 
> Adrian
> 

The so-called Ajax, standing for Asynchronous Javascript + XML is NOT a 
"browser-side technology", it's a bunch of technologies used together in 
a client-server environment.

If you only use Javascript without communicating with any server, you're 
not using the so-called Ajax, you're merely using Javascript (not that 
it's a bad thing, mind you).

Please refer to the article that started the hype 
(http://www.adaptivepath.com/publications/essays/archives/000385.php) 
for more insight about what Ajax is (or is supposed to be).

An ajax-integrating framework would therefore be a framework that could 
generate both the client-side javascript and the server-side variations 
of the resources that can be called, retrieved and used by the client in 
a seamless and transparent way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib.urlopen

2005-12-17 Thread Xavier Morel
JabaPyth wrote:
> Hello,
> I'm trying to use the urllib module, but when i try urllib.urlopen, it
> gives me a socket error:
> 
> >>import urllib
> >>print urllib.urlopen('http://www.google.com/').read()
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Python24\lib\urllib.py", line 77, in urlopen
> return opener.open(url)
>   File "C:\Python24\lib\urllib.py", line 180, in open
> return getattr(self, name)(url)
>   File "C:\Python24\lib\urllib.py", line 296, in open_http
> h.endheaders()
>   File "C:\Python24\lib\httplib.py", line 794, in endheaders
> self._send_output()
>   File "C:\Python24\lib\httplib.py", line 675, in _send_output
> self.send(msg)
>   File "C:\Python24\lib\httplib.py", line 642, in send
> self.connect()
>   File "C:\Python24\lib\httplib.py", line 610, in connect
> socket.SOCK_STREAM):
>  IOError: [Errno socket error] (11001, 'getaddrinfo failed')
> 
> Any ideas on what i did wrong?
> 
Works for me, do you have a proxy or some strange setup for accessing to 
the web?

Try using the urllib2 module, too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can you pass functions as arguments?

2005-12-19 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> I want to calculate f(0) + f(1) + ...+ f(100) over some function f
> which I can change. So I would like to create a function taking f as
> argument giving back the sum. How do you do that in Python?
> 
Python functions (and classes, and modules) are first-class objects, so 
you can use them as regular objects: send them as arguments, generate 
and return them from functions, ...

BTW, if your goal is to create that kind of sums of function results, I 
think you'd be interested in using both Python's _generators_ and the 
built-in function *sum*.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When Python *Eggs* better than Python *distutils*?? What's Eggs?

2005-12-20 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> So basically Python Eggs precompiles and compresses
> binaries for you so you just have to load it to run
> your app?
> 

Nah, Eggs is a packaging system, what you don't have to do is 
compile/configure, because the packaging does that for you. It also 
handles things like pre-required packages (the packages that this 
package uses), even though that doesn't always work atm.

If you ever used a debian-based linux system, think of Eggs as a 
Python-specific apt-get.

The most advanced kind of language-specific installer atm is the Ruby 
Gems packaging and distribution system (http://docs.rubygems.org/), go 
check it for more insight of what Eggs wants to be (and I hope it'll 
evolve to be as good as gems) (and the install software should be named 
eggs or hatch, not easy_install, ugly).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Try Python update

2006-01-06 Thread Xavier Morel
Mike Meyer wrote:
> After spending time I should have been sleeping working on it, the try
> python site is much more functional. It now allows statements,
> including multi-line statements and expressions. You can't create code
> objects yet, so it's still more a programmable calculator than
> anything real.
> 
> I've got some of the tutorial text (literally) up as well. I hope to
> make it easier to read the tutorial and interact with python at the
> same time in the near future.
> 
> The url is http://www.mired.org/home/mwm/try_python/. Reports of
> problems would appreciated.
> 
> If you want to try an online P{ython tool that lets you save code, try
> Devan L's at http://www.datamech.com/devan/trypython/trypython.py.
> 
>   http://mail.python.org/mailman/listinfo/python-list


Re: [OT] - Requesting Comments for Process Definition and Presentation

2006-01-06 Thread Xavier Morel
Ilias Lazaridis wrote:
> b) to retrieve feedback subjecting the Process Definition itself 
> (content of diagramms, clarity, terminology etc.)
> 
This is a lie, and you know it.

You are merely some kind of strange troll. You've built something that 
you consider the only "object model" worth using within your mind and 
proceed to try bashing OO languages such as Py or Ruby because they 
don't fit your own object model and terminology.

No one in either c.l.p or c.l.r need you, no one wants your object 
model, no one wants your so-called evaluations (especially about the 
community leaders, your various comments about both Guido van Rossum and 
Yukihiro "Matz" Matsumoto are insulting and disrespectful), please do 
everyone a favor: create your damn own language, or head over to 
comp.lang.lisp and implement your object model in this language, Lisp is 
a meta-language and _nothing_ stops you from heading over and creating a 
new object model from scratch (that's been done countless times anyway, 
and the CLOS probably wouldn't fit your personal object model, so go ahead).

The fact is that you don't live in reality, you generate more buzzwords 
and empty acronyms than a well-trained marketroid, but guess what? that 
doesn't matter, unless you can prove that what you advocate _works_.

And you can't.

Both Ruby's object model and Py's object models work. They have flaws, 
they evolve, they grow and change, but they work, they are used in real 
world situations and they fit the needs of their respective communities. 
"Ilias Lazaridis Majic Object Model" doesn't. Period.

Just stop posting altogether, implement your damn blasted object model 
(or try to) in an existing language or create a new language to 
implement it and just leave us.


And stop spamming your damn worthless website too. Thank you very much.

>> I can't see anything at this site what would make sense to me.
> 
> you mean, you don't understand _anything_?
> 
No, he means that your website just doesn't make sense. There is no 
purpose, no consistency, no way to understand what the website is 
supposed to hold, no way to find *informations* (and your colorful 
graphs with an informative level of somewhere below 0 do not count as 
information BTW).

I'll add that the color/style schemes are awfully misleading (why the 
hell are random words in bold-ocre, please go read a few books on 
interfaces and websites creation because you obviously don't have a clue 
there, Steve Krug's "Don't Make Me Think" would be a much required 
start), that the various categories are unclear, fuzzy and *never 
explained anywhere* and that you claiming that you can *review websites* 
(for a fee on top of that) is insulting to people with actual skills in 
the field.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python or Java or maybe PHP?

2006-01-06 Thread Xavier Morel
Mike Meyer wrote:
> That doesn't sounds like "hates" to me. More like "doesn't like the
> baggage."
> 
> >> # Current behavior
 >>> def foo(*args, **kwargs):
pass
 >>> print foo


 >>> # Extended behavior
 >>> # returns a reference to the function
 >>> def foo(*args, **kwargs):
pass

 >>>
 >>> # Anonymous functions
 >>> def (*args, **kwargs):
pass

 >>> foo = def(*args, **kwargs): pass


Note that the function wouldn't "have" it's own name anymore (no more 
"__name__" attribute? Or a blank one?)

Since functions can already be defined inline, the only thing that'd be 
left would be to end the function's definition when the "wrapper" 
structure ends:

 >>> doSomething(def (*args, **kwargs): pass, arg) # End of the function 
definition at the end of it's argument
 >>> doSomethingElse(def (*args, **kwargs):
... # Multiline
... pass
...)

I'm not too sure about the multi line version (and it looks very ugly 
with a non-monospaced font), but:

Pros (I think):
 * Backwards-compatible (I think, since the new uses of `def` are 
currently errors)
 * Fairly obvious syntax
 * No `lambda` or `macros` baggage, the new form of def would merely 
define an anonymous function instead of a named one.
 * No new keyword, or structure, or idiom
 * Existing idioms are merely slightly extended without changing 
their current meaning

Cons:
 * May reduce readability when misused, and may be used in Very 
Stupid Ways that reduce readability a lot (but then again most construct 
may be abused in some way), e.g.:

 doSomething(arg1, arg2, arg3, def foo(a): manipulate(a)) # 
binds a function to `foo` _and_ sends it to `doSomething`
 ...
 [a few lines of code]
 ...
 foo(value) # where the hell did that "foo" come from?

 * Replaces lambdas with something much more powerful, which may go 
against the goal of getting rid of lambdas (unless the aforementioned 
goal is mostly because of the historical baggage of lambdas/macros)

Unsure:
 * Shows that Python is the Ultimate Language, people are not ready yet.
 * May allow for blocks-like constructs (I'm not sure of the current 
state of the closures over Python functions though, these may have to be 
extended to "full" closures if they aren't) and be considered by some as 
yielding to the hype (even though the structure itself is more or less 
35 years old)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One-step multiples list generation?

2006-01-06 Thread Xavier Morel
Damien Wyart wrote:
> Thanks for these important and useful additions, they are very welcome !
> 
> In writing my answer I had immutables in mind, but mutables are a bit
> more dangerous, here...
> 

Not *that* much though.

The first construct can't be used, but he can use

 >>> [copy.copy(Foo) for _ in range(20)]

And he should be ok.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translate this to python?

2006-01-06 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> For some reason, ocassionally when  I see xrange, I think "But wasn't
> that deprecated  since range is now a . . oh wait that's xreadlines".
> xrange is a  cool thing the few times where you really need it.
> 
> john
> 
>> Not sure what i is really for, but j seems to be independent,
>> so perhaps (also untested, and caveat: it's past bedtime)
>>
>> i = nPoints - 1
>> for j in xrange(nPoints):
>> # whatever
>> i = j
>>
>> Regards,
>> Bengt Richter
> 
I think that xrange is also soon-to-be deprecated (xrange eats a little 
less memory and is slightly faster to _create_, but much slower to 
_iterate over_ than range)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance problem?

2006-01-06 Thread Xavier Morel
Pierre Barbier de Reuille wrote:
> Well, I would even add : don't use super !
> Just call the superclass method :
> 
> MyClass.__init__(self)
> 
> 
> 
> Simon Percivall a écrit :
>> Don't use self.__class__, use the name of the class.
>>
Bad idea if you're using new-style classes with a complex inheritance 
hierarchy and multiple inheritance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: inline function call

2006-01-06 Thread Xavier Morel
Peter Hansen wrote:
> Riko, any chance you could post the final code and a bit more detail on 
> exactly how much Psyco contributed to the speedup?  The former would be 
> educational for all of us, while I'm personally very curious about the 
> latter because my limited attempts to use Psyco in the past have 
> resulted in speedups on the order of only 20% or so.  (I blame my 
> particular application, not Psyco per se, but I'd be happy to see a 
> real-world case where Psyco gave a much bigger boost.)
> 
> Thanks,
> -Peter
> 

Someone I know created an application to compute Markus Lyapunov 
fractals (aka heavy mathematical computations) (he pretty much did it to 
learn Python).

Last time I checked, his code ran in roughly 3 minutes (179s) on my box 
(Athlon64/3000+) without psyco and 46 seconds with psyco enabled under 
Windows 2000.

Someone else got respectively 2mn34s and 13s (without and with psyco) on 
a Linux box with an Athlon XP 2600+ (same frequency as my 3200+ btw, 2GHz).

My tests show a 74% speedup, and the Linux test shows a 91% speedup.

In any case, the gain is significant because the actual code is very 
short (less than 200 lines, and the algorithm itself fits in under 50 
lines) and is called very often (from my notes, the main function is 
called 16 times during the computation of the fractal)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: - E04 - Leadership! Google, Guido van Rossum, PSF

2006-01-06 Thread Xavier Morel
Ilias Lazaridis wrote:
> I estimate that there is a "unfreeze" operation, too - which would lead 
> to flexibity.
> 
There is none, you have to make a copy of the object via the "dup" 
(duplicate) method to get an unfrozen copy (note: clone yields an exact 
copy, which means that it's still frozen).

Unfreezing an object is forbidden in Ruby.

Alex Martelli wrote:
 > At the other extreme, Ruby's very productive choice is to
 > allow freeze and unfreeze of everything (I believe -- but you should
 > double check with a Ruby expert)
I'm no ruby expert, but I'm pretty sure there is no way to unfreeze a 
frozen ruby object, you *have* to create a molten copy with the "dup" 
method.

Ilias Lazaridis wrote:
 > Alex Martelli wrote:
 >> Ilias Lazaridis <[EMAIL PROTECTED]> wrote:
 > [...] - google stuff
 >
 >>> http://lazaridis.com/case/lang/python.html#simple_variable_access
 >>>
 >>> this leads to a new limitation:
 >>>
 >>> "#LIMITATION: large amount of repetitive code"
 >> One normally does not define large numbers of identical accessors (there
 > [...] - (extensive elaboration)
 >
 > possibly one can provide the code for something similar to the ruby
 > attr_accessor:
 >
 > class Talker
 >def sayHello
 >  puts "Hello world"
 >end
 >
 >attr_accessor :name, :age
 >
 > end
 >
 > thus they can later be accessed this way
 >
 > john.age = 19
 >
 > print john.age
 >
There is no point, these exist because a ruby attribute can *never* be 
accessed from outside the object, a Ruby attribute is always private 
while a Python attribute is always public. This means that you *have to* 
declare properties to have the ability to access an attribute of a Ruby 
object, which lead to attr_accessor, attr_reader and attr_writer as 
shortcut-declarations of basic properties.

The Pythonic equivalent of Ruby's attr_accessor is merely to do nothing, 
because what the attr_accessor does is:

attr_accessor :something
generates
def something
@something
end
def something= value
@something = value
end

but not doing it would prevent any access to the "something" attribute.
(attr_reader only declares the getter method, making the attribute 
read-only, and attr_writer only defines the setter, making the attribute 
write-only)

One thing that is very important is that in Ruby you *never* deal with 
member attributes from outside the object, only methods (messages to the 
object).
In Python, you deal either with methods (messages) or attributes 
(datas), but these attributes can be either "real" attributes (real 
unchecked data) or properties, e.g. virtual attributes (that may 
generate side-effects, sanity check on the data, or _may not map to any 
existing unique data in the object_) and unless you really try to, you 
don't have any way to distinguish a "real" attribute from a property 
("virtual" attribute), and you don't care.

 >
 > thus if I make a typo, I create a new attribute?
 >
Why yes of course, what were you expecting?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spelling mistakes!

2006-01-06 Thread Xavier Morel
KraftDiner wrote:
> I've spent hours trying to find a bug that was a simple spelling
> mistake.
> 
> in an init method I declare a variable  self.someLongName
> 
> later in a different method of the class I use
> self.sumLongName
> Now I really meant self.someLongName.
> In fact I don't want a variable called sumLongName.
> Frankly how are you ever to know if this type of error is occuring?
> 

PyChecker and PyLint sound like the perfect remedy to this issue (I know 
one of them is able to warn you if you *create* an attribute outside of 
__init__, maybe both are but at least one of them is)

I just run them when I save my files, they don't take long and even 
though the default configuration is *extremely* annoying (especially 
PyLint's, it generates heaps of warnings) once configured to one's need, 
they're extremely valuable for both personal and team development.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Translate this to python?

2006-01-06 Thread Xavier Morel
Heiko Wundram wrote:
> Xavier Morel wrote:
>> I think that xrange is also soon-to-be deprecated (xrange eats a little
>> less memory and is slightly faster to _create_, but much slower to
>> _iterate over_ than range)
> 
> It might be slower to iterate using xrange, but xrange certainly has its
> place in Python... Try the following on your computer:
> 
> for x in range(10**10):
> print x
> 
> for x in xrange(10**10):
> print x
> 
> Tell me which one doesn't overflow your memory. ;-) And before you come
> telling me that these constraints are articial, I've _written_ programs
> that had to iterate over 2**24 (the set of 10.* IP addresses), and I most
> certainly wouldn't have wanted the machines to contain 384+ MB of RAM just
> to store the number objects that range creates.
> 
> --- Heiko.

While xrange does have it's place in Python, it has very few actual uses 
(yours being one of the few), and is usually more harmful than beneficial.

While the deprecation of xrange is not that "soon", it is part of the 
Python 3000 PEP (http://www.python.org/peps/pep-3000.html#id38) along 
with the deprecation of most FP-facilities of Python (filter, map, reduce).

It should also be noted that reimplementing xrange when needed is 
trivial and can be done with a 5-lines generator for the minimal version 
(1 argument, 0-n range) and probably less than 10 lines for the full 
blown version equivalent to the current one (including start, end and 
step arguments)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python or Java or maybe PHP?

2006-01-06 Thread Xavier Morel
Alex Martelli wrote:
> Xavier Morel <[EMAIL PROTECTED]> wrote:
>...
>> Wouldn't it be possible to change the `def` statement to return a 
>> reference to the function, and allow omitting the function name thereby
>> bypassing the default binding (current behavior)?
> 
> It's _possible_ (doesn't  introduce syntax ambiguities) though it does
> introduce incompatible interactive-interpreter behavior, as you say:
> 
>>  >>> # Extended behavior
>>  >>> # returns a reference to the function
>>  >>> def foo(*args, **kwargs):
>>   pass
>> 
> 
> This could be avoided if 'def ' remained a statement like
> today, and a separate expression 'def' returned a function object
> as a result; this would have the aded plus of avoiding the totally new
> (to Python) idea of "statement returning a value" (_expressions_ return
> a value).
> 
True that, I didn't even consider the possibility to create an 
independent expression.

And it completely remove the possibility to generate the first "con".

>>  * May allow for blocks-like constructs (I'm not sure of the current
>> state of the closures over Python functions though, these may have to be
>> extended to "full" closures if they aren't) and be considered by some as
> 
> Python's closures are 'full', but don't allow inner functions to rebind
> names in the namespace of outer functions.
> 
> I'm not sure a PEP like this has ever been proposed, but the idea of
> anonymous def is not new (bar some details of your proposal): if a PEP
> doesn't exist, you could write one, at least to firm up all details.
> 
> 
> Alex
Or maybe start by creating a thread on the subject of an anonymous def 
expression on this list first?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance problem?

2006-01-06 Thread Xavier Morel
Pierre Barbier de Reuille wrote:
> Xavier Morel a écrit :
>> Pierre Barbier de Reuille wrote:
>>
>>> Well, I would even add : don't use super !
>>> Just call the superclass method :
>>>
>>> MyClass.__init__(self)
>>>
>>>
>>>
>>> Simon Percivall a écrit :
>>>
>>>> Don't use self.__class__, use the name of the class.
>>>>
>> Bad idea if you're using new-style classes with a complex inheritance
>> hierarchy and multiple inheritance.
> 
> As a reference :
> 
> http://fuhm.org/super-harmful/
> 
> I may say this is the only place I ever saw what "super" *really* is
> for. The behavior is far too complex and misthought. All I can say is :
> don't use it ! It solves *nothing* and creates too many bugs in the long
> run.

My own encounter with the subject was Guido's "Unifying types and 
classes in Python 2.2" (http://www.python.org/2.2.3/descrintro.html#mro 
for the part on super itself), but I'll keep your link close by.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python speed

2006-01-07 Thread Xavier Morel
James Tanis wrote:
> Quite honestly I've never heard of java being faster than.. well..
> anything.  Faster than Python? I really doubt it. Their are several
> libraries for game programming specifically as well as opengl, sdl, as
> well as several different audio systems/daemons.. I'd suggest browsing
> through the categories in python.org's module search engine.
> 
> Disclaimer (:P): The majority of generalizations have some amount of
> exceptions, the java crack above was just my opinion - it was not
> really intended to offend any java addicts out there (the poor,
> miss-guided souls).
> 

While java is much slower than Python in developer-time (e.g. the time 
it takes to generate a working app, and the number of lines involved), 
(good) Java code running on the hotspot (JIT) VM is usually at least an 
order of magnitude faster than the equivalent Python code, if not faster.

What's dog slow in Java is primarily the VM startup, and then the memory 
bloating, but as far as execution speed goes, pure Java code is much 
faster than pure Python much more often than the opposite (now that may 
change with Pypy, but Pypy is not done yet)

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


Stackless Python

2006-01-07 Thread Xavier Morel
Some time ago, I finally decided to check what Stackless was (exactly) 
and which were the theorical concepts behind it (continuations and all).

I managed to find some documentations and papers, but most if not all of 
them are related to pre-2.0 Stackless. The issue is, I just can't seem 
to reach the Stackless website (http://stackless.com). Some specific 
pages of the site do work (http://stackless.com/spcpaper.htm), but the 
index itself always yields a 502 gateway error.

Would anyone have more informations about that? It doesn't seem to be an 
issue on my side (since I tried to access the Stackless site from two 
different connections and 3 computers) but I can't rule it out.

I should also note that Google is no good in this case as mostly yields 
fairly old results...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stackless Python

2006-01-07 Thread Xavier Morel
Christian Tismer wrote:
> Xavier Morel wrote:
> 
>> Would anyone have more informations about that? It doesn't seem to be an 
>> issue on my side (since I tried to access the Stackless site from two 
>> different connections and 3 computers) but I can't rule it out.
> 
> Thanks to Carl Friedrich, I restarted the Zope process.
> 
> I have no idea why it broke, the site was running since 38 days
> without problems. The Zope/Plone process was still there, blocking
> the port.
> 
> Maybe I should go for something simpler than Plone...
> 
> Don't hesitate to ask on the mailing list for all the things
> you will not find on the site. The list works :-)
> 
> ciao - chris

Ah yes, much better now, thank you very much

(BTW the first time I got a dead stackless.com was between xmas and new 
year's eve, so the website has probably been down for more than 10 days, 
just so you know, if you want to check your logs or something).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spelling mistakes!

2006-01-09 Thread Xavier Morel
Antoon Pardon wrote:
> I don't think unit tests are that helpful in this case.
> Unit tests help you in finding out there is a bug, they
> don't help that much in tracking down a bug.
> 
> I for some reason a person is reading over the difference
> between sumLongName and someLongName and doesn't notice
> the different spelling in his source a unit test won't
> be of much help.
> 
Since
1- The unit test will obviously fail in this case, telling you in which 
code unit the issue is
2- Unit Test favor extremely modular coding with very short increments 
(as a somewhat extreme example, Robert Martin gets nervous if his test 
suites don't validate the code every 5 minutes, you usually don't write 
200 lines and their unit tests in 5 minutes)

We can deduce that unit testing will detect the typo extremely early and 
that the field of research will span about 5 to 10 lines, making the 
tracking quite easy to perform.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problema con le RE....

2006-01-09 Thread Xavier Morel
Alessandro wrote:
> Problema con le RE
> Ho questa stringa "3 HOURS,  22 MINUTES, and  28 SECONDS" e la devo
> 'dividere' nelle sue tre parti "3 HOURS", "22 MINUTES", "28 SECONDS".
> La cosa mi viene molto con le RE...(inutile la premessa che sono molto
> alle prime armi con RE e Python)
> Qesito perchè se eseguo questo codice
> 
> regex=re.compile("[0-9]+ (HOUR|MINUTE|SECOND)")
> print regex.findall("22 MINUTE, 3 HOUR,  AND  28 SECOND")
> ottengo come output:
> 
>  ['MINUTE', 'HOUR', 'SECOND']
> 
> e non come mi aspettavo:
> 
>  ['3 MINUTE', '22 HOUR', '28 SECOND']
> 
> Saluti e grazie mille...
> Alessandro
> 
Would probably be slightly easier had you written it in english, but 
basically the issue is the matching group.

A match group is defined by the parenthesis in the regular expression, 
e.g. your match group is "(HOUR|MINUTE|SECOND)", which means that only 
that will be returned by a findall.

You need to include the number as well, and you can use a non-grouping 
match for the time (with (?: ) instead of () ) to prevent dirtying your 
matched groups.

 >>> pattern = re.compile(r"([0-9]+ (?:HOUR|MINUTE|SECOND))")

Other improvements:
* \d is a shortcut for "any digit" and is therefore equivalent to [0-9] 
yet slightly clearer.
* You may use the re.I (or re.IGNORECASE) to match both lower and 
uppercase times
* You can easily handle an optional "s"

Improved regex:

 >>> pattern = re.compile(r"(\d+ (?:hour|minute|second)s?)", re.I)
 >>> pattern.findall("3 HOURS 22 MINUTES 28 SECONDS")
['3 HOURS', '22 MINUTES', '28 SECONDS']
 >>> pattern.findall("1 HOUR 22 MINUTES 28 SECONDS")
['1 HOUR', '22 MINUTES', '28 SECONDS']

If you want to learn more about regular expressions, I suggest you to 
browse and read http://regular-expressions.info/ it's a good source of 
informations, and use the Kodos software which is a quite good Python 
regex debugger.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to improve this simple block of code

2006-01-11 Thread Xavier Morel
Mel Wilson wrote:
> py wrote:
>> Say I have...
>> x = "132.00"
>>
>> but I'd like to display it to be "132" ...dropping the trailing
>> zeros...
> 
> print '%g' % (float(x),)
> 
> might work.
> 
>   Mel.
> 
The input is a string, %g expects a float, TypeError exception.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to improve this simple block of code

2006-01-11 Thread Xavier Morel
Forget about the previous mail, i just saw you were converting the 
string to float beforehand, in which case he would more than likely run 
into the good ol' float imprecision issue sooner than later.

Not to mention that %g formats to scientific notation (e.g. exponential 
format with the exponent always being a multiple of 3), he'd probably 
use "%f".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Freezing

2006-01-12 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> The first line of that example has to be:
> 
> s = |set([1, 3, 5])|
> 
> But I don't know/remember why set() can't accept many values like
> max/min:
> 
> max([1,2,5])
> max((1,2,5))
> max(1,2,3)
> 
> Bye,
> bearophile
> 

How about just providing a freeze method on `object` (since everything 
will inherit from object) that can freeze the object?

In fact the freeze protocol could provide 2 methods: freeze and frozen, 
the former would freeze the object in place (e.g. freeze the object it's 
applied to) while the later would return a frozen copy of the object 
it's applied to.

That way, it could even be used as a const-like parameter to a function 
(with frozen)

Examples:
 >>> l = [0, 1, 2, 3]
 >>> l.append(5)
 >>> l
[0, 1, 2, 3, 5]
 >>> l.frozen()
[0, 1, 2, 3, 5]
 >>> fl = l.frozen()
 >>> l.append(7)
 >>> l
[0, 1, 2, 3, 5, 7]
 >>> fl.append(7)
Traceback (most recent call last):
...
WhateverError: frozen 'list' object cannot modified
 >>> fl
[0, 1, 2, 3, 5]
 >>> l.freeze()
 >>> l
[0, 1, 2, 3, 5, 7]
 >>> l.append(9)
Traceback (most recent call last):
...
WhateverError: frozen 'list' object cannot modified

One could even dream of a melt/molten method pair that'd behave at the 
opposite of the freeze/frozen pair (to have the ability to "unfreeze" an 
object if needed)

No new keyword, no new token, no new structure, no new builtin, same 
functionalities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to an array?

2006-01-12 Thread Xavier Morel
Tim Chase wrote:
> The closest hack I could come up with was
> 
>   import random
>   s = "abcdefg"
>   a = []
>   a.extend(s)
>   random.shuffle(a)
>   s = "".join(a)
> 
> This lacks the beauty of most python code, and clearly feels like 
> there's somethign I'm missing.  Is there some method or function 
> I've overlooked that would convert a string to an array with less 
> song-and-dance?  Thanks,
> 
> -tim
> 

Would

 >>> import random
 >>> s = "abcdefg"
 >>> data = list(s)
 >>> random.shuffle(data)
 >>> "".join(data)
'bfegacd'
 >>>

fit you better?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More than you ever wanted to know about objects [was: Is everything a refrence or isn't it]

2006-01-15 Thread Xavier Morel
Alex Martelli wrote:
> Steve Holden <[EMAIL PROTECTED]> wrote:
>...
>>> 3. If two objects are equal with "==", does that
>>>   mean their values are the same?
>> Almost universally, yes, although if you know enough about how the 
>> interpreter works "under the hood" you can define the response of 
>> instances of your own classes to the "==" operator (by defining their
>> __eq__ method), and even define a class whose instances aren't equal to
>> anything, even to themselves!
> 
> Hmmm... now this may be just be, but I'm quite vary of saying that,
> since 1 == 1.0 == 1.0+0j, those three objects's values "are the same".
> 
> "Are equal", sure.  But I intuitively see "being the same" as a stronger
> condition than "being equal".
> 
One could check use Common Lisp's "=", "eq" and "eql" operators (which 
respectively check for "being equal" as in "having the same set of 
values", "being very equal" as in "having the same set of values and the 
same type" and "being the same" as in being exactly the same object e.g. 
identity equality)

> In mathematics, 1 is not "the same" as 1.0 -- there exists a natural
> morphism of integers into reals that _maps_ 1 to 1.0, but they're still
> NOT "the same" thing.  And similarly for the real-vs-complex case.
> 
I disagree here, 1 and 1.0 are the same mathematical object e.g. 1 (and 
the same as "1+0i"), the difference due to notation only makes sense in 
computer science where integers, real and complex ensembles are disjoin. 
In mathematics, Z is included in IR which is included in C (note: this 
is not mathspeak, but I have no idea how to say it in english), and this 
notation -- at best -- merely determines the ensemble you're currently 
considering.

There is no "natural morphism" of integers into reals because there is 
no mathematical difference between integers and reals, the real ensemble 
is merely a superset of the integers one.

Or so it was last time i got a math course.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance attributes not inherited?

2006-01-16 Thread Xavier Morel
John M. Gabriele wrote:
> I'm having a hard time finding the documentation to the super() function.
> I checked the language reference ( http://docs.python.org/ref/ref.html )
> but didn't find it. Can someone please point me to the relevant docs on
> super?
> 
> help( super ) doesn't give much info at all, except that super is actually
> a class, and calling it the way we are here returns a "bound super object",
> but I don't yet see what that means (though I know what bound methods are).
> 

Super is a bit magic, quite complicated, and some people don't like it 
(basically, super is mainly to be used in complex inheritance case with 
diamond shape hierarchies and such, to automate the method resolution 
order).

If you want to give a try at understanding "super", you should read 
Guido's `Unifying types and classes in Python 2.2`, chapters on MRO, 
super and cooperative methods 
(http://www.python.org/2.2.3/descrintro.html#mro) (nb: you may also read 
the rest of the document, it lists all the magic introduced in the 
language with 2.2).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arithmetic sequences in Python

2006-01-16 Thread Xavier Morel
Paul Rubin wrote:
> There's something to be said for that.  Should ['a'..'z'] be a list or
> a string?
To me, the most obvious result would be either a range object as a 
result, or always a list/generator of objects (to stay perfectly 
consistent). If a range of numbers translate into a list of numbers, 
then a range of characters should likewise translate to a list of 
characters, and a join would be required to get a regular string. This 
also adds more consistency between the two proposals of the initial post 
(e.g. list-based range and generator-based range), for while the 
list-based range could be expanded into a string a generator-based one 
couldn't/shouldn't, and the abstraction breaks (because two constructs 
that should be more or less equivalent become extremely different and 
can't be swapped transparently).

This would also be consistent with other languages providing a native 
"range" object such as Ruby or or Ada ranges.

The only thing that bothers me about the initial proposal is that there 
would not, in fact, be any "range object", but merely a syntactic sugar 
for list/generator creation. Not that I really mind it, but, well, 
syntactic sugar for the purpose of syntactic sugar really doesn't bring 
much to the table.

For those who'd need the (0..n-1) behavior, Ruby features something that 
I find quite elegant (if not perfectly obvious at first), (first..last) 
provides a range from first to last with both boundaries included, but 
(first...last) (notice the 3 periods) excludes the end object of the 
range definition ('a'..'z') is the range from 'a' to 'z' while 
('a'...'z') only ranges from 'a' to 'y').
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: excellent book on information theory

2006-01-16 Thread Xavier Morel
Tim Peters wrote:
> Non-English translations have real challenges, and because this series
> is more popular than the Python Reference Manual these days, there's a
> lot of fascinating info to be found.  For example, I think the
> Japanese translator deserves a Major Award for their heroic attempt to
> translate Ron's "Uranus" pun:
> 
>http://www.cjvlang.com/Hpotter/wordplay/uranus.html
> 

The translations of Pratchett's works are also quite amazing feats. I 
think that when they were looking for a polish translator one of the 
people they auditioned told them something along the lines of "You can't 
even think like this in polish."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arithmetic sequences in Python

2006-01-16 Thread Xavier Morel
Steven D'Aprano wrote:
> On Mon, 16 Jan 2006 12:51:58 +0100, Xavier Morel wrote:
> 
>> For those who'd need the (0..n-1) behavior, Ruby features something that 
>> I find quite elegant (if not perfectly obvious at first), (first..last) 
>> provides a range from first to last with both boundaries included, but 
>> (first...last) (notice the 3 periods) 
> 
> No, no I didn't.
> 
> Sheesh, that just *screams* "Off By One Errors!!!". Python deliberately
> uses a simple, consistent system of indexing from the start to one past
> the end specifically to help prevent signpost errors, and now some folks
> want to undermine that.
> 
> *shakes head in amazement*
> 
> 
Steven, I never said that Python should use this syntax, I merely showed 
how it was done in Ruby.

It's nothing more than a ... basis of discussion... not a "I want that 
!!ONE" post (if I did, i'd be using Ruby and posting on c.l.r)

(and you didn't what by the way?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arithmetic sequences in Python

2006-01-16 Thread Xavier Morel
Steven D'Aprano wrote:
> On Mon, 16 Jan 2006 12:51:58 +0100, Xavier Morel wrote:
> 
>> For those who'd need the (0..n-1) behavior, Ruby features something that 
>> I find quite elegant (if not perfectly obvious at first), (first..last) 
>> provides a range from first to last with both boundaries included, but 
>> (first...last) (notice the 3 periods) 
> 
> No, no I didn't.
> 
> Sheesh, that just *screams* "Off By One Errors!!!". Python deliberately
> uses a simple, consistent system of indexing from the start to one past
> the end specifically to help prevent signpost errors, and now some folks
> want to undermine that.
> 
> *shakes head in amazement*
> 
> 
Steven, I never said that Python should use this syntax, I merely showed 
how it was done in Ruby.

It's nothing more than a ... basis of discussion... not a "I want that 
!!ONE" post (if I did, i'd be using Ruby and posting on c.l.r)

(and you didn't what by the way?)

Ok scratch that, you didn't notice the 3 periods.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forced spaces when inserting a variable between strings

2006-01-17 Thread Xavier Morel
mjteigen wrote:
> I'm very new at Python, but have been trying it in conjunction with
> CGI. I've encountered a problem that I'm pretty sure is a trivial one,
> but I don't know enough Python to work it out. Here's an example.
> Imagine that I have a file named "5.jpg" in the same directory as this
> Python script:
> 
>print "content-type: text/html\n"
>number = 5
>print ""
> 
> My goal is print out ''. However, when I view the
> source on the generated html page, I see this:
> 
>
> 
> In other words, that "5" has a space tacked on either side of it, and
> of course a browser can't find the file. Is there a way I can avoid the
> tacking of spaces on either side of a variable inserted between two
> strings?
> 
> TIA :-)
> --
> m j teigen
> 
1- Use sys.stdout.write(), it doesn't add any kind of formatting to the data
2- You may also use string interpolation, either in sys.stdout.write or 
in print
3- I'd suggest you to use a templating system in order to separate the 
displayed data and the retrieval/computations of said data, and prevent 
from mixing logic and presentation in your scripts (which always leads 
to an unmaintainable system)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arithmetic sequences in Python

2006-01-17 Thread Xavier Morel
Paul Rubin wrote:
> I don't think this is a valid objection.  Python is already full of
> syntactic sugar like indentation-based block structure, infix
> operators, statements with keyword-dependent syntax, etc.  It's that
> very sugar that attracts programmers to Python away from comparatively
> sugarless languages like Scheme.  Indeed, Python is considered by many
> to be a sweet language to program in, and they mean that in a nice
> way.
> 
> If you want, you can think of it as "flavor" rather than "sugar".  We
> aren't after syntactic minimalism or we'd be using Scheme.  The
> criterion for adding something like this to Python should be whether
> makes the language taste better or not.

I don't know, most of the syntactic sugar I see in Python brings 
something to the language, or trivialize the generation of structures 
and constructs that may be complex or awkward without it, it has a 
natural, honey-ish sweetness full of flavor, it does not taste like some 
cancer-spawning artificial sweetener ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate graphics dynamically on the web using Python CGI script?

2006-01-20 Thread Xavier Morel
Steve Holden wrote:
> Debashis Dey wrote:
>> Hello,
>>  
>> I have a python CGI program. I would like to show a graph within a HTML 
>> plage. I would like to dynamically generate the graph using the python 
>> CGI script on the web server side and send it to the browser.
>>  
>> My question is how can I do this in python? Is there a free tool to do 
>> this? Can someone please send me some simple python code to draw simple 
>> graphics within HTML (e.g. draw a line or a circle).
>>  
> Unfortunately HTML does not include graphics facilities, simply the 
> ability to refer to graphical resources.
> 
> The typical way to include a created graphic would be:
> 
>   1. Create a (.png, .jpg, .gif) file showing the
>  image you want
> 
>   2. Store it in a temporary file whose name will be
>  unique to the current session
> 
>   3. Generate an HTML response including an 
>  tag referring to the newly created graphic
> 
> Step 1, which is what you seem to be asking about, can be handled by a 
> number of packages, perhaps the best-known of which is PIL, the Python 
> Imaging Library - see
> 
>http://www.pythonware.com/products/pil/
> 
> This is open source, and available at no cost. There's a wealth of 
> information on how to use it on the web, and many regular readers of 
> this group are skilled with it!
> 
> regards
>   Steve

Well, some people have been crazy enough lately to generate more or less 
imageless bar graphs though, see Eric Meyer's "Bar Graphs with Style" 
(http://meyerweb.com/eric/thoughts/2005/12/20/bar-graphs-with-style/) 
for more informations on the subject 
(http://meyerweb.com/eric/css/edge/bargraph/demo.html for a demo)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate graphics dynamically on the web using Python CGI script?

2006-01-20 Thread Xavier Morel
Steve Holden wrote:
> Luiz Geron wrote:
>> I don't have experience on this, but I think that you can make the
>> script return the image "contents" directly to the img tag, without
>> passing it to a img file, so you can use something like this:
>>
>> 
>>
>> wich saves some processing and I/O.
>>
> No it doesn't, because the script that generates the graphic is then a 
> different script from the one that generates the referring HTML. I agree 
> that scripted generation of the graphical content is a viable option 
> that I overlooked, though it seems from the OP's inquiry that he already 
> uses CGI to generate the HTML.
> 
> regards
>   Steve

Generate inline base64 encoded images in your HTML page and you're done.
(yes, this is ugly, but it generates both HTML and graphics in the same 
script)
-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE Problem in Windows XP

2006-09-15 Thread ELATTAOUI Xavier



Hi,
 
I have encountered 
the same problem so you can try the following :
 
- Be sure your 
%PYTHONPATH% is set
- open a DOS console 
and type : "python C:\Python23\Lib\idlelib\idle.py"
-> this will 
launch the IDLE
- then choose 
"configure IDLE" in Options menu
- in the menu 
"Highlighting" on right part, choose "IDLE Classic" and 
apply
- close all and try 
to launch now the IDLE
 
This is what I have 
done and now it works (don't ask me why !!).
 
Hope this 
help,
Xavier
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Converting date to milliseconds since 1-1-70

2006-01-26 Thread Xavier Morel
NateM wrote:
> Thank you!  If I am reading in dates as strings from a text file, like
> "5/11/1998", how do I convert that to a format I can pass into mktime?
> Thanks again.
> 
Check time.strptime()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decoupling the version of the file from the name of the module.

2006-01-28 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> I'm a newbie experimenting with Python. I want to incrementally develop
> a module called 'circle'. The problem is now that the file name is used
> for two purposes. To keep track of the version number and as the name
> for the module. So when I develop the first version of my file I have
> to call it circle_a.py. The name of the module then automatically
> becomes circle_a. But when I develop the next increment and call my
> file circle_b.py the module name changes as well.
> 
> Basically I want to decouple the version of my file from the name of
> the module.
> 
> Is there a *simple* way out of this dilemma.
> 

You have two choices:

1- Just get rid of the version number in the name (what's the point) and 
define a __version__ attribute in the module, that's what is usually done.
2- create a wrapper module called "circle.py" whose content will be 
something along the lines of "from your_current_module_with_version 
import *"

I'd strongly suggest the first choice, there is no point in giving the 
version number into the file name of a module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decoupling the version of the file from the name of the module.

2006-01-29 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> Now suppose I have make a new version with __version__ = 1.1. What
> shall I call this file and (I don't want to overwrite the old file if I
> need to go back to it) how do I import it from the shell. Your advice
> sounds nice, but I would appreciate if you could give me (or point me
> to) a simple example.
> 
> Thanks
> 

As Kirk, Roy and Peter suggested (nay, commanded), use a versioning 
system, either CVS or Subversion for example (both are quite simple, 
Subversion has a 1 click installer for Windows boxes, and there is a 
small book/user manual with it so that you're not lost), they'll do what 
you need (keep the old versions around "just in case") and much more to 
boot. Spending a day or two learning about how the versioning system 
you'll have chosen work is an investment that you'll get back tenfold in 
no time, so don't get intimidated or scared.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about idioms for clearing a list

2006-01-31 Thread Xavier Morel
Steven Watanabe wrote:
> I know that the standard idioms for clearing a list are:
> 
>   (1) mylist[:] = []
>   (2) del mylist[:]
> 
> I guess I'm not in the "slicing frame of mind", as someone put it, but 
> can someone explain what the difference is between these and:
> 
>   (3) mylist = []
> 
> Why are (1) and (2) preferred? I think the first two are changing the 
> list in-place, but why is that better? Isn't the end result the same?
> 
> Thanks in advance.
> --
> Steven.

The solution (1) and (2) clear the content of the list (replace the 
content of the list by an empty list for (1), or delete the content of 
the list for (2) while the solution (3) creates a new list and binds the 
old name to the new list. This means that you don't actually modify 
(clear) the initial list.

Just try it out:

 >>> a = range(10)
 >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> b = a
 >>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> c = a
 >>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> a.append(10) # assert that a, b and c point to the same list
 >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> b = []
 >>> b
[]
 >>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> del c[:]
 >>> c
[]
 >>> a
[]
 >>>

Here we can see that using method (3) on b didn't modify the content of 
a (even though we asserted that they were the same list).
Using method (2) on c, the other hand, did modify the content of a.

This is because method (3) on b actually created a new list and bound 
"b" (as a name) to that new list, without modifying the list "b" used to 
be bound to (which is the one "a" and "c" are still bound to).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classmethod and instance method

2006-02-02 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I'm trying to write a method that needs to know both the class name and
> the  instance details
> 
> Any suggestions?
> 

What's the point of using a classmethod and an explicit cls argument 
when you can get the class object from the instance itself?

 >>> class Test(object):
def meth(self):
print self
print self.__class__
print type(self)


 >>> test = Test()
 >>> test.meth()
<__main__.Test object at 0x00FA1710>


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


Re: Python on Windows

2006-02-03 Thread Xavier Morel
Simon Faulkner wrote:
> I've just written my first (simple) WxPython program - yy!
> 
> What would folks suggest is the easiest way to package it to run on 
> other windows PCs?
> 
> I would love a single .exe file that would run without ANY OTHER FILES 
> even if it was 50 Mb!
> 
> TIA
> 
> 
> Simon

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


Re: classmethod and instance method

2006-02-03 Thread Xavier Morel
[EMAIL PROTECTED] wrote:
> Yes that's better.  Didn't know about the __class__ attribute.  I
> thought there must be a way to access this but couldn't find it in the
> docs.
> 
> Thanks,
> 
> Andy
> 
dir(), help() and the interactive interpreter (IDLE or CLI) are your 
best friends.

Any time you wonder what an object does, or if you do something to an 
object, fire the interpreter, create your object, abuse it via 
dir/help/whatever, and then use dir/help/whatever on the results of 
dir'ing your object.

Oh, and use new style classes too (explicitly inherit from `object` or a 
built-in type), they are much more flexible and interesting than 
old-style classes

 >>> class Test: # old style class
pass

 >>> test = Test()
 >>> dir(test) # are completely uninteresting
['__doc__', '__module__']
 >>> class Test(object): # new style classes on the other hand
pass

 >>> test = Test()
 >>> dir(test) # have 2500% more sexyness
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', 
'__hash__', '__init__', '__module__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python on Windows

2006-02-04 Thread Xavier Morel
Grant Edwards wrote:
> Definitely.  Nobody does single .exe file windows programs
> anymore.  A single-file installer is almost as easy.
> 
uTorrent, Process Explorer or Media Player Classic are single .exe 
windows programs.

Granted, most of them are under-150kb-works-of-arts, but MPC isn't (well 
it's a work of art, but it's well over 5Mb now), but even then, some 
people STILL do single .exe windows programs, and some of these are the 
best programs in their fields (utorrent certainly is one of the best 
Torrent programs on windows, and it clearly has the very best 
features/exe size and features/ram consumption ratios, and I haven't 
seen anything that could even remotely close on to Process Explorer, 
RegMon or FileMon)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re.search slashes

2006-02-04 Thread Xavier Morel
Scott David Daniels wrote:
> pyluke wrote:
>> I'm parsing LaTeX document and want to find lines with equations blocked 
>> by "\[" and "\]", but not other instances of "\[" like "a & b & c \\[5pt]"
>> so, in short, I was to match "\[" but not "\\]"   I've tried:
>> check_eq = re.compile('(?!\%\s*)\[')
>  > check_eq.search(line)
>  > this works in finding the "\[" but also the "\\["
> 
> If you are parsing with regular expressions, you are running a marathon.
> If you are doing regular expressions without raw strings, you are running
> a marathon barefoot.
> 
> Notice:  len('(?!\%\s*)\[') == 13
>   len(r'(?!\%\s*)\[') == 15
> 
>> so I would think this would work
>> check_eq = re.compile('(?![\%\s*])\[')
>> check_eq.search(line)
>>
>> but it doesn't.  Any tips?
> Give us examples that should work and that should not (test cases),
> and the proper results of those tests.  Don't make people trying to
> help you guess about anything you know.
> 
> --Scott David Daniels
> [EMAIL PROTECTED]

To add to what scott said, two advices:
1. Use Kodos, it's a RE debugger and an extremely fine tool to generate 
your regular expressions.
2. Read the module's documentation. Several time. In your case read the 
"negative lookbehind assertion" part "(?http://mail.python.org/mailman/listinfo/python-list


Re: Importing a class, please help...

2006-02-05 Thread Xavier Morel
anon wrote:
> Would somebody please drop me a hint, please?
> 
Yeah, the definition of "JAR" is Java ARchive, why the hell would a 
Python script be able to read a JAR in the first place (truth is it is, 
a JAR file is nothing but a renamed ZIP, therefore the zipfile module 
allows you to read it's content) and -- more importantly -- import Java 
classes.

Notice the difference between *Python* script and *Java* class? That's 
because they're two different languages.
If you want to use Java classes and modules in a Pythonic context, you 
want Jython (http://www.jython.org/) not Python (http://www.python.org/)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2006-02-05 Thread Xavier Morel
Byte wrote:
> x = input(raw_input("Please enter your name: "))
> if x==myself: print 'OK'
> 
> It kinda works - I can get to the please enter your name bit but then
> it simply reprints your input as output. Someone please HELP!
 >

-->
C:\>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> help(input)
Help on built-in function input in module __builtin__:

input(...)
 input([prompt]) -> value

 Equivalent to eval(raw_input(prompt)).

 >>> help(raw_input)
Help on built-in function raw_input in module __builtin__:

raw_input(...)
 raw_input([prompt]) -> string

 Read a string from standard input.  The trailing newline is stripped.
 If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise 
EOFError.
 On Unix, GNU readline is used if enabled.  The prompt string, if given,
 is printed without a trailing newline before reading.
<--

Where the hell did you get the idea of stacking input on a raw_input in 
the first place?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2006-02-05 Thread Xavier Morel
Byte wrote:
> p.s. Xavier Morel, you seem to be using Windows, not Linux
> 
I don't see how this may even remotely be relevant, Python is cross 
platform and (mostly) works the same regardless of the OS

 > I got
 > the idea of stacking input on a raw_input from the official Python
 > Tutorial.
 >
Reference please, I never saw that anywhere in the tutorial
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2006-02-05 Thread Xavier Morel
Byte wrote:
> http://docs.python.org/tut/node6.html#SECTION00610
> 
-->
 >>> x = int(raw_input("Please enter an integer: "))
<--

Unless my eyes fail me, it's written "int", not "input", the goal of 
this line is to convert the return value of raw_input (a string) into an 
integer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2006-02-05 Thread Xavier Morel
Byte wrote:
> Assumption. Im also new to programing, so could do something stupid
> like think a Windows path is a command/input/etc. (really, ive done
> things like that before.)
> 
Don't assume anything when you have no reason to, and especially don't 
assume that a cross-platform programming language behaves differently 
from a platform to another, especially on built-in basic functions

> Now, im running this on a terminal, but am acctually writing my scripts
> in a text editor. How can I get a script to do a sum with the editor?
> e.g. it asks for a sum, then does it etc.
> 
parse the expression, extract the operands and the operation, apply the 
operation to the operands (are you trying to code a calculator?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2006-02-05 Thread Xavier Morel
Byte wrote:
>> parse the expression, extract the operands and the operation, apply the
> operation to the operands
> 
> How? Give me some example code, but please keep it simple.
> 
>> are you trying to code a calculator?
> 
> Not intending to, just trying to learn Python. Suppose what i'm trying
> to code is a but like a CLI calculator, but i'm just writing it for my
> own educational beifits.
> 

Side note: have you read Dive into Python (http://diveintopython.org/) 
yet? If you haven't -- and are done reading the whole python tutorial -- 
you should, it's a very good and practical read.

Now about the calculator, let's do a simple RPN notation (they're much 
simpler to compute than the "regular" notation, see 
http://en.wikipedia.org/wiki/RPN for some informations about RPN)

First, we need an input

-->
expression = raw_input("> ")
<--

Now we need to handle this input. An RPN expression is a space-separated 
list of tokens, these tokens being either operands (numbers) or 
operations. This means that we merely need to split our expression at 
the spaces

-->
expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default 
split delimiter
<--

Now we have a list of tokens.

RPN calculations involve a stack, to keep the current operands. Python's 
`list` has everything you need to emulate a stack

-->
expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default 
split delimiter
stack = list()
<--

Now, we have to handle each token.
Either a token is a number (an operand), in which case we have to 
convert it to an integer (it's currently stored as a string), or it's an 
operation, in which case we have to apply the operation on the last two 
tokens of the computation stack and store the result back on the stack.

This means that we have to store addition, substraction, multiplication 
and division. Luckily, there is the python module `operator` that stores 
an accessor to these operations (add, sub, mul, div). We could store 
them in a dictionary with an operation token as index: we feed the 
operation token to the dict, it outputs the operation function.

-->
import operator

operations = {
 "+": operator.add,
 "-": operator.sub,
 "*": operator.mul,
 "/": operator.div
}

expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default 
split delimiter
stack = list()
<--

Good, now all we need to know is to feed each token to the `operations` 
dict, let's try with the first token of the RPN expression "1 2 + 4 * 3 +"

 >>> operations['1']

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 operations['1']
KeyError: '1'

Well, there is no "1" key in our dictionary, so we get an error. Kind of 
obvious.
The Python dictionaries also have a "get" method that takes a key and a 
value, and they return the value (default) if the key doesn't exist, how 
would that one fare?

 >>> operations.get('1',None)
 >>> operations.get('2',None)
 >>> operations.get('+',None)

 >>>

Ok, it's return the operation function if it knows the token we feed it, 
and "None" if it doesn't.
Now all we have to do is check if it returns None, and if it does we 
know it's an operand and not an operation.

First we need to loop on the list of tokens:

-->
import operator

operations = {
 "+": operator.add,
 "-": operator.sub,
 "*": operator.mul,
 "/": operator.div
}

expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default 
split delimiter
stack = list()

for token in tokens:
 operation = operations.get(token, None)
 if operation: # If operation is not "None", therefore if the token 
was an operation token
 pass # do nothing for now
 else: # if operation is "None" == if the token is an operand token
 pass # do nothing either
<--

Ok, what are we supposed to do if the token is an operand? Convert the 
operand (token) to an integer (the token is a string), and then add it 
to our computational stack.
The last part is done via the `append` methods of  Python's list.

If the token is an operation, we have to apply the operation to the last 
two operands of the stack, and push the result back on the stack
To get the last operation of a Python list, we use the `pop`method, it 
defaults to returning the last value of a list.

-->
import operator

operations = {
 "+": operator.add,
 "-": operator.sub,
 "*": operator.mul,
 "/": operator.div
}

expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default 
split delimiter
stack = list()

for token in tokens:
 operation = operations.get(token, None)
 if operation: # If operation is not "None", therefore if the token 
was an operation token
 result = operation(stack.pop(), stack.pop()) # apply the 
operation on the last two items of the stack
stack.append(result) # put the result back on the stack

Re: Importing a class, please help...

2006-02-05 Thread Xavier Morel
Jorgen Grahn wrote:
 > You are rude to an obvious newbie here ... please keep in mind that 
today's
 > stupid newbies are tomorrow's Python professionals.
 >
I didn't mean to be rude and apologize if that's the way it came out.

> Maybe he /is/ running Jython and failed to explain that properly?
 >
No, he explicitely stated that he's using Python 2.4 (I'm pretty sure 
Jython's latest release is 2.1) and SPE (which didn't handle Jython last 
time I tried it)

> If I
> understand things correctly, jar files are not tied to Java but to the java
> bytecode format -- which Java and Jython share.
> 
Yes, it's used to store/package compiled java classes (.class bytecode 
files) and various metadata associated to the classes (resources, ...) 
and therefore tied to the bytecode (or the JVM) indeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2006-02-05 Thread Xavier Morel
Byte wrote:
> I asked to keep it simple! Anyway, ill try Dive into Python, thanks
> 
It is simple, merely explicit and with some details.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: translating PHP to Python

2006-02-05 Thread Xavier Morel
Dave wrote:
> Anyone familiar with PHP? I'm trying to make a translation. In PHP you
> can get the current object's name by going like this:
> 
> get_class(item) == 'ClassName'
> 
> I've tried type(item), but since I can't be sure if I'll be in __main__
> or as a child object, I can't guarantee what that value will return, so
> I can't just manipulate that value as a string.
> 
Type doesn't return a string, it returns a reference to a class object.

You look like you want to test if the class of an object is . For that purpose, check isinstance.

> Is there a simple way to get the current object's name? You would think
> __name__ would work, right? It doesn't.
> 
What do you call "the current object's name"? A python object usually 
has no name per se (only functions and classes do have one I think).

> Now here's  another, similar one:
> 
> You can reference an object's parent object directly in PHP, like so:
> 
> //note the charming use of semi-colon. isn't it cute?
> parent::__construct(
> $stuffInAWeirdSyntaxThatDoesntMeanAnythingWhenYouReadIt);
> 
> I'd like to avoid passing a reference to an object's parent in
> __init__, but is there a built in way in Python to say "You, Parent
> Object, do ...stuff!"
> 
> Thanks!
> 
I guess it's a parent in the inheritance meaning of the term. If so, you 
can use either the call-by-class syntax or the `super` construct.

For the call-by-class, see the Python tutorial, chapter 9.5 
"Inheritance", last paragraph. For the `super` construct, check the help 
on the subject, and the document "Unifying types and classes in Python 
2.2" by the BDFL (http://www.python.org/2.2.3/descrintro.html)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dual Core outlook

2006-02-07 Thread Xavier Morel
malv wrote:
> Of course, multiprocessing has been used for many years but this always
> involved a much higher level of sophistication on the part of the
> designers. This point seems to be largely hidden from the public,
> ignorant and semi-ignorant, by the chip manufacturers.
> Will new languages see the light rendering the spreading of
> applications over many processors quasi transparent?
> What is the outlook for Python? Would Ironpython with .net do better?
> What about talk by the Java lobby that Java would be very much suited
> for taking advantage of dual-core? Is there any thruth to this?
> 
Python has support for OS threads, but it also has the GIL (a global 
lock from the interpreter). This means that Python behaves the same way 
Java or C# do as far as threads are concerned but for one field: 
multiprocessor (or multicore) situations.

While C# or Java can execute two threads of the same process on two 
separate cores/processors Python can't.

This means that you can't choke a multiprocessor/multicores machine with 
Python threads, and that if you want to scale in a 
multiprocessor/multicore environment (e.g. make use of all the available 
cores/processors) you have to use processes not threads (e.g. you have 
to launch multiple instances of the Python interpreter, each one having 
the ability to execute on a different core/processor).

Now the question is: do you want to do it? Do you have several extremely 
demanding computational threads? If yes, then Python probably isn't what 
you need (unless you implement your computations in specific C modules 
and get rid of the GIL issue). If not (a single computational thread and 
several low-resources GUI/network/whatever threads), it's a non-issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   >