Re: Data available on socket?

2005-07-22 Thread Nicolas
Jan Danielsson a écrit :
> Hello all,
> 
>How do I find out if a blocking socket has data available [for
> reading] on it?
> 
> I assume I could do something like this:
> 
> tmp = self.read(1, socket.MSG_PEEK)
> if len(tmp) > 0:
># Data available
> 
>But is there a better way? A call which specifically checks if data
> is available?

Hello,

You might want to use select.select.
See http://effbot.org/librarybook/select.htm for an example with sockets.

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


clicking on turtle

2012-11-06 Thread Nicolas Graner
I have a problem with the standard "turtle" module. When a turtle has
a custom shape of type "compound", it doesn't seem to respond to click
events. No problem with polygon shapes.

Running python 3.2.3, turtle version 1.1b on Windows XP.

Here is my test file:

##
import turtle
square = ((0,0),(0,20),(20,20),(20,0))
turtle.addshape("sq1", square) # sq1 = polygon shape
s = turtle.Shape("compound")
s.addcomponent(square, "red")
turtle.addshape("sq2", s) # sq2 = compound shape
t1 = turtle.Turtle(shape="sq1")
t2 = turtle.Turtle(shape="sq2")
t2.fd(20) # set the turtles side by side
def click(x,y): print("click at",x,y)
t1.onclick(click)
t2.onclick(click)
turtle.mainloop()
##

When I run this and click on the black square (i.e. t1), the message
"click at..." gets printed on the console. When I click on the red
square (i.e. t2), nothing happens.

Bug or feature?

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


Re: Migrate from Access 2010 / VBA

2012-11-29 Thread Nicolas Évrard
* Wolfgang Keller  [2012-11-25 20:48 +0100]: 

I am the lone developer of db apps at a company of 350+ employees.
Everything is done in MS Access 2010 and VBA. I'm frustrated with the
limitations of this platform and have been considering switching to
Python.

I've been experimenting with the language for a year or so,
and feel comfortable with the basics.

I am concerned that I'll have a hard time replacing the access form
and report designers. I've worked a little with TKinter, but it's a
far cry from the GUI designer in Access.


The list of Python frameworks for rapid development of desktop
(i.e. non-Web) database applications currently contains:

using PyQt (& Sqlalchemy):
Pypapi: www.pypapi.org
Camelot: www.python-camelot.com
Qtalchemy: www.qtalchemy.org

using PyGTK:
Sqlkit: sqlkit.argolinux.org (also uses Sqlalchemy)
Kiwi: www.async.com.br/projects/kiwi

using wxPython:
Dabo: www.dabodev.com
Defis: sourceforge.net/projects/defis (Russian only)
GNUe: www.gnuenterprise.org

Pypapi, Camelot, Sqlkit and Dabo seem to be the most active and best
documented/supported ones.


I'd like to add to the list 


 Tryton http://www.tryton.org/

Which framework can be used to create a business application without
even using the already existing modules (one of our customer uses only
the 'party' modules in order to manage insurance products, the GNU
Health (http://www.gnuhealth.org/) project uses more official modules
to create their HIS software).

Reporting is done through relatorio (http://relatorio.openhex.org/),
which uses ODF templates to generate ODF reports (or other format
thanks to unoconv) the client is written in GTk (we're writing one in
JavaScript right now (and I miss python badly)).

--
(°> Nicolas Évrard
( ) Liège
  `¯


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


[winreg] How to access "(Default)" key value?

2022-05-03 Thread Nicolas Formichella
Hello,

I am encountering an issue with winreg, I can't figure out how to read the 
"(Default)" of a registry value

```
def get_chrome_version() -> str:
with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as registry:
with winreg.OpenKeyEx(registry, 
r"Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe",
  access=winreg.KEY_READ) as key:
value, _ = winreg.QueryValueEx(key, "(default)")
return value
```

Taking the example above it raises a FileNotFoundError :

```
Traceback (most recent call last):
  File "C:/Users/noulo/dev/py/chromedriver_dl/main.py", line 14, in 
get_chrome_version
value, _ = winreg.QueryValueEx(key, "(default)")
FileNotFoundError: [WinError 2] The system cannot find the file specified
```

(Trying "Path" instead of "(Default)" works)

Although the value definitely exists as shown by Powershell

```
Get-Item -Path  "HKCU:/Software/Microsoft/Windows/CurrentVersion/App 
Paths/chrome.exe" | Select-Object -ExpandProperty Property
```

Returns :

```
(default)
Path
```

Is this a bug I should report, or if not, what is the way, using winreg, to 
access the "(Default)" value of a key?

Regards,
Nicolas FORMICHELLA
-- 
https://mail.python.org/mailman/listinfo/python-list


Typing on child class' methods of a Generic base class

2022-03-09 Thread Nicolas Haller

Hello,

I am wondering about a situation involving typing, Generic and a child 
class.


The documentation about "user-defined generic types"[1] says that I can 
fix some types on a child class (class MyDict(Mapping[str, T]):) but 
doesn't say much about the signature of the methods I need to 
implement/override on that child class.


Should I keep the TypeVar and remember that I fixed the type(alternative 
1) or change the signature of the method to replace the TypeVar by the 
type I set (alternative 2)?


Mypy seems to prefer the second alternative but changing the signature 
feels wrong to me for some reason. That's why I'm asking :-)



Below is a small example to illustrate:

from abc import ABCMeta, abstractmethod
from typing import TypeVar, Generic


T = TypeVar("T")


class Base(Generic[T], metaclass=ABCMeta):
"""A base class."""

@abstractmethod
def _private_method(self, an_arg: T) -> T:
...

def public_method(self, an_arg: T) -> T:
from_private_method = self._private_method(an_arg)
return from_private_method


class Alternative1(Base[int]):
def _private_method(self, an_arg: T) -> T:  # I keep T
return 42


class Alternative2(Base[int]):
def _private_method(self, an_arg: int) -> int:  # I replace T
return 42


Thanks,

--
Nicolas Haller


[1]: 
https://docs.python.org/3/library/typing.html#user-defined-generic-types

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


Re: Typing on child class' methods of a Generic base class

2022-03-12 Thread Nicolas Haller

On 2022-03-10 12:31, Dieter Maurer wrote:

Nicolas Haller wrote at 2022-3-9 10:53 -0500:

...
The documentation about "user-defined generic types"[1] says that I can
fix some types on a child class (class MyDict(Mapping[str, T]):) but
doesn't say much about the signature of the methods I need to
implement/override on that child class.


I have the fealing that this is a case of (generic type) "specialization".
In this setup, `Mapping` would be a generic type with two type
variables `K` (the key type) and `V` (the value type).
The signatures of its methods would use those type variables.
In your example, you specialize the key type to `str` (and
leave the value type generic). The signatures of the methods
would automatically follow this specialization -- without the need
to do anything.


If I understand correctly, you're saying I should use the first 
alternative by keeping the signature as it is in the base class:

---
T = TypeVar("T")


class Base(Generic[T], metaclass=ABCMeta):
"""A base class."""

@abstractmethod
def _private_method(self, an_arg: T) -> T:
...

def public_method(self, an_arg: T) -> T:
from_private_method = self._private_method(an_arg)
return from_private_method

class Alternative1(Base[int]):
def _private_method(self, an_arg: T) -> T:  # I keep T
return 42
---

The problem with it is that mypy doesn´t seem quite happy with it:
./scratch.py:22: error: Incompatible return value type (got "int", 
expected "T")


Do you think this is error is incorrect? If so, I can open an issue with 
mypy.


Thanks,

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


Pretty printing dicts with compact=True

2018-09-11 Thread Nicolas Hug
Is there a reason why the 'compact' parameter is ignored when pretty 
printing a dict? For example:


pprint({x: x for x in range(15)}, compact=True)

would be be printed in 15 lines while it could fit on 2.


Is this a bug or was this decided on purpose?

Thank you!

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


Re: Pretty printing dicts with compact=True

2018-09-11 Thread Nicolas Hug

To me it also seems to be the most sensible behaviour, since
dictionaries with their keys and values are different from most other
sequences.

You've got a point but

1. That goes against the compact=True expected behaviour

2. Small dicts (e.g. /{x: x for x in range(5)}/) are still printed on a 
single line (regardless of the compact parameter), so I don't believe 
that was the rationale behind this behaviour.



On 9/11/18 1:05 PM, Max Zettlmeißl wrote:

On Tue, Sep 11, 2018 at 1:58 PM, Nicolas Hug  wrote:

pprint({x: x for x in range(15)}, compact=True)

would be be printed in 15 lines while it could fit on 2.


Is this a bug or was this decided on purpose?

It is on purpose as can be seen in the code for pprint [1], which
calls _format [2], which in the case of a dictionary calls
_pprint_dict [3], which ultimately calls _format_dict_items [4].
(which does not use compact or rather _compact)

To me it also seems to be the most sensible behaviour, since
dictionaries with their keys and values are different from most other
sequences. In a dictionary the relation between keys and values is the
most important one and reading a dictionary certainly is easier if
each key value pair has a line of it's own. (Especially if the keys
and values vary a lot in their lengths.)

[1] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L138
[2] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L154
[3] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L180
[4] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L333

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


Re: SOAP and Zeep

2016-08-01 Thread Nicolas Évrard
* Ethan Furman  [2016-07-29 19:54 +0200]: 

Greetings!

I may have a need in the immediate future to work with SOAP and WSDL
services, and a quick search turned up Zeep
(http://docs.python-zeep.org/en/latest/) -- does anyone have any
experience with it?
Or any other libraries that can be recommended?


We used zeep to communicate with SOAP webservices.
We choose it over suds because it supports python3.

I also happen to have a bug, and the maintainer quickly accepted my
patch, so according to me it's a good choice.

--
(°> Nicolas Évrard
( ) Liège
`¯
--
https://mail.python.org/mailman/listinfo/python-list


my matplotlib realtime plot doesn't show the line between the points

2020-03-31 Thread Nicolas Marat
hi guys, i need help because my matplotlib realtime plot doesn't show the line 
between the points.
even if i right '.k-' 
thit plot is display in a qwidget in an other code
wirdely that if i put bar it actualy working.
the real time data come from an arduino sensor 
that the shape of the data i have to plot:

ser_bytes = ser.readline()
value = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))




that is my code: 

class MplWidget(QWidget ):


def __init__( self, parent = None):

QWidget.__init__(self, parent)

self.canvas = FigureCanvas(Figure())

vertical_layout = QVBoxLayout() 
vertical_layout.addWidget(self.canvas)

self.canvas.axes = self.canvas.figure.add_subplot(1,1,1)
self.canvas.axes.set_ylim(0,90)
self.canvas.axes.set_xlim(0,100)
self.setLayout(vertical_layout)
   

def update_graph(self, value):

y = list()
x = list()


y.append(value)
x.append(self.i)
 
self.i += 1

   
self.MplWidget.canvas.axes.set_xlim(left=max(0, self.i-40), right= 
self.i+60)
self.MplWidget.canvas.axes.bar(x, y,)#'.k-')
self.MplWidget.canvas.axes.set_title('pull') 
self.MplWidget.canvas.draw()



thanks for help!

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


Re: my matplotlib realtime plot doesn't show the line between the points

2020-03-31 Thread Nicolas Marat
sorry that the real piece of code




self.MplWidget.canvas.axes.set_xlim(left=max(0, self.i-40), right= 
self.i+60)
self.MplWidget.canvas.axes.plot(x, y,'.k-')
self.MplWidget.canvas.axes.set_title('pull')
self.MplWidget.canvas.draw()
-- 
https://mail.python.org/mailman/listinfo/python-list


Continuous system simulation in Python

2005-10-06 Thread Nicolas Pernetty
Hello,

I'm looking for any work/paper/ressource about continuous system
simulation using Python or any similar object oriented languages (or
even UML theory !).

I'm aware of SimPy for discrete event simulation, but I haven't found
any work about continuous system.
I would like to develop a generic continous system simulator, and so
would be eager to join any open source effort on the subject.

For instance, it would be useful for modelling an airplane with all the
dynamics (flight simulator).

Python is my language of choice because of the keyword 'generic'. Being
an object oriented dynamic language, it's perfect for such a task.
Unfortunately I'm a novice when it comes to object oriented
design and development, so I would prefer to start from something
already existent instead of starting from scratch.

If you had any idea on the subject, I would be really glad to discuss it
with you.

Thanks in advance,

P.S. : for email, replace nowhere by yahoo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Continuous system simulation in Python

2005-10-07 Thread Nicolas Pernetty
Hello Phil,

Yes I have considered Octave. In fact I'm already using Matlab and
decided to 'reject' it for Python + Numeric/numarray + SciPy because I
think you could do more in Python and in more simple ways.

Problem is that neither Octave, Matlab and Python offer today a
framework to build continuous system simulator (in fact Matlab with
Simulink and SimMechanics, do propose, but I was not convinced at all).

Regards,

*** REPLY SEPARATOR  ***

On 7 Oct 2005 11:00:54 -0700, [EMAIL PROTECTED] wrote :

> Nicholas,
> 
> Have you looked at Octave? It is not Python, but I believe it can talk
> to Python.
> Octave is comparable to Matlab for many things, including having ODE
> solvers. I have successfully used it to model and simulate simple
> systems. Complex system would be easy to model as well, provided that
> you model your dynamic elements with (systems of) differential
> equations.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Continuous system simulation in Python

2005-10-07 Thread Nicolas Pernetty
On Thu, 06 Oct 2005 22:30:00 -0700, Robert Kern <[EMAIL PROTECTED]>
wrote :

> Dennis Lee Bieber wrote:
> > On Fri, 7 Oct 2005 01:12:22 +0200, Nicolas Pernetty
> > <[EMAIL PROTECTED]> declaimed the following in
> > comp.lang.python:
> > 
> > > I'm aware of SimPy for discrete event simulation, but I haven't
> > > found any work about continuous system.
> > > I would like to develop a generic continous system simulator, and
> > > so would be eager to join any open source effort on the subject.
> > >
> > >For instance, it would be useful for modelling an airplane with all
> > > the dynamics (flight simulator).
> >
> > Unless that flight simulator is running on some big ugly ANALOG
> > computer (the ones that used rheostats, transformers, and
> > amplifiers), they all are really using discrete time intervals and
> > computing values at those time points. Such computation may require
> > integration of continuous functions from previous time step to
> > current time step.
> 
> I think Nicolas means "(discrete event) simulation" as opposed to
> "discrete (event simulation)" and "(continuous system) simulation" as
> opposed to "continuous (system simulation)". The methods used in SimPy
> to model (discrete events) don't apply terribly well to simulating
> many (continuous systems) like airplane dynamics. For example, an ODE
> integrator would probably want to adaptively select its timesteps as
> opposed to laying out a uniform discretization upfront.
> 

Yes you are absolutely right. That's what I wanted to mean.
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Continuous system simulation in Python

2005-10-07 Thread Nicolas Pernetty
Thanks, but what is really difficult is not to understand how to design
the program which solve a specific problem but to design a generic
framework for solving all these kinds of problem. And in a simple enough
way for basic programmers (but good scientists !) to handle it.

*** REPLY SEPARATOR  ***

On 6 Oct 2005 17:04:01 -0700, "hrh1818" <[EMAIL PROTECTED]> wrote
:

> A good starting point is the book "Python Scripting for Computational
> Science" by Hans Petter Langtangen.  The book covers topics that go
> from simulating second order mechanical systems to solving partial
> differentail equations.
> 
> Howard
> 
> Nicolas Pernetty wrote:
> > Hello,
> >
> > I'm looking for any work/paper/ressource about continuous system
> > simulation using Python or any similar object oriented languages (or
> > even UML theory !).
> >
> > I'm aware of SimPy for discrete event simulation, but I haven't
> > found any work about continuous system.
> > I would like to develop a generic continous system simulator, and so
> > would be eager to join any open source effort on the subject.
> >
> > For instance, it would be useful for modelling an airplane with all
> > the dynamics (flight simulator).
> >
> > Python is my language of choice because of the keyword 'generic'.
> > Being an object oriented dynamic language, it's perfect for such a
> > task. Unfortunately I'm a novice when it comes to object oriented
> > design and development, so I would prefer to start from something
> > already existent instead of starting from scratch.
> >
> > If you had any idea on the subject, I would be really glad to
> > discuss it with you.
> > 
> > Thanks in advance,
> > 
> > P.S. : for email, replace nowhere by yahoo
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Continuous system simulation in Python

2005-10-08 Thread Nicolas Pernetty
Simulink is well fitted for small simulators, but when you run into big
projects, I find many shortcomings appears which made the whole thing
next to unusable for our kind of projects.

That's why I'm interested in Python by the way, it is not a simple clone
like Scilab/Scicos. It is a real language which bring its own
advantages, and its own shortcomings, which I find well suited for our
activity.

If you want, I can send you a paper I wrote last year, detailing all
Simulink shortcomings. I doubt that this mailing list is interested in
such things...(and it's in French...).

Concerning Scilab/Scicos, I'm not really interested in a technology
primarily developed (INRIA and ENSPC) and used by France. Python and all
its libraries and communities are so much more dynamic !
And also I've heard that Scilab was developed in Fortran in a way which
make it rigid and that the sources are poorly documented, not a good
sign for an open source software (and Scilab isn't 'Free' for the FSF).

Regards,


*** REPLY SEPARATOR  ***

On 8 Oct 2005 11:06:25 -0700, "Sébastien Boisgérault"
<[EMAIL PROTECTED]> wrote :

> 
> Simulink is a framework widely used by the control engineers ...
> It is not *perfect* but the ODEs piece is probably the best
> part of the simulator. Why were you not convinced ?
> 
> You may also have a look at Scicos and Ptolemy II. These
> simulators are open-source ... but not based on Python.
> 
> Cheers,
> 
> SB
> 
> 
> 
> 
> 
> Nicolas Pernetty a écrit :
> 
> > Hello Phil,
> >
> > Yes I have considered Octave. In fact I'm already using Matlab and
> > decided to 'reject' it for Python + Numeric/numarray + SciPy because
> > I think you could do more in Python and in more simple ways.
> >
> > Problem is that neither Octave, Matlab and Python offer today a
> > framework to build continuous system simulator (in fact Matlab with
> > Simulink and SimMechanics, do propose, but I was not convinced at
> > all).
> >
> > Regards,
> >
> > *** REPLY SEPARATOR  ***
> >
> > On 7 Oct 2005 11:00:54 -0700, [EMAIL PROTECTED] wrote :
> >
> > > Nicholas,
> > >
> > > Have you looked at Octave? It is not Python, but I believe it can
> > > talk to Python.
> > > Octave is comparable to Matlab for many things, including having
> > > ODE solvers. I have successfully used it to model and simulate
> > > simple systems. Complex system would be easy to model as well,
> > > provided that you model your dynamic elements with (systems of)
> > > differential equations.
> > >
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Continuous system simulation in Python

2005-10-09 Thread Nicolas Pernetty
Hello Phil,

I'm currently looking to see if I can build upon SimPy, thus making it
an hybrid system simulator. That would be a great step for the
community.

Main difficulty would be to build a framework which isn't clumsy, like
you said.
I have close to no experience in Python and object oriented development,
but I'm fairly advanced in C and procedural development, and of course
in continuous sytem simulator. I'll keep you informed of my
investigations...

I've downloaded your zip files, but unfortunately I have no access to
Windows. Are you able to send me only the sources ?

Thanks in advance,

*** REPLY SEPARATOR  ***

On 8 Oct 2005 21:36:05 -0700, [EMAIL PROTECTED] wrote :

> Nicholas,
> 
> I have a particular interest in this subject as well. I've also used
> the Python/Scipy combination, and it is a tantalizing combination, but
> I found it to be a bit more clumsy than I'd like. Plus, my need for
> continuous-time simulation is not as great as it has been in the past.
> 
> That said, I've been down this path before (see
> http://custom.lab.unb.br/pub/asme/DYNAMICS/BUFORD1.zip), and I would
> be interested in helping to develop something. I agree that Python
> would be a great foundation to build upon.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Continuous system simulation in Python

2005-10-10 Thread Nicolas Pernetty
> I am aware of some shortcomings and design flaws of Simulink,
> especially in the code generation area. I am interested by
> your paper nonetheless, please send me copy.

Ok no problem. Let me just a few days to strip any irrelevant data on
it...

> However, Simulink is used by many people on a day-to-day basis
> in the context of big, industrial projects. The claim that it
> is "next to unusable" is, in my book, an overstatement ...

Well the exact sentence is "next to unusable for our kind of projects".
You'll see the details on the paper, but I'm not joking.
For instance, under Simulink, our model is so big (well not so, but too
big for Simulink obviously), that you may have a loss of up to 40x in
performance compared to the model in C (how to optimize the Simulink
model is a whole other subject in itself). So to make it usable, we have
to use automatic code generation wich bring a whole new set of
problems... BUT our work is *very* specific, and I'm not talking about
Simulink in general. It may be perfect suited for others, it's just that
for us it's far from perfect...

> Scicos is not perfect either but you can hardly say that is
> is a simple clone of Simulink. No time and space to go into
> the details ...

I wasn't in charge of evaluating Scilab/Scicos, so I can only talk about
the conclusion : main motives to switch to Scilab/Scicos would be
because it's free, that's all. Report said that next to almost
everything Scilab/Scicos does, Matlab/Simulink can do, and more often
than not, do it much better.
So if you have a different report, I would be happy to read and transmit
it...

> Obviously, the python community is very dynamic, but how much
> support will you get in the very specific topic of continuous
> time systems simulation ?

Well some people already offered me their help. But I believe
that someone _has_ to begin alone some day...
Otherwise people who work on continuous system simulation would never be
interested in Python.

That's the beauty of open source : do what you can, but do it ! and hope
that someone else will come one day and use your work to build upon it.
Step by step you will have something usable (in theory).

> IMHO, an hybrid approach, such as the development of bridge
> to include Python components into Simulink/Scicos/Ptolemy/
> Modelica/pick_your_favorite_simulator may grant you more
> interest from the simulation community.

I already know some bridges like pymat or mlabwrap and I agree that a
way to include Python to Matlab/Simulink would be a great step.
But :

1) I think that it's Mathworks job to do it, and if they don't want to
do it, we'll never have a very good integration.

2) For our kind of projects and our kind of developers (mainly
non-IT engineers), I'm very reluctant to introduce too many different
technologies in a project. If we decided to go for Python, fine, let's
do the entire thing in Python/C. If we decided to go for Simulink, fine,
let's do the whole thing in Simulink/Matlab/C. Matlab, for algorithms,
can do almost the same things than Python and sometimes much better, so
if you have already Simulink (and so have the license) why go for Python
and struggle to have a good integration ?

Regards,

> 
> Cheers,
> 
> SB
> 
> 
> 
> Nicolas Pernetty wrote:
> > Simulink is well fitted for small simulators, but when you run into
> > big projects, I find many shortcomings appears which made the whole
> > thing next to unusable for our kind of projects.
> > That's why I'm interested in Python by the way, it is not a simple
> > clone like Scilab/Scicos. It is a real language which bring its own
> > advantages, and its own shortcomings, which I find well suited for
> > our activity.
> >
> > If you want, I can send you a paper I wrote last year, detailing all
> > Simulink shortcomings. I doubt that this mailing list is interested
> > in such things...(and it's in French...).
> > Concerning Scilab/Scicos, I'm not really interested in a technology
> > primarily developed (INRIA and ENSPC) and used by France. Python and
> > all its libraries and communities are so much more dynamic !
> > And also I've heard that Scilab was developed in Fortran in a way
> > which make it rigid and that the sources are poorly documented, not
> > a good sign for an open source software (and Scilab isn't 'Free' for
> > the FSF).
> >
> > Regards,
> >
> >
> > *** REPLY SEPARATOR  ***
> >
> > On 8 Oct 2005 11:06:25 -0700, "Sébastien Boisgérault"
> > <[EMAIL PROTECTED]> wrote :
> >
> > >
> > > Simulink is a framework widely used by the control engineers ...
> > >

Re: Continuous system simulation in Python

2005-10-11 Thread Nicolas Pernetty
I was implicitly referring to Python/C model for this.
I'm aware that Python can be very slow on heavy computations (it's a
_documented_ shortcoming), sometimes much slower than Simulink.

I believe that no current technology can meet the needs of both rapid
prototyping (for projects in their infancy) and performance (for
projects in their industrial cycle).

That's why, as it is _documented_ and _recommended_ on the Python
website, I intend to first prototype with Python then slowly migrate
some critical parts to C/C++ as we refine and stabilize the specs.
Ideally, at the end of the project, we'll have the best of both worlds.

Note that it's the first time that I try this, I may be a perfectly
wrong approach for continuous system simulation...

*** REPLY SEPARATOR  ***

On 10 Oct 2005 17:48:39 -0700, "hrh1818" <[EMAIL PROTECTED]> wrote
:

> In your simulator how much do you want Python to do?  I ask this
> because your subject title implies you want to write your simulation
> code in Python but a  simulator written entirely in Python would be
> very slow.  Python is an interpreted language and pure Python code is
> not suitable for simulating big  continuous systems. Hence to me it
> appears you have two distinct proplems. One is developing a front end,
> a user interface, that is easy to use. The other is either finding or
> writing a good code compiler that wlll produce fast simulation code or
> writing an interface to existing optimize simulation code.  Although
> most likely not suitable for your applicaion but a good example of
> this type of program is Mathematica. It is written in two parts a user
> interface and a kernel that does all of the high power math.
> 
> Howard
> 
> 
> Nicolas Pernetty wrote:
> > > I am aware of some shortcomings and design flaws of Simulink,
> > > especially in the code generation area. I am interested by
> > > your paper nonetheless, please send me copy.
> >
> > Ok no problem. Let me just a few days to strip any irrelevant data
> > on it...
> >
> > > However, Simulink is used by many people on a day-to-day basis
> > > in the context of big, industrial projects. The claim that it
> > > is "next to unusable" is, in my book, an overstatement ...
> >
> > Well the exact sentence is "next to unusable for our kind of
> > projects". You'll see the details on the paper, but I'm not joking.
> > For instance, under Simulink, our model is so big (well not so, but
> > too big for Simulink obviously), that you may have a loss of up to
> > 40x in performance compared to the model in C (how to optimize the
> > Simulink model is a whole other subject in itself). So to make it
> > usable, we have to use automatic code generation wich bring a whole
> > new set of problems... BUT our work is *very* specific, and I'm not
> > talking about Simulink in general. It may be perfect suited for
> > others, it's just that for us it's far from perfect...
> >
> > > Scicos is not perfect either but you can hardly say that is
> > > is a simple clone of Simulink. No time and space to go into
> > > the details ...
> >
> > I wasn't in charge of evaluating Scilab/Scicos, so I can only talk
> > about the conclusion : main motives to switch to Scilab/Scicos would
> > be because it's free, that's all. Report said that next to almost
> > everything Scilab/Scicos does, Matlab/Simulink can do, and more
> > often than not, do it much better.
> > So if you have a different report, I would be happy to read and
> > transmit it...
> >
> > > Obviously, the python community is very dynamic, but how much
> > > support will you get in the very specific topic of continuous
> > > time systems simulation ?
> >
> > Well some people already offered me their help. But I believe
> > that someone _has_ to begin alone some day...
> > Otherwise people who work on continuous system simulation would
> > never be interested in Python.
> >
> > That's the beauty of open source : do what you can, but do it ! and
> > hope that someone else will come one day and use your work to build
> > upon it. Step by step you will have something usable (in theory).
> >
> > > IMHO, an hybrid approach, such as the development of bridge
> > > to include Python components into Simulink/Scicos/Ptolemy/
> > > Modelica/pick_your_favorite_simulator may grant you more
> > > interest from the simulation community.
> >
> > I already know some bridges like pymat or mlabwrap and I agree that
> > a way to include Python t

Numeric array equivalent of index ?

2005-10-14 Thread Nicolas Pernetty
Hello,

I'm trying to find a clear and fast equivalent to the index method of
plain python list :
>> a = [5,1,4,3,4]
>> a.index(4)
2

I have to use it on a Numeric array, so the best I've come up with is
(rather ugly I think) :
>> from Numeric import array, equal, nonzero
>> a = array([5,1,4,3,4])
>> nonzero(equal(a,4))[0]
2


Does someone know of a more Pythonic way ?

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


Examples of Python code compared to other languages

2005-10-29 Thread Nicolas Pernetty
Hello,

I'm looking (without success so far) for code sources for common
problems in different languages, but especially Python, C, Fortran, Ada
and Matlab.

It would help people coming from other languages to understand the
'python way of thinking'.

Priority is clean code, performance is not an issue here because it
often leads to obscure code.

Ideally code for Python would extensively use the standard library
("don't reinvent the wheel").

I've already checked the following sites, but they were not suited for
what I'm looking for :

These ones are too focused on performance :
http://shootout.alioth.debian.org/
http://dada.perl.it/shootout/

This one don't include C or Fortran :
http://pleac.sourceforge.net/

This one is ok but rather limited :
http://www.kochandreas.com/home/language/lang.htm

If there is a site which regroup very good ('Pythonic') code examples
which make extensively use of standard library to resolve common
problems, I would be happy to help and try to contribute by giving the
equivalent in C code.

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


Re: Examples of Python code compared to other languages

2005-10-30 Thread Nicolas Pernetty
On 29 Oct 2005 21:27:39 -0700, [EMAIL PROTECTED] wrote :

> http://pleac.sourceforge.net/ probably is what you're looking for. It
> shows how to to stuff from the perl cookbook in a plethora of other
> languages, including Python.
> 
> Kind regards Terji Petersen
> 

Hello,

As mentioned in the original message, this site is good but doesn't
include C or Fortran.
Of course I can try to contribute with C code...

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


recursive function call

2005-11-08 Thread Nicolas Vigier
Hello,

I have in my python script a function that look like this :

def my_function(arg1, arg2, opt1=0, opt2=1, opt3=42):
if type(arg1) is ListType:
for a in arg1:
my_function(a, arg2, opt1=opt1, opt2=opt2, opt3=opt3)
return
if type(arg2) is ListType:
for a in arg2:
my_function(arg1, a, opt1=opt1, opt2=opt2, opt3=opt3)
return
 ... then here the real function code

I'm new to python, so I was wondering if there is a better way to do that.
The reason for a recursive function here is to be able to give lists for
the first 2 args (I could as well use only a simple 'for' without a
recursive call). The problem I have here, is that as I'm working on this
script, I often change the prototype of the function, and each time I
have to think about changing the recursive call too. Is there a way that
I can do a recursive call and say something like "keep all the same
arguments except this one" ?

Thanks

Nicolas

-- 
http://n0x.org/ - [EMAIL PROTECTED]


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


Re: recursive function call

2005-11-08 Thread Nicolas Vigier
Peter Otten said:
> Here is a non-recursive approach:
>
> def tolist(arg):
>if isinstance(arg, list):
>return arg
>return [arg]
>
> def f(arg1, arg2, more_args):
>for arg1 in tolist(arg1):
>for arg2 in tolist(arg2):
># real code
>
> If it were my code I would omit the tolist() stuff and instead always
> pass lists (or iterables) as the function's first two arguments.

Hmm, that's right. After all it's not very useful to be able to give
a single element, passing a list all the time is more simple. That's
what I'll do. I got the idea of passing a list or a singe element
because that's what they do in SCons, but in my case it's not really
usefull.

Thanks

-- 
http://n0x.org/ - [EMAIL PROTECTED]


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


Re: option argument length

2005-12-04 Thread Nicolas Couture
I don't think that's actually what you want to do. Yes arguments are
not to be used directly as option arguments (otherwise why have option
arguments anyways ;-) but each option argument is usually evaluated
under the evaluation of the actual option and optparse will error on
invalid use of the options you build.

Why exactly do you think you need to find the number of optional arguments?

Everytime I thought about the need for this kind of option parsing
design I was able to find an easier way to achieve what I wanted to do.

See "How optik handles errors" - http://optik.sourceforge.net/doc/1.5/tutorial.html

If you really think you need to be doing this, you can modify the following function:

def is_empty(options
):"""Returns True or False if an option is set or not.
"""values = options
.__dict__.values()return
 (values == [None] *
 len(values))


On 12/4/05, Ritesh Raj Sarraf <[EMAIL PROTECTED]> wrote:
-BEGIN PGP SIGNED MESSAGE-Hash: SHA1Hi,I'm using optparse module to parse all options and arguments.My program uses mostly "option arguments" hence my len(args) value is always
zero. I need to check if the user has passed the correct number of "optionarguments". Something like:(options,args) = parser.parse_args()len(options) != 1 or len(options) > 2:print "Incorrect number of arguments passed."
How do I accomplish it ?Regards,rrs- --Ritesh Raj SarrafRESEARCHUT -- http://www.researchut.com"Stealing logics from one person is plagiarism, stealing from many is
research.""Necessity is the mother of invention."Note: Please CC me. I'm not subscribed to the list-BEGIN PGP SIGNATURE-Version: GnuPG v1.4.2 (GNU/Linux)iD8DBQFDk1Nh4Rhi6gTxMLwRApx0AJ9XHlWFU1J0NdN02gtvimogUSgDkACgmkOO
2pX8ocoC7pot1a8R4u2BWrY==piNo-END PGP SIGNATURE---http://mail.python.org/mailman/listinfo/python-list

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

Re: python 3000 and removal of builtin callable

2005-01-04 Thread Nicolas Fleury
Mirko Zeibig wrote:
This is not an option for e.g. IDEs as some functions might actually do 
something when called ;-) and I like `callable` for introspection.

Other ways would be to check for the `__call__` attribute or use several 
methods of the `inspect`-Module, both of which are not better than 
`callable` IMHO.
I totally agree with you.  The callable function could be moved to a 
module and be built-in, but it cannot really be removed.  Calling a 
callable and know if an object is a callable without calling it is 
definitely not the same thing.

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


exporting from Tkinter Canvas object in PNG

2005-01-11 Thread Nicolas Pourcelot
Hello,
I'm new to this mailing list and quite to Pyhon too.
I would like to know how to export the contain of the Canvas object 
(Tkinter) in a PNG file ?
Thanks :)
Nicolas Pourcelot
-- 
http://mail.python.org/mailman/listinfo/python-list


Reraise exception with modified stack

2005-06-23 Thread Nicolas Fleury
Hi,
I've made a small utility to re-raise an exception with the same stack 
as before with additional information in it.  Since I want to keep the 
same exception type and that some types have very specific constructors 
(which take, for example, more than one parameter), the only safe way I 
have found to made it is by hacking the str representation:


import sys

class ExceptionStr:
 def __init__(self, content):
 self.content = content
 self.infos = []
 def addinfo(self, info):
 self.infos.insert(0, info)
 def __call__(self):
 return '\n' + '\n'.join(self.infos + [self.content])

def reraise(exception, additionalInfo):
 strFunc = getattr(exception, "__str__", None)
 if not isinstance(strFunc, ExceptionStr):
 strFunc = ExceptionStr(str(exception))
 exception.__str__ = strFunc
 strFunc.addinfo(additionalInfo)
 raise exception, None, sys.exc_info()[-1]

if __name__ == '__main__':
 def foo():
 raise AttributeError('Test')
 def bar():
 foo()
 try:
 try:
 try:
 bar()
 except Exception, exception:
 reraise(exception, "While doing x:")
 except Exception, exception:
 reraise(exception, "While doing y:")
 except Exception, exception:
 reraise(exception, "While doing z:")


Suppose the resulted traceback is:

Traceback (most recent call last):
   File "somefile.py", line 52, in ?
 reraise(exception, "While doing z:", MyException)
   File "somefile.py", line 50, in ?
 reraise(exception, "While doing y:", Exception)
   File "somefile.py", line 48, in ?
 reraise(exception, "While doing x:")
   File "somefile.py", line 46, in ?
 bar()
   File "somefile.py", line 40, in bar
 foo()
   File "somefile.py", line 38, in foo
 raise AttributeError('Test')
AttributeError:
While doing z:
While doing y:
While doing x:
Test

I would like to know how to code the reraise function so that the lines 
48, 50 and 52 don't appear in the stack.  Is it possible?

Thx and regards,
Nicolas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reraise exception with modified stack

2005-06-23 Thread Nicolas Fleury
Scott David Daniels wrote:
> How about dropping reraise and changing:
>   reraise(...)
> to:
>   addinfo(...)
>   raise

It doesn't work, or at least it doesn't do what I want.  I want to keep 
the same exception stack to be able to identify the original error.  I 
would like to avoid also writing in the caller something like 
sys.exc_info()[-1].

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


Re: Reraise exception with modified stack

2005-06-23 Thread Nicolas Fleury
Scott David Daniels wrote:
> Have you tried it?  Looked to do what you described to me when I run a
> sample.  Note that is an unadorned raise with no args.  The idea is to
> simply modify the exception object and then use raise to carry the
> whole original exception along as if not intercepted.

Oups, sorry, I tried it but wrote "raise exception" instead of "raise".

Yes, that's a very good idea indeed.  I'll change to that.

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


Re: Favorite non-python language trick?

2005-06-25 Thread Nicolas Fleury
Steven D'Aprano wrote:
> One of the things I liked in Pascal was the "with" keyword. You could
> write something like this:
> 
> with colour do begin
> red := 0; blue := 255; green := 0;
> end;
> 
> instead of:
> 
> colour.red := 0; colour.blue := 255; colour.green := 0;
> 
> Okay, so maybe it is more of a feature than a trick, but I miss it and it
> would be nice to have in Python.
> 

With PEP343 (I guess in Python 2.5), you will be able to do something like:
with renamed(colour) as c:
 c.red = 0; c.blue = 255; c.green = 0

I think however it is bad.  Better solutions to me would be:

colour.setRgb(0, 255, 0)

or

c = myVeryLongNameColour
c.red = 0; c.blue = 255; c.green = 0

Regards,
Nicolas

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


Re: Better console for Windows?

2005-06-27 Thread Nicolas Fleury
Brett Hoerner wrote:
> This is a pretty basic, mostly un-python-related question, although I'm
> asking because of Python.
> 
> Is there a different shell I can use (other than cmd.com) to run Python
> in, where I can full-screen the window (if I pleased), etc?  As it is,
> things that would run far off the right have to be word wrapped after
> very few characters.

I don't know if you absolutely want a shell, but if what you want is a 
Python interactive prompt, I find PyShell coming with wxPython really 
nice.  It has autocompletion and support copy-paste with/without the 
preceding >>>.

Regards,
Nicolas

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


Generating a list of None

2005-07-14 Thread Nicolas Couture
Hi,

Is it possible to generate a list of `None' ?

opts.__dict__.values() below could be represented by [None, None, None]

---
def get_options(opts):
"""Return True or False if an option is set or not"""
vals = opts.__dict__.values()

for val in vals:
if val is not None:
return True

return False
---

This is how I'd like to see it:

---
def get_options(opts):
"""Return True or False if an option is set or not"""
vals = opts.__dict__.values()

for if vals is [None * len(vals)]:
return False

return True
---

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


Re: Generating a list of None

2005-07-14 Thread Nicolas Couture
of course the later snipplet should be:
---
def get_options(opts):
"""Return True or False if an option is set or not"""
vals = opts.__dict__.values()

if vals == [None * len(vals)]:
return False

return True
---

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


pyQT 4

2005-07-25 Thread Nicolas Lebas
hello,

i'm using actually pyqt 3.x to create several tools under linux.
I plan to propose those tools also for windows and mac os x under GPL 
agreement.

My question is : does anybody know when pyqt 4 will be distributed ?

 thanks


    Nicolas

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


getting Arrays and variables from R

2005-07-26 Thread Nicolas Lebas
hello,

i don't know if this is the best list to send this question, but i'm 
already trying to ask.

I need to import variables from .RData files (arrays or variables).
I'm trying to use the rpy module, but without success beccause when i 
try to access to a variable loaded from the .RData file i have a 
segmentation fault !

This is what i'm doing :
- in R-projet, i create a .RData file with some variables :
 > tab<-c(2,5,8,6)
 > v<-0.5
 > save.image("file.RData")

- in Python :
 > from rpy import *
 > r.load("file.RData")
['tab', '.Traceback', 'v']
 > r.tab
segmentation fault !

I don't understand very well what does python crash.

If someone has an idea to solve my problem or to give me a method which 
permit to import arrays and variables from .RData files with another module.

Thanks

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


Re: getting Arrays and variables from R [fixed]

2005-07-27 Thread Nicolas Lebas
Nicolas Lebas a écrit :

>hello,
>
>i don't know if this is the best list to send this question, but i'm 
>already trying to ask.
>
>I need to import variables from .RData files (arrays or variables).
>I'm trying to use the rpy module, but without success beccause when i 
>try to access to a variable loaded from the .RData file i have a 
>segmentation fault !
>
>This is what i'm doing :
>- in R-projet, i create a .RData file with some variables :
> > tab<-c(2,5,8,6)
> > v<-0.5
> > save.image("file.RData")
>
>- in Python :
> > from rpy import *
> > r.load("file.RData")
>['tab', '.Traceback', 'v']
> > r.tab
>segmentation fault !
>
>I don't understand very well what does python crash.
>
>If someone has an idea to solve my problem or to give me a method which 
>permit to import arrays and variables from .RData files with another module.
>
>Thanks
>
>         Nicolas
>  
>
Finally, i found the solution with rpy.
There is a bug in the python2.4-rpy_0.4.1 release, so you have to use
instead of 'r.tab' command :

r.get('tab')



-- 
Nicolas Lebas
INRA Unité Mixte de Recherche INRA / INAPG "Environnement et Grandes 
Cultures"
78850 Thiverval - Grignon
France
Tél.  +33 (0)1 30 81 55 55   (standard)
Fax   +33 (0)1 30 81 55 63
Site Web : www-egc.grignon.inra.fr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting Arrays and variables from R [fixed]

2005-07-27 Thread Nicolas Lebas
Finally i found the solution in Rpy-list : there is a bug in 
python2.4-rpy_0.4.1.

An alternative solution which works fine it's to use the R get(str) 
function instead of using directly the variable (i.e r.tab) like that :

r.get('tab')



Nicolas Lebas a écrit :
> hello,
> 
> i don't know if this is the best list to send this question, but i'm 
> already trying to ask.
> 
> I need to import variables from .RData files (arrays or variables).
> I'm trying to use the rpy module, but without success beccause when i 
> try to access to a variable loaded from the .RData file i have a 
> segmentation fault !
> 
> This is what i'm doing :
> - in R-projet, i create a .RData file with some variables :
>  > tab<-c(2,5,8,6)
>  > v<-0.5
>  > save.image("file.RData")
> 
> - in Python :
>  > from rpy import *
>  > r.load("file.RData")
> ['tab', '.Traceback', 'v']
>  > r.tab
> segmentation fault !
> 
> I don't understand very well what does python crash.
> 
> If someone has an idea to solve my problem or to give me a method which 
> permit to import arrays and variables from .RData files with another module.
> 
> Thanks
> 
>  Nicolas


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


Re: getting Arrays and variables from R

2005-07-30 Thread Nicolas Lebas
Finally i found the solution in Rpy-list : there is a bug in 
python2.4-rpy_0.4.1.

An alternative solution which works fine it's to use the R get(str) 
function instead of using directly the variable (i.e r.tab) like that :

r.get('tab')


This bug is fixed in the rpy_0.4.6 release.



Nicolas Lebas a écrit :
> hello,
> 
> i don't know if this is the best list to send this question, but i'm 
> already trying to ask.
> 
> I need to import variables from .RData files (arrays or variables).
> I'm trying to use the rpy module, but without success beccause when i 
> try to access to a variable loaded from the .RData file i have a 
> segmentation fault !
> 
> This is what i'm doing :
> - in R-projet, i create a .RData file with some variables :
>  > tab<-c(2,5,8,6)
>  > v<-0.5
>  > save.image("file.RData")
> 
> - in Python :
>  > from rpy import *
>  > r.load("file.RData")
> ['tab', '.Traceback', 'v']
>  > r.tab
> segmentation fault !
> 
> I don't understand very well what does python crash.
> 
> If someone has an idea to solve my problem or to give me a method which 
> permit to import arrays and variables from .RData files with another module.
> 
> Thanks
> 
>  Nicolas


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


PEP: Specialization Syntax

2005-08-07 Thread Nicolas Fleury
Hi everyone, I would to know what do you think of this PEP.  Any comment 
welcomed (even about English mistakes).

PEP:XXX
Title:  Specialization Syntax
Version:$Revision: 1.10 $
Last-Modified:  $Date: 2003/09/22 04:51:49 $
Author: Nicolas Fleury 
Status: Draft
Type:   Standards Track
Content-Type:   text/plain
Created:24-Jul-2005
Python-Version: 2.5
Post-History:   
Abstract

 This PEP proposes a syntax in Python to do what is called in
 this document "specialization".  It contains more than one
 proposal:
 - Extend square brackets syntax to allow a full call syntax,
   using a __specialize__ method, similarly to the __call__
   method.
 - Extend function definition syntax to allow specialization
   of functions.
 - Parameterized types.


Motivation

 In his controversial blog entry "Adding Optional Typing to
 Python -- Part II" [1], Guido Van Rossum introduced the idea
 of "parameterized types" in Python.  The proposition was to
 use [square brackets] rather than  to allow
 prototyping with __getitem__ method.  However, the __getitem__
 method is not flexible enough.  It doesn't support keyword
 arguments and using multiple and default arguments can be pain,
 since the only argument received would be a tuple.  Calling
 can also be error-prone if a tuple can be allowed as a first
 argument.  This PEP proposes to enhance square brackets syntax
 to allow full-call syntax as with parenthesis.

 Note that Guido dropped the idea, for now, of parameterized
 types in a following blog entry [2].  This PEP introduces
 parameterized types only as a last step, and focus more on
 having a syntax to prototype them.  This PEP can also serve
 as a place to discuss to feature of specialization independently.

 The term "specialization" is used in that document because
 "parameterized functions" would sound like an already available
 feature.  As Guido pointed out [1], "generic" is neither a good
 term.  Specialization is a term in that case borrowed from C++.
 The term alone is not perfect, since it refers to the action of
 passing arguments to a "parameterized type" (or function) to
 make it usable and a term must still be found to describe the
 "unspecialized" type or function.

 Another motivation to this PEP is the frequent usage in Python
 of functions to create functions.  This pattern is often used
 to create callback functions and decorators, to only name these.
 However, the fact that both the creation and the use is using
 parenthesis can be confusing.  Also, a programmer ends up naming
 two functions, when only the creating one is called by name and
 the created one is doing the job.  Some programmers ends up
 naming the creating function with the name they would want to
 give to the created function, confusing even more the code using
 it.  To fix this situation, this PEP proposes a syntax for
 function specialization.


__specialize__ Special Member Function.

 The first element of this proposal is the addition of the
 __specialize__ special member function.  The __specialize__
 function can have the same signatures as __call__.  When
 defined, the definition of __getitem__ has no effect, and
 __specialize__ will be called instead.

 The language grammar is extended to allow keyword arguments
 and no arguments.  For example:

 class MyObject(object):
 def __specialize__(self, a=4, b=6, *args, **kwargs):
 pass

 obj = MyObject()
 obj[b=7, a=8, c=10]
 obj[]

 Note that when __specialize__ is defined, __setitem__,
 __getslice__ and __setslice__ are still used as before.


The specializer Decorator

 To explain the syntaxes proposed in this PEP, the following
 decorator is used:

 class Specializer:
 def __init__(self, callableObj):
 self.callableObj
 self.__name__ = callableObj.__name__
 def __specialize__(self, *args, **kwargs):
 self.callableObj(*args, **kwargs)

 def specializer(callableObj):
 return Specializer(callableObj)

 It takes a callable and make it callable with square brackets
 instead.


Function Specialization

 A common pattern in Python is to use a function to create
 another function:

 def makeGetMemberFunc(memberName):
 def getMember(object):
 return getattr(object, memberName)
 return getMember

 foo(makeGetMemberFunc('xyz'))

 The second element of this proposal is to add a syntax so
 that the previous example can be replaced by:

 def getMember[memberName](object):
 

Re: PEP: Specialization Syntax

2005-08-07 Thread Nicolas Fleury
Martin v. Löwis wrote:
> -1. I don't see the point of this PEP. Apparently, you want to define
> parametrized types - but for what purpose? I.e. what are the specific
> use cases for the proposed syntax, and why do you need to change the
> language to support these use cases? I very much doubt that there are
> no acceptable alternatives for each case.

Well, I'm using the alternatives.  For example, where I work we have 
built a small framework to create binary data to be loaded-in-place by 
C++ code (it might be presented at next GDC (Game Developer 
Conference)).  It uses metaclasses and descriptors to allow things like:

class MyObject(LoadInPlaceObject):
 size = Member(Int32)
 data = Member(makeArrayType(makePtrType(MyObject2, nullable=True)))
 ...

I know, it's not really Python, but still, defining functions like 
makeArrayType and makePtrType is a pain.  It is necessary to maintain a 
dictionary of types (to avoid redundacy) and simple things like:

def makeType(someArgument):
 class MyObject:
 someArgument = someArgument
 return MyObject

are not allowed.  So its ends up with something like:

__arrayTypes = {}
def makeArrayType(arg1, arg2=someDefault):
 if (arg1, arg2) in __arrayTypes:
 return __arrayTypes[arg1, arg2]
 renamed_arg1 = arg1
 renamed_arg2 = arg2
 class Array:
arg1 = renamed_arg1
arg2 = renamed_arg2
 ...
 __arrayTypes[arg1, arg2] = Array
 return Array

Does it qualify as an "acceptable alternative"? when it could have been:

class Array[arg1, arg2=someDefault]:
 ...

I probably should have put this example in the PEP.

> IOW, whatever it is that you could do with this PEP, it seems you could
> do this today easily.

The PEP validity is also very much influenced if optional static typing 
is planned to be added to the language.  I realize defending this PEP is 
much harder without static typing and my use cases imply typing of some 
sort anyway.

Regards,
Nicolas

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


Re: PEP: Specialization Syntax

2005-08-07 Thread Nicolas Fleury
Bengt Richter wrote:
>>__specialize__ Special Member Function.
> 
> By "Member Function" do you mean anything different from "method"?

No, I should have written method.  C++ habit.

>>The first element of this proposal is the addition of the
>>__specialize__ special member function.  The __specialize__
>>function can have the same signatures as __call__.  When
> 
> Any function can have any legal signature, so I'm not sure what you are 
> saying.

You're right, I should focus on the syntax change, to call __getitem__ 
(or __specialize__) automatically.

>>defined, the definition of __getitem__ has no effect, and
>>__specialize__ will be called instead.
> 
> What about subclassing and overriding __getitem__ ?

I have no problem with that.  I even suggest it at the end of the PEP.

But don't you think the name "__getitem__" is not appropriate then?

> here you can currently write
>   __getitem__ = __specialize__
> although you have to remember that obj[:] and related slicing expressions
> become legal and that obj[] does not, without a language sysntax change.

Yes, the PEP is about that syntax change.

>>class Specializer:
>>def __init__(self, callableObj):
>>self.callableObj
> 
>^^?? = callableObj ?

Yes, "= callableObj" is missing.

>>A common pattern in Python is to use a function to create
>>another function:
>>
>>def makeGetMemberFunc(memberName):
>>def getMember(object):
>>return getattr(object, memberName)
>>return getMember
>>
>>foo(makeGetMemberFunc('xyz'))
> 
> 
> Either closures like the above or bound methods work for this,
> so you just want more concise spelling?

In the case of functions, yes.  For functions, I guess the syntax is 
much more useful is static typing is added, or planned to be added, in 
the language.  However, there's still use cases where it is useful.

> Have you looked at currying? E.g.,
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549

And partial will be in Python 2.5 (PEP 309).  Yes, I've look at it, but 
in my use cases the created function correspond to a specific function 
signature, so, for example, you always only want to specify the 
"memberName" argument.  Currying is nice, but since any argument can 
supplied, the code is less self-documenting.  But I used these in 
day-to-day programming.

>>class MyList[ElementType=object](List[ElementType]):
>>...
> 
> Before I'd want to extend class syntax this way, I think I'd want to
> explore some other aspects of class syntax as well, with more (and
> more persuasive) use cases in view. Also more thought to what is done
> when and whether the issue is to supply information into existing control
> contexts or to modify control flow as well, to extend possibilities for
> customized processing.

What do you think of the example I post in a reply to Martin v.Lowis?

>>Instead of adding a __specialize__ method, the __getitem__
> 
> When you say "the" __getitem__ method, what do you mean? AFAIK the
> method itself is an unrestricted function. It just happens that
> binding it as a class attribute __getitem__ makes it get called
> from code with square bracket access spellings. I think that's where
> your changes to allow "additional signatures" would have to go. I.e.,
> in generation of code from the "calling" syntax. To illustrate:
> 
>  >>> class C(object):
>  ... def __getitem__(self, *args, **kwargs):
>  ... return self, args, kwargs
>  ...
>  >>> c=C()
>  >>> c[1]
>  (<__main__.C object at 0x02EF498C>, (1,), {})
>  >>> c[1,2]
>  (<__main__.C object at 0x02EF498C>, ((1, 2),), {})
>  >>> c[:]
>  (<__main__.C object at 0x02EF498C>, (slice(None, None, None),), {})
>  >>> c[kw='key word arg']
>File "", line 1
>  c[kw='key word arg']
>  ^
>  SyntaxError: invalid syntax
> 
> But here the problem is not in the __getitem__ method:
> 
>  >>> c.__getitem__(kw='key word arg')
>  (<__main__.C object at 0x02EF498C>, (), {'kw': 'key word arg'})
> 
> It's just that square bracket expression trailer syntax does not
> allow the same arg list syntax as parenthesis calling trailer syntax.

I totally agree and that's what I mean.  The formulation of the PEP is 
wrong, I should almost not talk about __getitem__ since as you said it 
can have any signature.  The PEP is about extending [] syntax to call 
automtically __getitem__ function with more complex signatures.

>>Should other operators that square brackets be used for
>>specialization?
> 
> Didn't quite parse that ;-) You mean list comprehensions? Or ??

I mean should angle brackets <> like in C++, or another operator, be 
used instead?

Regards and thx for your feedback,
Nicolas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP: Specialization Syntax

2005-08-07 Thread Nicolas Fleury
Bengt Richter wrote:
> I don't understand why you wouldn't give the function arg a different name
> in the first place instead of via a temporary intermediary binding, e.g.,
> 
>  def makeType(someArgument_alias):
>   class MyObject:
>   someArgument = someArgument_alias
>   return MyObject

Because that would affect documentation and keyword arguments.  Both the 
constructed class *and* the function are exposed to the user, so it 
needs to be coherent.

>>__arrayTypes = {}
>>def makeArrayType(arg1, arg2=someDefault):
>>if (arg1, arg2) in __arrayTypes:
>>return __arrayTypes[arg1, arg2]
>>renamed_arg1 = arg1
>>renamed_arg2 = arg2
>>class Array:
>>  arg1 = renamed_arg1
>>  arg2 = renamed_arg2
>>...
>>__arrayTypes[arg1, arg2] = Array
>>return Array
>>
> 
> Or (untested, using new style class):
> 
>  def makeArrayType(arg1, arg2=someDefault):
>   try: return __arrayTypes[arg1, arg2]
>   except KeyError:
>   __arrayTypes[arg1, arg2] = Array = type('Array',(),{'arg1':arg1, 
> 'arg2':arg2})
>   return Array
>  
> (just re-spelling functionality, not understanding what your real use case is 
> ;-)

Well, of course, but I didn't wrote the rest of the class definition;)

So I need a place to put the class definition.  In the end, it looks 
very much like the mess in the example.  Maybe I'm missing a solution 
using decorators.  I've defined a few classes like that, and I can live 
with it, but having a syntax to do it more easily, I would use it right 
away.

I guess it can also be useful for people interfacing with COM or typed 
contexts.

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


Re: PEP: Specialization Syntax

2005-08-08 Thread Nicolas Fleury
Kay Schluehr wrote:
> def makeClass(cls_name, **kw):
> return type(cls_name,(), kw)
> 
>>>>MyObject = makeClass("MyObject",a=8)
>>>>MyObject

As said to Bengt, a place is needed to write the class definition. 
There's no need for metaclass in that case:

def makeType(a, b, c=someDefault):
 arguments = locals()
 class MyObject:
 pass # Complete definition here
 MyObject.__dict__.update(arguments)
 return MyObject

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


Re: PEP: Specialization Syntax

2005-08-08 Thread Nicolas Fleury
Kay Schluehr wrote:
> I have to admit that i don't actually understand what you want? The
> problems you try to solve seem trivial to me but it's probably my fault
> and i'm misreading something. You might be correct that your PEP may be
> interesting only if "optional static typing" will be introduced to Py3K
> and then we will suddenly have an immediate need for dealing with
> generic types so that the syntax can be reused for deferred functions (
> the concept of "specialization" is usually coupled with some kind of
> partial evaluation which doesn't take place somewhere in your proposal
> ). But i'm not sure if this makes sense at all. 

Well, the partial evaluation is done when using [].

def getMember[memberName](obj):
 return getattr(obj, memberName)
x = getMember["xyz"]  # specialization
y = x(obj)  # use

I realize the term "specialization" can be confusing, since people might 
think of what is called in C++ "explicit specialization" and "partial 
specialization", while these concepts are not present in the PEP.

The point is that I'm already using static-like typing in frameworks 
interacting with other languages with generic types.  So I would already 
benefit from such a capability, and yes, there's workarounds.  I'm 
clearly in a minority with such a need, but the first point fo the PEP 
is to extend [] syntax, so that it is possible to prototype generic 
types using [] operators.

Regards,
Nicolas

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


Re: PEP: Specialization Syntax

2005-08-08 Thread Nicolas Fleury
Bengt Richter wrote:
> On Sun, 07 Aug 2005 21:41:33 -0400, Nicolas Fleury <[EMAIL PROTECTED]> wrote:
>>I mean should angle brackets <> like in C++, or another operator, be 
>>used instead?
> 
> I am getting the feeling that your PEP is about a means to do something 
> C++-like
> in python, not necessarily to enhance python ;-) IOW, it seems like you
> want the [] to do something like C++  in templates?

Yes, exactly.  Actually Guido also mentionned pointy brackets:
http://www.artima.com/weblogs/viewpost.jsp?thread=86641

> (BTW, I have nothing against giving python new capabilities (quite the 
> reverse),
> but not by grafting limbs from other animals ;-)

If I look at a very recent blog entry of Guido, it seems the idea is 
still in the air:
http://www.artima.com/weblogs/viewpost.jsp?thread=92662

> Maybe you want hidden name-mangling of function defs according to arg types
> and corresponding dispatching of calls? I am afraid I am still not clear
> on the fundamental motivation for all this ;-)

I wrote the PEP to see if was the only one that would benefit from 
generic types *before* having optional static typing in the language.

It seems I'm the only one;)

According to blog entry 86641, Guido himself is prototyping with 
__getitem__.  However, I cannot do the same, because the framework I use 
is much more complete and keyword arguments are a must.

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


Re: PEP: Specialization Syntax

2005-08-08 Thread Nicolas Fleury
Bengt Richter wrote:
> On Mon, 08 Aug 2005 16:18:50 -0400, Nicolas Fleury <[EMAIL PROTECTED]> wrote:
>>I wrote the PEP to see if was the only one that would benefit from 
>>generic types *before* having optional static typing in the language.
>>
>>It seems I'm the only one;)
>>
>>According to blog entry 86641, Guido himself is prototyping with 
>>__getitem__.  However, I cannot do the same, because the framework I use 
>>is much more complete and keyword arguments are a must.
>>
> Here is a decorator object to set up function call dispatch according to type.
> It only uses positional arguments, but could be fleshed out, I think.
> Not tested beyond what you see ;-)

That's nice.  Guido also posted this multimethods solution:
http://www.artima.com/weblogs/viewpost.jsp?thread=101605

The only thing I was saying it that I can use generic types in Python 
right now (and I do), by using (), but I can't with what will probably 
be the syntax in future, i.e. using [].

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


Re: PEP: Specialization Syntax

2005-08-09 Thread Nicolas Fleury
Martin v. Löwis wrote:
> Nicolas Fleury wrote:
> 
>>Well, I'm using the alternatives.
> 
> Perhaps not to the full power.

Not perhaps, surely;)  Who does anyway;)

> So you don't want to write the makeArrayType function, right?
> 
> How about this:
> 
> # declaration
> class Array(object):
>   __typeargs__ = ['arg1', ('arg2', someDefault)]
>   ...
> 
> # use
> t = specialize(Array, arg1=Int32)
> 
> where specialize is defined as
> 
> def specialize(ptype, *args):
>   result = type(ptype.__name__, (ptype,), args)
>   for t in result.__typeargs__:
>   if isinstance(t, string):
>   if not hasattr(result, t):
>   raise TypeError("missing parameter "+t)
>   else:
>   name,val = t
>   if not hasattr(result, name):
>   setattr(result, val)
>return result

That exact solution would not work for me, since that would replace the 
class metaclass, right?  However, you have a good point.  Such a 
function could be done by using the class metaclass instead of type, 
passing the base classes and dictionary (basically copying the class) 
and using a dictionary with args values as a key to avoid redundacies 
(can't see if there's something else).

Thx and regards,
Nicolas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32pipe.popen3

2005-08-17 Thread Nicolas Fleury
Jakob Simon-Gaarde wrote:
> Follow-up on a thread from 1999 (see below)
> 
> Well now it is 2005 and the operating system I'm using is Windows
> Server 2003, and I can still see that the same problem persists with:
> 
> win32pipe.popen2()
> win32pipe.popen3()
> win32pipe.popen4()
> 
> while win32pipe.popen() does almost what you want.

Have you tried subprocess?

Regards,
Nicolas

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


Re: Basic Server/Client socket pair not working

2005-08-29 Thread Nicolas Couture

Michael Goettsche wrote:
> Hi there,
>
> I'm trying to write a simple server/client example. The client should be able
> to send text to the server and the server should distribute the text to all
> connected clients. However, it seems that only the first entered text is sent
> and received. When I then get prompted for input again and press return,
> nothing gets back to me. Any hints on what I have done would be very much
> appreciated!
>
> Here's my code:
>
>  SERVER ##
> import socket
> import select
>
> mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> mySocket.bind(('', 1))
> mySocket.listen(1)
>
> clientlist = []
>
> while True:
>connection, details = mySocket.accept()
>print 'We have opened a connection with', details
>clientlist.append(connection)
>readable = select.select(clientlist, [], [])
>msg = ''
>for i in readable[0]:

for i in readable:

>   while len(msg) < 1024:
>  chunk = i.recv(1024 - len(msg))
>  msg = msg + chunk
>
>for i in clientlist:
>   totalsent = 0
>   while totalsent < 1024:
>  sent = i.send(msg)
>  totalsent = totalsent + sent
>
> ## CLIENT 
> import socket
> import select
>
> socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> socket.connect(("127.0.0.1", 1))
>
> while True:
> text = raw_input("Du bist an der Reihe")
> text = text + ((1024 - len(text)) * ".")
> totalsent = 0
> while totalsent < len(text):
> sent = socket.send(text)
> totalsent = totalsent + sent
>
> msg = ''
> while len(msg) < 1024:
> chunk = socket.recv(1024 - len(msg))
> msg = msg + chunk
>  
> print msg

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


Import mechanism to support multiple Python versions

2005-03-18 Thread Nicolas Fleury
Hi,
	I'm trying to support two Python versions at the same time and I'm 
trying to find effective mechanisms to support modules compiled in C++ 
transparently.

All my code in under a single package.  Is it possible to override the 
import mechanism only for modules under that package and sub-packages so 
that?:

import cppmymodule
would be equivalent to:
if sys.version == "2.4":
import cppmymodule24 as cppmymodule
elif sys.version == "2.3":
import cppmymodule23 as cppmymodule
for all modules under the package and all modules with names beginning 
with cpp (or another way to identify them).

I have also third party packages.  Is it possible to make a package 
point to another folder?  For example:

psyco23/...
psyco24/...
psyco/__init__.py  => points to psyco23 or psyco24 depending on Python 
version used.

Note that I cannot use .pth files or symbolic links, since I would want 
the exact same code hierarchy to work with both Python 2.3 and 2.4.

Any help appreciated.
Thx and regards,
Nicolas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Import mechanism to support multiple Python versions

2005-03-18 Thread Nicolas Fleury
Nicolas Fleury wrote:
import cppmymodule
would be equivalent to:
if sys.version == "2.4":
import cppmymodule24 as cppmymodule
elif sys.version == "2.3":
import cppmymodule23 as cppmymodule
for all modules under the package and all modules with names beginning 
with cpp (or another way to identify them).
Since all my imports are absolute, my code looks more like:
import root.subpackage.cppmymodule
So I guess, I can add this in root/__init__.py and everything would be fine:
def myimport(name, globals=None, locals=None, fromlist=None,
 __import__=__import__):
names = name.split('.')
if names[0] == 'root' and names[-1][0:3] == 'cpp':
name += '%s%s' % sys.version_info[0:2]
return __import__(name, globals, locals, fromlist)
__builtins__['__import__'] = myimport
It seems to work, is that right?
Thx and regards,
Nicolas
--
http://mail.python.org/mailman/listinfo/python-list


Re: getattr() woes

2004-12-29 Thread Nicolas Fleury
David M. Cooke wrote:
Ideally, I think the better way is if getattr, when raising
AttributeError, somehow reused the old traceback (which would point
out the original problem). I don't know how to do that, though.
Maybe a solution could be to put the attribute name in the 
AttributeError exception object, and use it in getattr; if the name 
doesn't match, the exception is re-raised.  It's still not flawless, but 
would reduce risk of errors.

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


Re: Why would I use inspect.isclass()?

2004-12-29 Thread Nicolas Fleury
an_instance=Abc()

But what good is that?  Of course I know Abc is a class, why would I want to
inspect it so that it would tell me what I already know?
Well, for no reason in that case.  For the same reason you would not 
call isinstance(an_instance, Abc) if you already know an_instance is an 
instance of Abc.

def Hello(self, some_class):
# since I don't know if the argument passed down *is* a class or not, I
would:
if inspect.isclass(some_class)==True:
   ...
return
###
But that obviously isn't what isclass is for.  What should I use?
Well, it's obviously what isclass is for;)  (By the way, you would be 
better not compare your conditions with True, unless it's really what 
you want).

I guess another example would be an assert on the type of argument:
def foo(someClass):
assert inspect.isclass(someClass)
# rest of code
This way errors on types are handled at the beginning and at the same 
time the code it documenting itself.  The function could also be useful 
in cases where you do some C++-like overloading mechanism.  Anyway, 
isclass, like iscallable, are functions that are not used often, but you 
still might need them.

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


Re: Why would I use inspect.isclass()?

2004-12-29 Thread Nicolas Fleury
It's me wrote:
I guess another example would be an assert on the type of argument:
def foo(someClass):
assert inspect.isclass(someClass)
# rest of code
But that would always fail!  (I just tried it).
Are you sure you haven't pass an instance instead of a class?  Remember, 
classes are also objects in Python:

>>> import inspect
>>> class A: pass
...
>>> def foo(a): assert inspect.isclass(a)
...
>>> foo(A)
>>>
Works fine and makes sense, no?  Of course, if I pass an instance 
instead of a class it would fail:

>>> myA = A()
>>> foo(myA)
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 1, in foo
AssertionError
Maybe your question is in what situations passing a class can be useful? 
   There's many examples and once you're used to that capability it can 
be powerful.  One simple example could be the generation of 
documentation; since you usually want to doc your classes, not 
instances.  So it would make sense to do something like:

def writeHtmlDoc(file, someClass): ...
Regards,
Nicolas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why would I use inspect.isclass()?

2004-12-30 Thread Nicolas Fleury
it's me wrote:
Okay, Nick, I didn't know you can pass a "Class" rather then an instance.  I
have to chew on what your example does.
But no, I want to pass an instance of a Class.  But how do I know that the
calling routine *did* pass me a class - pardon me: an instance of a Class?
You have the builtin function isinstance:
class A: pass
a = A()
print isinstance(a, A)  # True
Regards,
Nicolas
--
http://mail.python.org/mailman/listinfo/python-list


How to use subprocess

2005-03-22 Thread Nicolas Fleury
Hi,
	I want to use the subprocess module (or any standard Python module) to 
run a process:
- which stdout and stderr can each be redirected to any file-like object 
(no fileno function).
- can be cancelled with a threading.Event.

My problem is that the subprocess.Popen constructor doesn't seem to 
support file-like objects (only file objects with fileno()).

If I use subprocess.PIPE, I have the problem that the read functions of 
of the subprocess objects stdout and stderr are blocking (and I want to 
redirect them to different file-like objects, so I definitely need 
non-blocking access).  How am I supposed to do it?

Thx and regards,
Nicolas
It something like that that I would need to make work (but supporting 
file-like objects):

class CancellationException(Exception): pass
class CancellableCommand:
def __init__(self, command, stdout=nullFile, stderr=nullFile,
 refreshDelay=0.1, raiseIfNonZero=True):
self.command = command
self.stdout = stdout
self.stderr = stderr
self.refreshDelay = refreshDelay
def execute(self, cancelEvent=None):
if cancelEvent is None:
cancelEvent = threading.Event()  # dummy
exitCode = None
cmd = subprocess.Popen(
self.command, stdout=self.stdout, stderr=self.stderr)
while exitCode is None:
# Wait for event to be set for a specific delay
cancelEvent.wait(self.refreshDelay)
if cancelEvent.isSet():
kill(cmd.pid)  # implemented as in FAQ
raise CancellationException(
'Process "' + self.command + '" cancelled')
exitCode = cmd.poll()
return exitCode
--
http://mail.python.org/mailman/listinfo/python-list


Once again a unicode question

2005-03-26 Thread Nicolas Evrard
Hello,
I'm puzzled by this test I made while trying to transform a page in
html to plain text. Because I cannot send unicode to feed, nor str so
how can I do this ?
[EMAIL PROTECTED]:~$ python2.4
.Python 2.4.1c2 (#2, Mar 19 2005, 01:04:19) 
.[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
.Type "help", "copyright", "credits" or "license" for more information.
.>>> import formatter
.>>> import htmllib
.>>> html2txt = htmllib.HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter()))
.>>> html2txt.feed(u'D\xe9but')
.Traceback (most recent call last):
.  File "", line 1, in ?
.  File "/usr/lib/python2.4/sgmllib.py", line 95, in feed
.self.goahead(0)
.  File "/usr/lib/python2.4/sgmllib.py", line 120, in goahead
.self.handle_data(rawdata[i:j])
.  File "/usr/lib/python2.4/htmllib.py", line 65, in handle_data
.self.formatter.add_flowing_data(data)
.  File "/usr/lib/python2.4/formatter.py", line 197, in add_flowing_data
.self.writer.send_flowing_data(data)
.  File "/usr/lib/python2.4/formatter.py", line 421, in send_flowing_data
.write(word)
.UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128)
.>>> html2txt.feed(u'D\xe9but'.encode('latin1'))
.Traceback (most recent call last):
.  File "", line 1, in ?
.  File "/usr/lib/python2.4/sgmllib.py", line 94, in feed
.self.rawdata = self.rawdata + data
.UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 1: ordinal not in range(128)
.>>> html2txt.feed('Début')
.Traceback (most recent call last):
.  File "", line 1, in ?
.  File "/usr/lib/python2.4/sgmllib.py", line 94, in feed
.self.rawdata = self.rawdata + data
.UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
.>>>

--
(°>  Nicolas Évrard
/ )  Liège - Belgique
^^
--
http://mail.python.org/mailman/listinfo/python-list


Re: Once again a unicode question

2005-03-26 Thread Nicolas Evrard
* Serge Orlov  [23:45 26/03/05 CET]: 
Nicolas Evrard wrote:
Hello,
I'm puzzled by this test I made while trying to transform a page in
html to plain text. Because I cannot send unicode to feed, nor str so
how can I do this ?
Seems like the parser is in the broken state after the first exception.
Feed only binary strings to it.
That was that thank you very much.
--
(°>  Nicolas Évrard
/ )  Liège - Belgique
^^
--
http://mail.python.org/mailman/listinfo/python-list


Re: list-comprehension and map question (simple)

2005-03-27 Thread Nicolas Évrard
* Charles Hartman  [16:51 27/03/05 CEST]: 
I understand this toy example:
lines = "this is a group\nof lines of\nwords"
def getlength(w): return len(w)
s = map(getlength, [word for ln in lines.split() for word in  
ln.splitlines()])

(now s is [4, 2, 1, 5, 2, 5, 2, 5])
My question is whether there's any compact way to combine function  
calls, like this (which doesn't work):

lines = "this is a group\nof lines of\nwords"
def getlength(w): return len(w)
def timestwo(x): return x * 2
s = map(timestwo(getlength), [word for ln in lines.split() for word in  
ln.splitlines()])

I hope the question is clear enough. I have a feeling I'm ignoring a  
simple technique . . .
lambda !
map(lambda x: timestwo(getlength(x)), ...)
--
(°>  Nicolas Évrard
/ )  Liège - Belgique
^^
--
http://mail.python.org/mailman/listinfo/python-list


threading.Event file descriptor

2005-04-02 Thread Nicolas Fleury
Hi,
Is there any way to get the file descriptor on Unix or handle on Windows 
associated internally with a threading.Event object?  So that it can be 
used in a call to select or WaitForMultipleObjects.
Thx and regards,
Nicolas
--
http://mail.python.org/mailman/listinfo/python-list


Re: threading.Event file descriptor

2005-04-03 Thread Nicolas Fleury
[EMAIL PROTECTED] wrote:
There is no event handle used in Event object (for NT at least). Do not
know about Linux...
And there's no handle at all?  It's not important if it's not an event 
handle as long as it is an handle usable with WaitForMultipleObjects.

Also, I don't understand how it will be possible to implement 
threading.Event without using finally, at the lower level, a handle, 
since as far as I know this is the mechanisms the OS offers.

Unless you want to rewrite the interpreter (namelly
PyThread_allocate_lock.c) for platforms you are talking about, you
would be better of, if you create your own class (derived from Event,
and ovewritte aquire, release and wait methods).
I wouldn't want to derive from Event since my goal would be to submit a 
patch to make subprocess.Popen.wait take an optional threading.Event to 
kill the process.

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


Re: threading.Event file descriptor

2005-04-03 Thread Nicolas Fleury
[EMAIL PROTECTED] wrote:
//And there's no handle at all?
There is one (check thread_nt.h) you have to "propagate" HANDLE to
Pythom level. That's why, you have to change the interpreter. Do not
forget, that thread is a build-in module.
Sounds fine with me.  A fileno (or whatever) function can be added to 
threading.Event on all platforms, giving access to internal file 
descriptor/handle.

//I wouldn't want to derive from Event since my goal would be to submit
a
patch to make subprocess.Popen.wait take an optional threading.Event to
kill the process.
And that's it? Right now aquire_lock is non-interruptable, as a result
your Popen.wait is also non-interruptable, but if you pass derived
event you will be able to handle more generic cases.
I'm not 100% sure I understand what you say.  Support killing the 
process with any handle, not only an event, would be a good thing.  But 
it doesn't change the fact that, IMHO, the usefulness of threading.Event 
is just too limited if it doesn't support select or 
WaitForMultipleObjects.  I think also that threading.Thread should give 
access to its internal handle (at least thread module does).

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


Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Nicolas Fleury
Shane Hathaway wrote:
I like this PEP a lot, but your concern is valid.  Maybe Brian could
modify the PEP slightly to disambiguate.  How about using an ellipsis in
the argument list to signify suite-based keywords?  Examples:
f(...):
x = 1
class C(object):
   x = property(...):
  doc = "I'm the 'x' property."
  def fget(self):
 return self.__x
  def fset(self, value):
 self.__x = value
  def fdel(self):
 del self.__x
d = dict(...):
a = 1
b = 2
Using an ellipsis in a statement that would begin a different kind of
block is illegal and generates a syntax error.  Note that this usage
seems to fit well with the definition of "ellipsis".
http://dictionary.reference.com/search?q=ellipsis
Shane
I like the ellipsis syntax a lot, it greatly helps the proposal IMHO.
Regards,
Nicolas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to do static local variables?

2005-04-25 Thread Nicolas Fleury
Charles Krug wrote:
I've a function that needs to maintain an ordered sequence between
calls.
In C or C++, I'd declare the pointer (or collection object) static at
the function scope.
What's the Pythonic way to do this?
Is there a better solution than putting the sequence at module scope?
Thanks.
You might want a generator.  Search for yield keyword.
Regards,
Nicolas
--
http://mail.python.org/mailman/listinfo/python-list


Re: E-commerce system in Python

2016-03-23 Thread Nicolas Évrard
* Arshpreet Singh  [2016-03-18 05:25 +0100]: 

I am looking for an E-commerce system in python to sell things things
online, which can also be responsive for Android and IOS.

A  quick Google search brought me  http://getsaleor.com/ it uses
Django, Is there any available one using Flask or newly born asyncio
based framework?


You could build your own e-commerce system using Tryton and
flask-tryton.

http://www.tryton.org/
https://pypi.python.org/pypi/flask_tryton

We're in the process of adding basic cart functionalities to the ERP.
It will probably be included in the near future.

--
Nicolas Évrard - B2CK SPRL
E-mail/Jabber: [email protected]
Tel: +32 472 54 46 59
Website: http://www.b2ck.com/
--
https://mail.python.org/mailman/listinfo/python-list


Which type should be used when testing static structure appartenance

2015-11-17 Thread Nicolas Évrard

Hello,

I saw the following retweet by Raymond Hettinger in this morning:

   https://twitter.com/sanityinc/status/666485814214287360

   Programming tip: many of those arrays and hashes in your code
   should actually be sets. Match data structures to data
   constraints!

I saw just in time because in a review I wrote something like this:

   if operator not in ('where', 'not where')

and my colleague proposed that I should use a list instead of a tuple.
But reading the mentioned tweet I tend to think that a set would be a
better choice.

What are your opinion on this issue (I realize it's not something of
the utmost importance but rather a "philosophical" question).

--
Nicolas Évrard - B2CK SPRL
E-mail/Jabber: [email protected]
Tel: +32 472 54 46 59
Website: http://www.b2ck.com/
--
https://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb Python API: Unable to connect

2005-12-27 Thread Nicolas Kassis
Dennis Lee Bieber wrote:

>On 26 Dec 2005 21:39:11 -0800, "Mondal" <[EMAIL PROTECTED]> declaimed
>the following in comp.lang.python:
>
>  
>
>c=MySQLdb.Connect(host='localhost',user='root',passwd='',db='shop',port=330­6)
>  
>
>
>   So what is that - doing in the port number... So far as I know,
>nothing reasonable lives on port 324... 
>
>  
>
I don't see anything with 324 in there ? What do you mean ?

>   If that is supposed to be the standard MySQL port, just leave it
>off... Granted, I'm not running 5.x... (and I'm behind both a router
>firewall and a software firewall AND MySQL's own authorization scheme,
>so the user/password won't do anyone any good at getting into my system)
>
>myDB = MySQLdb.connect(host="localhost",
>   user="BestiariaCP",
>   #passwd="web-asst",
>   db="bestiaria")
>
>   Note the lack of a port number specification. The default port for
>MySQL is 3306; if your server is running on the default, you don't need
>to specify it. Error 10061 is the generic Windows socket "connection
>refused" -- since I doubt you have anything on port 324, that is to be
>expected.
>  
>
Just to make sure, ( Not trying to be a smart ass) are you sure the
database is running ? That seems like the most obvious thing.

Nic

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


Patch : doct.merge

2005-12-27 Thread Nicolas Lehuen
Hi,

I've posted this patch on Source forge :

http://sourceforge.net/tracker/index.php?func=detail&aid=1391204&group_id=5470&atid=305470

If you want to update a dictionary with another one, you can simply use
update :

a = dict(a=1,c=3)
b = dict(a=0,b=2)
a.update(b)
assert a == dict(a=0,b=2,c=3)

However, sometimes you want to merge the second dict into the first,
all while keeping the values that are already defined in the first.
This is useful if you want to insert default values in the dictionary
without overriding what is already defined.

Currently this can be done in a few different ways, but all are awkward
and/or inefficient :

a = dict(a=1,c=3)
b = dict(a=0,b=2)

Method 1:
for k in b:
if k not in a:
a[k] = b[k]

Method 2:
temp = dict(b)
temp.update(a)
a = temp

This patch adds a merge() method to the dict object, with the same
signature and usage as the update() method. Under the hood, it simply
uses PyDict_Merge() with the override parameter set to 0 instead of 1.
There's nothing new, therefore : the C API already provides this
functionality (though it is not used in the dictobject.c scope), so why
not expose it ? The result is :

a = dict(a=1,c=3)
b = dict(a=0,b=2)
a.merge(b)
assert a == dict(a=1,b=2,c=3)

Does this seem a good idea to you guys ?

Regards,
Nicolas

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


Re: Patch : doct.merge

2005-12-28 Thread Nicolas Lehuen
Here's method 3 :

# Python 2.3 (no generator expression)
a.update([(k,v) for k,v in b.iteritems() if k not in a])

# Python 2.4 (with generator expression)
a.update((k,v) for k,v in b.iteritems() if k not in a)

It's a bit cleaner but still less efficient than using what's already
in the PyDict_Merge C API. It's even less efficient than method 1 and 2
! Here is the benchmark I used :

import timeit

init = '''a = dict((i,i) for i in xrange(1000) if i%2==0); b =
dict((i,i+1) for i in xrange(1000))'''

t = timeit.Timer('''for k in b:\n\tif k not in a:\n\t\ta[k] =
b[k]''',init)
print 'Method 1 : %.3f'%t.timeit(1)

t = timeit.Timer('''temp = dict(b); temp.update(a); a = temp''',init)
print 'Method 2 : %.3f'%t.timeit(1)

t = timeit.Timer('''a.update((k,v) for k,v in b.iteritems() if k not in
a)''',init)
print 'Method 3 : %.3f'%t.timeit(1)

t = timeit.Timer('''a.merge(b)''',init)
print 'Using dict.merge() : %.3f'%t.timeit(1)

Here are the results :

Method 1 : 5.315
Method 2 : 3.855
Method 3 : 7.815
Using dict.merge() : 1.425

So using generator expressions is a bad idea, and using the new
dict.merge() method gives an appreciable performance boost (~ x 3.73
here).

Regards,
Nicolas

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


csv file or sqlite ?

2006-07-25 Thread frevol nicolas
hi,

I am programming a filter for websites. to check if an
url is in the blacklist, i have used a csv file. i
have try to use sqlite but it looks as fast as csv
files.

Can you tell me if sqlite is faster than csv files ?
or not ?

thanks






___ 
Découvrez un nouveau moyen de poser toutes vos questions quelque soit le sujet 
! 
Yahoo! Questions/Réponses pour partager vos connaissances, vos opinions et vos 
expériences. 
http://fr.answers.yahoo.com 

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


unicode "table of character" implementation in python

2006-08-22 Thread Nicolas Pontoizeau
Hi,

I am handling a mixed languages text file encoded in UTF-8. Theres is
mainly French, English and Asian languages. I need to detect every
asian characters in order to enclose it by a special tag for latex.
Does anybody know if there is a unicode "table of character"
implementation in python? I mean, I give a character and python replys
me with the language in which the character occurs.

Thanks in advance

-- 
http://www.nicolas.pontoizeau.org/
Nicolas Pontoizeau - Promotion EFREI 2005
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode "table of character" implementation in python

2006-08-22 Thread Nicolas Pontoizeau
2006/8/22, Brian Beck <[EMAIL PROTECTED]>:
> Nicolas, check out the unicodedata module:
> http://docs.python.org/lib/module-unicodedata.html
>
> Find "import unicodedata" on this page for how to use it:
> http://www.amk.ca/python/howto/unicode
>
> I'm not sure if it has built-in support for finding which language block a
> character is in, but a table like this might help you:
> http://www.unicode.org/Public/UNIDATA/Blocks.txt

As usual, Python has a solution that goes beyond my needs!
Thanks for the links I will dive into it.

Nicolas

-- 
http://www.nicolas.pontoizeau.org/
Nicolas Pontoizeau - Promotion EFREI 2005
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to tell what is the IP of my PC .

2006-11-08 Thread Nicolas G
On 11/9/06, Tim Williams <[EMAIL PROTECTED]> wrote:
On 8 Nov 2006 15:35:31 -0800, NicolasG <[EMAIL PROTECTED]> wrote:> How can I use python to get the real IP address of my DSL router (when> my PC is part of the local home LAN) ?
The router will the PC's default gateway IP address,  if you are on awindows platform,  you can view it by typing IPCONFIG (enter) from acommand prompt.This is the  router local IP, I need to get the router "outside" IP witch is the real one. 
A quick google, gave me this,  look at the comments at the end for anexample of finding the Default Gateway IP address using Python
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162994import
 win32api raise the error "module not exsit"and socket.gethostbyname(name)the router doesn't have a hostname.cheers ;)-- Nicolas GSkype: nicolasg_
mobile: +30 69 45 714 578
-- 
http://mail.python.org/mailman/listinfo/python-list

HTTPBasicAuthHandler doesn't work

2006-07-09 Thread nicolas . surribas
Hi !
I'm trying to add the HTTP basic authentification to my web spider but
it doesn't work...
The HTTPBasicAuthHandler don't send the headers for authentification
:-(

Here is the code : http://devloop.lyua.org/releases/lswww_urllib2.py

def
__init__(self,rooturl,firsturl=[],forbidden=[],proxy={},cookie="",auth_basic=[]):
root=rooturl
self.excluded=forbidden
self.proxy=proxy
self.cookie=cookie
self.auth_basic=auth_basic
if root[-1]!="/":
root+="/"
if(self.checklink(root)):
print "Invalid link argument"
sys.exit(0)
for lien in firsturl:
if(self.checklink(lien)):
print "Invalid link argument"
sys.exit(0)
server=(root.split("://")[1]).split("/")[0]
self.root=root
self.server=server
director = urllib2.OpenerDirector()

director.add_handler(urllib2.HTTPHandler())
director.add_handler(urllib2.HTTPSHandler())

if self.proxy!={}:
director.add_handler(urllib2.ProxyHandler(self.proxy))

if self.auth_basic!=[]:

auth=urllib2.HTTPBasicAuthHandler(urllib2.HTTPPasswordMgrWithDefaultRealm())
auth.add_password(None, self.root, self.auth_basic[0],
self.auth_basic[1])
director.add_handler(auth)

if self.cookie!="":
cj = cookielib.LWPCookieJar()
if os.path.isfile(self.cookie):
cj.load(self.cookie,ignore_discard=True)
director.add_handler(urllib2.HTTPCookieProcessor(cj))

urllib2.install_opener(director)

Where is the problem ?
Thanks !

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


Re: Python web service ...

2006-08-28 Thread Nicolas G
If I want to run my program as a web service I need to setup a
webserver , am I right ?
Whars that difference ? can a webservice be run without a webserver ?

On 8/29/06, Jorge Vargas <[EMAIL PROTECTED]> wrote:
> On 26 Aug 2006 04:07:35 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > Hi folks, I have accomplished to make a python program that make some
> > image manipulation to bmp files.
> > I now want to provide this program as a web service. A user can visit a
> > site and through a web interface he should upload the file to the web
> > server , the server then will do the image process with the python
> > program I have wrote and when it finish the user must get the image
> > file back .
> >
> > My question is how difficult is to set up a web server that can run
> > python easy ? should I try ZOPE or there is something better in mind ?
>
> is that webservice or webserver?
> if webservice try ZSI of it's a webserver why don't you try CherryPy?
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>


-- 
Nicolas G

mobile: +30 69 45 714 578
-- 
http://mail.python.org/mailman/listinfo/python-list


python and snmp

2006-09-18 Thread Nicolas Miyasato
Hi all, I was just wondering if someone here had any experience with
some of these implementations of the snmp protocol?

pysnmp, libsnmp, snmpy.

Does anybody know of another implementation?

thanks in advance!!!

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


Re: VB to Python migration

2006-01-27 Thread Nicolas Kassis
Josh wrote:

> We have a program written in VB6 (over 100,000 lines of code and
> 230 UI screens) that we want to get out of VB and into a better
> language. The program is over 10 years old and has already been
> ported from VB3 to VB6, a job which took over two years. We would
> like to port it to Python, but we need to continue to offer
> upgrades and fixes to the current VB6 version. Does anybody know of
> ways we could go about rewriting this, one screen at a time, in
> Python, and calling the screens from the existing program?
>
> We are also looking for a graphics toolkit to use. IronPython with
> it's .NET bindings and ability to integrate with Visual Studio
> looks good, but leaves that bad MS taste in the mouth.
>
> We currently use a MS Access back end and need to migrate to a
> proper SQL server. We need to leave options open for SQL Server
> (for customers who want to use existing infrastructure) and
> something like MySQL or PostgreSQL. But in the mean time, we need
> to be able to access an MSAccess (Jet) database from Python.
>
> Any answers/suggestions/pointers are greatly appreciated.
>
> Thanks,
>
> Josh Isted

For the Database, you should use the SQLObject(sqlobject.org) module.

Nic

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


Re: Python vs C for a mail server

2006-01-28 Thread Nicolas Lehuen
If your friend is proficient in C/C++ then learning Python should not
be a pain. Quite the contrary, it should be an enlightnement. Being
good in C/C++ AND Python is a killer combination, as you can promptly
and efficiently code big chunks of your application in Python and
interface with C/C++ code where (and if) high performance is required.

Now, you should definitely check the requirements for the homework.

If the assignment is about being able to decipher an RFC and implement
it correctly with a nice software design, then I would definitely opt
for Python. Having to squish memory management, string manipulation and
character encoding bugs in C/C++ is not fun and not related to
high-level design nor RFC support.

If it's just a way to throw a programming challenge at your friend's
face, then you should check whether it's okay to use Python rather than
C/C++, otherwise he could be charged of cheating by using a more
productive language :).

Regards,
Nicolas

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


Re: Python vs C for a mail server

2006-01-28 Thread Nicolas Lehuen
Jens Theisen wrote:
> Please don't be offended, but if anyone could make a point of how Python's
> disadvantages in these regards could be alleviated, I'd be very
> interested.
>
> Jens

Well, I write Java, C++ and Python code, and I have posted a few
thoughts about this on my blog :

http://nicolas.lehuen.com/

My two latest problems with coding in C++ are due to the environments :
libraries using different string types and the whole problem with the
building system. I love the language, but I get a much better leverage
through Python and Java due to the quality and ease of use of their
built-in and third party libraries. I use C++ only for my core data
structure (namely a tuned version of a ternary search tree which I use
to build full text indices).

Regards,
Nicolas

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


Make staticmethod objects callable?

2006-02-28 Thread Nicolas Fleury
Hi everyone,
I was wondering if it would make sense to make staticmethod objects 
callable, so that the following code would work:

class A:
 @staticmethod
 def foo(): pass
 bar = foo()

I understand staticmethod objects don't need to implement __call__ for 
their other use cases, but would it still make sense to implement 
__call__ for that specific use case?  Would it be error-prone in any way?

Thx and regards,
Nicolas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Make staticmethod objects callable?

2006-02-28 Thread Nicolas Fleury
Felipe Almeida Lessa wrote:
> Em Ter, 2006-02-28 às 15:17 -0500, Nicolas Fleury escreveu:
> 
>>class A:
>> @staticmethod
>> def foo(): pass
>> bar = foo()
> 
> 
> # Why not:
> 
> def foo(): pass
> 
> class A:
>   bar = foo()
>   foo = staticmethod(foo)
> 

Well, you could even do:

class A:
 def foo(): pass
 bar = foo()
 staticmethod(foo)

But it's a bit sad to have a special syntax for decorators then.  It's a 
usability problem, nothing to do with functionality.  There's obvious 
workarounds, but IMHO any user saying "it should just work" is at least 
partly right.

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

Re: Make staticmethod objects callable?

2006-02-28 Thread Nicolas Fleury
Steven Bethard wrote:
> Nicolas Fleury wrote:
> 
>> I was wondering if it would make sense to make staticmethod objects 
>> callable, so that the following code would work:
>>
>> class A:
>> @staticmethod
>> def foo(): pass
>> bar = foo()
> 
> Do you have a real-world use case?  I pretty much never use 
> staticmethods (preferring instead to use module-level functions) so I'm 
> having a hard time coming up with some code where this would be really 
> useful.  I'm also a little wary of breaking the parallel between 
> classmethod and staticmethod which are currently *just* descriptors 
> (without any other special functionality).

Well, IMHO, if staticmethod is worth being standard, than calling these 
static methods inside the class definition is worth being supported.  To 
be honest I don't use static methods like you, but users come see me 
asking "Why?" and I find their code logically structured so I conclude 
there's a usability problem here.

> Maybe instead of making just staticmethods callable, both staticmethods 
> and classmethods could gain an 'im_func' attribute like bound and 
> unbound methods have?

I don't like it either (__get__ can be called anyway).  My problem is 
the expectation of the user.  I wonder if it should just work.  Adding a 
few lines of code in staticmethod is worth it if it avoids all these 
questions over and over again, no?

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


Re: Make staticmethod objects callable?

2006-03-01 Thread Nicolas Fleury
Steven Bethard wrote:
> ...
> Yes, you have to explain descriptors, but at the point that you start 
> trying to do funny things with staticmethods and classmethods, I think 
> you need to start learning about them anyway.)

That's all good points, but IMHO, descriptors are a much more advanced 
Python feature than static methods, especially for programmers from 
other backgrounds, like Java/C#/C++.  We basically have the choice 
between hiding something unnecessarily complex or force to understand a 
useful feature;)

> All that said, you should probably just submit a patch and see what 
> happens.  I'll make a brief comment on it along the above lines, but 
> since I'm not a committer, it's not really worth your time to try to 
> convince me. ;)

I might do it, but even if I'm not a commiter, I'll continue trying to 
convince myself;)

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


wxpython and wxtextctrl

2005-05-18 Thread Nicolas Pourcelot
Hello,
my script worked well until today : when I tried to launch it, I got the 
following :

 frame = MyFrame(None,-1,"Geometrie",size=wx.Size(600,400))
   File "/home/nico/Desktop/wxGeometrie/version 0.73/geometrie.py", line 
74, in __init__
 self.commande.Bind(wx.EVT_CHAR, self.EvtChar)
AttributeError: wxTextCtrl instance has no attribute 'Bind'

(self.commande is a wxTextCtrl instance)
I don't understand : why did wxTextCtrl lost its Bind attribute ??
As there's not so much changes on my computer since yesterday, I suppose 
this is due to Boa package installation on my Ubuntu Hoary ?
Does Boa installation changes wxpython version ?
Is wxTextCtrl attribute .Bind() obsolete ??

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


Re: wxpython and wxtextctrl

2005-05-19 Thread Nicolas Pourcelot
Ok, as I guessed, it was Boa installation which changed the wxpython 
version used.
I removed Boa...
Thanks !
Nicolas

Greg Krohn a écrit :
> Nicolas Pourcelot wrote:
> 
>> Hello,
>> my script worked well until today : when I tried to launch it, I got 
>> the following :
>>
>> frame = MyFrame(None,-1,"Geometrie",size=wx.Size(600,400))
>>   File "/home/nico/Desktop/wxGeometrie/version 0.73/geometrie.py", 
>> line 74, in __init__
>> self.commande.Bind(wx.EVT_CHAR, self.EvtChar)
>> AttributeError: wxTextCtrl instance has no attribute 'Bind'
>>
>> (self.commande is a wxTextCtrl instance)
>> I don't understand : why did wxTextCtrl lost its Bind attribute ??
>> As there's not so much changes on my computer since yesterday, I 
>> suppose this is due to Boa package installation on my Ubuntu Hoary ?
>> Does Boa installation changes wxpython version ?
>> Is wxTextCtrl attribute .Bind() obsolete ??
>>
>> Thanks,
>> Nicolas
> 
> 
> control.Bind is relativly new. The wxTextCtrl notation (vs wx.TextCtrl) is
> the old way (but it IS kept around for backwards compatablility). My guess
> is that your code is for for a newer version of wxPython than what you
> actually have.
> 
> Try printing the version from in your code:
> 
> import wxPyhon
> print wxPython.__version__
> self.commande.Bind(wx.EVT_CHAR, self.EvtChar)
> 
> -greg
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing 2 similar strings?

2005-05-25 Thread nicolas . lehuen
William Park a écrit :
> How do you compare 2 strings, and determine how much they are "close" to
> each other?  Eg.
> aqwerty
> qwertyb
> are similar to each other, except for first/last char.  But, how do I
> quantify that?
>
> I guess you can say for the above 2 strings that
> - at max, 6 chars out of 7 are same sequence --> 85% max
>
> But, for
> qawerty
> qwerbty
> max correlation is
> - 3 chars out of 7 are the same sequence --> 42% max
>
> (Crossposted to 3 of my favourite newsgroup.)

Hi,

If you want to use phonetic comparison, here are some algorithms that
are reportedly more efficient than Soundex :

Double-Metaphone
NYSIIS
Phonex

Of course, phonetic algorithms have a lot of disadvantages, the main
one being that they know about one way to pronounce words (usually a
rather rigid, anglo-saxon way) which may not be the right way (hence
the examples given before for Gaellic surnames). But these ones are far
"better" than soundex.

Regards,

Nicolas Lehuen

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-03 Thread Nicolas Fleury
Guido van Rossum wrote:
> After many rounds of discussion on python-dev, I'm inviting public
> comments for PEP 343. Rather than posting the entire PEP text here,
> I'm inviting everyone to read it on line
> (http://www.python.org/peps/pep-0343.html) and then post comments on a
> Wiki page I've created for this purpose
> (http://wiki.python.org/moin/WithStatement).
> 
> I think this is a good one; I hope people agree. Its acceptance will
> obsolete about 4 other PEPs! (A sign that it fulfills a need and that
> the proposed solution is powerful.)

I like the PEP very much; I guess most C++ programmers are missing that 
capability in Python.  (I was following the discussion on python-dev, 
and I'm pleased and surprised how good the result/compromise is).

What about making the ':' optional (and end implicitly at end of current 
block) to avoid over-indentation?

def foo():
 with locking(someMutex)
 with opening(readFilename) as input
 with opening(writeFilename) as output
 ...

would be equivalent to:

def foo():
 with locking(someMutex)
 with opening(readFilename) as input
 with opening(writeFilename) as output
 ...

Regards,

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-03 Thread Nicolas Fleury
Andrew Dalke wrote:
>>def foo():
>> with locking(someMutex)
>> with opening(readFilename) as input
>> with opening(writeFilename) as output
>> ...
> 
> 
> Nothing in Python ends at the end of the current block.
> They only end with the scope exits.  The order of deletion
> is not defined, and you would change that as well.

There's no change in order of deletion, it's just about defining the 
order of calls to __exit__, and they are exactly the same.  As far as I 
know, PEP343 has nothing to do with order of deletion, which is still 
implementation-dependant.  It's not a constructor/destructor thing like 
in C++ RAII, but __enter__/__exit__.

But yes, it creates a precedent by creating a statement affecting the 
end of the current indentation block.  But that's what this PEP is all 
about...

> Your approach wouldn't allow the following

No, I said making the ':' *optional*.  I totally agree supporting ':' is 
useful.

> If the number of blocks is a problem it wouldn't be that
> hard to do
> 
> with multi( locking(someMutex),
> opening(readFilename),
> opening(writeFilename) ) as _, input, output:
>   ...

True.  But does it look as good?  Particularly the _ part?

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Nicolas Fleury
Andrew Dalke wrote:
> The implementation would need to track all the with/as forms
> in a block so they can be __exit__()ed as appropriate.  In this
> case ghi.__exit() is called after jkl.__exit__() and
> before defg.__exit__
> 
> The PEP gives an easy-to-understand mapping from the proposed
> change to how it could be implemented by hand in the existing
> Python.  Can you do the same?

I think it is simple and that the implementation is as much 
straight-forward.  Think about it, it just means that:

 > with abc
 >
 > with defg:
 >   with ghi
 >   with jkl:
 > 1/0

is equivalent to:

 > with abc:
 >
 >   with defg:
 > with ghi:
 >   with jkl:
 > 1/0

That's it.  Nothing more complex.  It's only about syntax.

> I have not idea if the problem you propose (multiple with/as
> blocks) will even exist so I can't comment on which solution
> looks good.  It may not be a problem in real code, so not needing
> any solution.

Good point.  As a C++ programmer, I use RAII a lot.  However, there's 
situations in C++ that don't apply, like allocating dynamic memory in a 
scope.  However, I still expect some Python programmers to use it enough 
to ask for that syntax to be added, in the same way operators like += 
have been added.

But there's another point that has nothing to do with how many "with" 
statements you have in a function.  In C++, very very rarely I've seen 
something like:

void foo() {
 {  // (define a scope for the Lock object)
Lock locking(myMutex);
...
 }
 ...
 {
Lock locking(myMutex);
...
 }
}

So I come to another conclusion: the indentation syntax will most of the 
time result in a waste of space.  Typically a programmer would want its 
with-block to end at the end of the current block.

So basically, there's two 10-90% points, one in favor of my proposal, 
one against:

- Most of the time, you don't have a lot of with-statements in a single 
function, so not so much indentation.
- Most of the time, a with-statement ends at the end of current block, 
so indentation-syntax most of the time result in a waste of space.

The way to see my proposal is not "to be used when you have multiple 
with-blocks" but instead "never use the ':' syntax, unless necessary". 
The day some code need it, it's very easy to add a ':' and indent some 
code with our favorite editor.

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Nicolas Fleury
Ilpo Nyyssönen wrote:
> Nicolas Fleury <[EMAIL PROTECTED]> writes:
>>What about making the ':' optional (and end implicitly at end of current 
>>block) to avoid over-indentation?
>>
>>def foo():
>>with locking(someMutex)
>>with opening(readFilename) as input
>>with opening(writeFilename) as output
>>...
> 
> 
> How about this instead:
> 
> with locking(mutex), opening(readfile) as input:
> ...
> 
> So there could be more than one expression in one with.

I prefer the optional-indentation syntax.  The reason is simple (see my 
discussion with Andrew), most of the time the indentation is useless, 
even if you don't have multiple with-statements.  So in my day-to-day 
work, I would prefer to write:

def getFirstLine(filename):
 with opening(filename) as file
 return file.readline()

than:

def getFirstLine(filename):
 with opening(filename) as file:
 return file.readline()

But I agree that in the case of only one with-statement, that's no big deal.

Also, if multiple with-statements are separated by other indentating 
statements, your proposal doesn't help:

with locking(lock)
if condition:
 with opening(filename) as file
 for line in file:
 ...

would still be needed to be written:

with locking(lock):
 if condition:
 with opening(filename) as file:
 for line in file:
 ...

Regards,
Nicolas

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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-04 Thread Nicolas Fleury
Andrew Dalke wrote:
> Consider the following
>
> server = open_server_connection()
> with abc(server)
> with server.lock()
> do_something(server)
>
> server.close()
>
> it would be translated to
>
> server = open_server_connection()
> with abc(server):
>   with server.lock()
> do_something(server)
> server.close()
>
> when I meant for the first code example to be implemented
> like this
>
> server = open_server_connection()
> with abc(server):
>   with server.lock()
> do_something(server)
>
> server.close()

That's an interesting point.  But I'm not sure if it is a realistic
error.  It would be like using a with-statement without knowing what it
does.  Also, and it seems we agree, these cases are very rare.

>
> (It should probably use the with-block to handle the server open
> and close, but that's due to my lack of imagination in coming up
> with a decent example.)
>
> Because of the implicit indentation it isn't easy to see that
> the "server.close()" is in an inner block and not at the outer
> one that it appears to be in.  To understand the true scoping
> a reader would need to scan the code for 'with' lines, rather
> than just looking at the layout.

But with both syntaxes you only look at the indentation layout, no?  If
you want to know the "scope" of something as you said, it means you have
already scan its "with" statement.  You only need after that to look at
the indentation layout, as with indentation syntax.

It's however less obvious at first look that with-statements implies
some scope, but I feel that Python newcomers usually do the opposite
error instead, thinking their variables have a defined scope as in some
other languages.

> A test for how often this is needed would be to look in existing
> code for the number of try/finally blocks.  I have seen and
> written some gnarly deeply stacked blocks but not often - once
> a year?
>
> That's not to say it's a good indicator.  A lot of existing code
> looks like this

I agree.  It's hard to find a good indicator.  In my case I use both my
Python code (with try/finally typically ending a function) and my C++
code (with typically no {} block created for RAII object scope).  So, my
conclusion, most of the time the indentation will be useless.

> What I mean by all of this is that the new PEP may encourage
> more people to use indented blocks, in a way that can't be
> inferred by simply looking at existing code.  In that case
> your proposal, or the one written

Totally agree.  The with-statement will open the door to new programming
patterns in Python and it's hard to tell from status quo how much it
will be used.

Regards,
Nicolas


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


Re: For review: PEP 343: Anonymous Block Redux and Generator Enhancements

2005-06-05 Thread Nicolas Fleury
Steven Bethard wrote:
> Can you do the same thing for your proposal?  As I understand it you 
> want some sort of implicitly-defined BLOCK that starts the line after 
> the with statement and runs to the end of the current block...

Yes.  I totally agree with the syntax in the PEP, it provides a 
necessary feature.  I'm just suggesting to make the indentation 
*optional*, because most of the time it is not necessary.

> Do you think the benefit of less indentation outweighs the added 
> complexity of explaining the construct?  I still can't think of a good 
> way of explaining the semantics you want.  If you could provide an 
> explanation that's simple and as explicit as Guido's explanation in PEP 
> 343, I think that would help your case a lot.

Since the current syntax would be there, the no-indentation syntax can 
be explained in terms of the indentation syntax:

"""
To avoid over-indentation, a with-statement can avoid defining a new 
indentation block.  In that case, the end of the with block is the end 
of the current indentation block.

with EXPR as VAR
REST OF BLOCK

is equivalent to

with EXPR as VAR:
 BLOCK
"""

What do you think?  I fail to see the complexity...

> P.S.  I think it's a great sign that people are mainly squabbling about 
> syntax here.  More likely than not, Guido's already made his mind up 
> about the syntax.  So, since no one seems to have any real problems with 
> the semantics, I'm hopeful that we'll get a direct implementation of PEP 
> 343 in the next Python release. =)

It's important to note that nobody is against the PEP syntax.  We are 
only talking about adding things to it (optional indentation, or 
multiple-as as with import).

All these changes can also be made later, so no proposition should slow 
down the implementation of the PEP.

Regards,
Nicolas

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


Re: For review: PEP 343: Anonymous Block Redux and GeneratorEnhancements

2005-06-05 Thread Nicolas Fleury
Delaney, Timothy C (Timothy) wrote:
> Nicolas Fleury wrote:
>>def getFirstLine(filename):
>> with opening(filename) as file
>> return file.readline()
> 
> Your tastes definitely disagree with the majority of Python programmers
> then, including Guido. Scoping is defined in Python by indentation.

I'm very happy to met someone who can speak for the majority of Python 
programmers, I should have chat with you in the first place;)

But you're right, that would make a precedent in Python, and that is 
probably what makes my proposal so bad.  Someone could argue that this 
should be allowed too:

with locking(lock)
if condition
with opening(filename) as file
for line in file
...

And that's horrible IMO (and a no-no to me).

About the majority of Python programmers, a lot of newcomers come from 
languages where you don't have to make a new block for an 
acquire/release pattern.

Also, the following syntax:
decorate staticmethod:
 def foo():
 ...
have been rejected for decorators.  All this to say that 
over-indentation can be an issue.

> If you want the above sort of thing, you're going to have to write a new
> PEP, and I'd be very surprised to see it accepted. But there's nothing
> stopping you from doing so.
> 
> 
>>def getFirstLine(filename):
>> with opening(filename) as file:
>> return file.readline()
> 
> This is beautiful and explicit. What else could you want?

Did you deliberately keep that example instead of the other one in the 
message?

with locking(lock):
 if condition:
 with opening(filename) as file:
 for line in file:
 ...

It is definately explicit, but beautiful?

Add to that the indentation of the class, of the method, a few more 
with-statements and you end up with something that makes it difficult to 
  respect PEP008 (4 spaces indentation and lines < than 80).

Compare that with the += like operators.  It is not beautiful, but very 
usable.  The same can be said for @decorators.

> The syntax:
> 
> with EXPR1 as VAR1, EXPR2 as VAR2:
> ...

That syntax doesn't help in the previous example.

> was discussed on python-dev. It wasn't explicitly rejected, but the
> feeling seemed to be that it was an unnecessary complication as far as
> PEP 343 is concerned. There's nothing stopping another PEP proposing
> this as an extension to PEP 343, and there's nothing stopping that being
> in Python 2.5 if it's accepted.

I totally agree.  I don't want to change PEP343, but keeping the door 
open for a no-indentation syntax is a good idea.

> PEP 343 was originally PEP 340 (and several other things) and was quite
> complicated at one point (it originally contained PEP 342 as well). The
> PEP in its current state represents 2 months of discussion, complication
> and (finally) simplification. Its semantics are clear and unambiguous.
> And (as Guido states) it will obsolete 4(?) other PEPs.

I know, and I followed these discussions even in vacation.  I'm very 
happy with the result.  I'm just pointing that it will result in 
over-indented code.  In some situations indentation is necessary anyway, 
so the PEP syntax is fine.

Will I write a PEP for that?  Maybe.  I think the first step is to just 
use with-statements in real-life code and see how it comes.  But I will 
not be surprised if it is added someday.

Regards,
Nicolas

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


Re: "also" to balance "else" ?

2005-06-15 Thread Nicolas Fleury
Ron Adam wrote:
> It occurred to me (a few weeks ago while trying to find the best way to 
> form a if-elif-else block, that on a very general level, an 'also' 
> statement might be useful.  So I was wondering what others would think 
> of it.

But the feature is already there:

for x in :
 BLOCK1
 if :
 ALSO-BLOCK
 break
else:
 BLOCK2

If find "else" fine, since the only times I used it is in searches:

for x in 
 BLOCK1
 if : break
else:
 raise Exception('Not found')

In that case, 'else' sounds like the good keyword.

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


strxfrm works with unicode string ?

2005-06-17 Thread nicolas . riesch
I am trying to use strxfm with unicode strings, but it does not work.
This is what I did:

>>> import locale
>>> s=u'\u00e9'
>>> print s
é
>>> locale.setlocale(locale.LC_ALL, '')
'French_Switzerland.1252'
>>> locale.strxfrm(s)

Traceback (most recent call last):
  File "", line 1, in -toplevel-
locale.strxfrm(s)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in
position 0: ordinal not in range(128)
>>>

Someone sees what I did wrong ?

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


Re: strxfrm works with unicode string ?

2005-06-17 Thread nicolas . riesch
Gruëzi, Gerald ;-)

Well, ok, but I don't understand why I should first convert a pure
unicode string into a byte string.
The encoding ( here, latin-1) seems an arbitrary choice.

Your solution works, but is it a workaround or the real way to use
strxfrm ?
It seems a little artificial to me, but perhaps I haven't understood
something ...

Does this mean that you cannot pass a unicode string to strxfrm ?

Bonne journée !

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


Re: python in academics?

2007-11-08 Thread Nicolas DERAM
2007/11/6, Nicolas.Chauvat <[EMAIL PROTECTED]>:
>
> Le Mon, 29 Oct 2007 20:39:29 -0700, sandipm a écrit:
>
> > seeing posts from students on group. I am curious to know, Do they teach
> > python in academic courses in universities?
>
> I am teaching assistant for the course
>
> http://www.etudes.ecp.fr/cours/claroline/course/index.php?cid=TI1210
>
> held at http://www.ecp.fr/index_html_en
>
> They are also making an increasing use of python over there.


Python is also taught at the university of Calais (France).
A master about free software opened last year.

http://dpt-info.univ-littoral.fr/mediawiki/index.php/I2L:Accueil

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

Re: Pythonic way to determine if one char of many in a string

2009-02-15 Thread Nicolas Dandrimont
* [email protected]  [2009-02-16 00:17:37 -0500]:

> I need to test strings to determine if one of a list of chars is
> in the string. A simple example would be to test strings to
> determine if they have a vowel (aeiouAEIOU) present.
> I was hopeful that there was a built-in method that operated
> similar to startswith where I could pass a tuple of chars to be
> tested, but I could not find such a method.
> Which of the following techniques is most Pythonic or are there
> better ways to perform this type of match?
> # long and hard coded but short circuits as soon as match found
> if 'a' in word or 'e' in word or 'i' in word or 'u' in word or
> ... :
> -OR-
> # flexible, but no short circuit on first match
> if [ char for char in word if char in 'aeiouAEIOU' ]:
> -OR-
> # flexible, but no short circuit on first match
> if set( word ).intersection( 'aeiouAEIOU' ):

I would go for something like:

for char in word:
if char in 'aeiouAEIUO':
char_found = True
break
else:
char_found = False

(No, I did not forget to indent the else statement, see
http://docs.python.org/reference/compound_stmts.html#for)

It is clear (imo), and it is seems to be the intended idiom for a search
loop, that short-circuits as soon as a match is found.

Cheers,
-- 
Nicolas Dandrimont

linux: the choice of a GNU generation
([email protected] put this on Tshirts in '93)


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to determine if one char of many in a string

2009-02-16 Thread Nicolas Dandrimont
* [email protected]  [2009-02-16 00:48:34 -0500]:

> Nicolas,
> 
> > I would go for something like:
> > 
> > for char in word:
> > if char in 'aeiouAEIUO':
> > char_found = True
> > break
> > else:
> > char_found = False
> >
> > It is clear (imo), and it is seems to be the intended idiom for a 
> > search loop, that short-circuits as soon as a match is found.
> 
> Thank you - that looks much better that my overly complicated attempts.
> 
> Are there any reasons why I couldn't simplify your approach as follows?
> 
> for char in word:
> if char in 'aeiouAEIUO':
>     return True
> return False

If you want to put this in its own function, this seems to be the way to go.

Cheers,
-- 
Nicolas Dandrimont

The nice thing about Windows is - It does not just crash, it displays a
dialog box and lets you press 'OK' first.
(Arno Schaefer's .sig)


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >