Re: Function definition

2006-06-20 Thread bruno at modulix
faulkner wrote:
(pelase don't top-post - fixed)
 aarondesk wrote:
 
(snip)
Now I've tried putting the function declaration after the call but the
program wouldn't work. Is there anyway to put function declarations at
the end of the program, rather than putting them at the beginning,
which is rather clunky?

 no.
 python is not C. python is interpreted, not compiled,

Please verify your assertions... FWIW, being compiled or interpreted
is not a feature of a language, but of an implementation of a language.
And FWIW also, CPython *is* compiled (to byte-code, like Java).



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] code is data

2006-06-20 Thread bruno at modulix
Diez B. Roggisch wrote:
 because lots of people know how to describe XML transformations, and
 there are plenty of tools that implement such transformations
 efficiently ?


 Efficiently enough for dynamic (runtime) use ?
 
 
 Using XML-transformation for AST manipulation isn't my first choice
 either - yet efficiency concerns aren't really the point here - after
 all we're talking about generating code,

I thought we were talking about *transforming* code - just like one uses
metaclasses to transform a class definition, or @decorators to transform
a function definition...

(snip)

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] code is data

2006-06-20 Thread bruno at modulix
Diez B. Roggisch wrote:
 bruno at modulix wrote:
 
 
Diez B. Roggisch wrote:

because lots of people know how to describe XML transformations, and
there are plenty of tools that implement such transformations
efficiently ?


Efficiently enough for dynamic (runtime) use ?


Using XML-transformation for AST manipulation isn't my first choice
either - yet efficiency concerns aren't really the point here - after
all we're talking about generating code,

I thought we were talking about *transforming* code - just like one uses
metaclasses to transform a class definition, or @decorators to transform
a function definition...
 
 
 Yes we were. So where does the runtime efficiency you mention come in to
 play?

class transformations via metaclasses and function wrapping does happen
at runtime - when the class or (decorated) def statements are eval'd.
This is not the same as having a distinct preprocessing phase that would
write a new .py file.

 While the _result_ of a transformation might be a less efficient piece of
 code (e.g. introducing a lock around each call to enable concurrent
 access), the transformation itself is very - if not totally - static - 

really ?

 and
 usually only run once. 

Nope, it's runned each time the module is loaded (with 'loaded' distinct
from 'imported') - which can make a real difference in some execution
models...

 So except from a start up latency, it has no impact. 

Having a high startup latency can be a problem in itself.

But the problem may not be restricted to startup latency. If for example
you use a metaclasse and a function that *dynamically* creates new
classes using this metaclass, then both the class statement and the
metaclass code transformation will be executed on each call to this
function.

The whole point of a code transformation mechanism like the one Anton is
talking about is to be dynamic. Else one just needs a preprocessor...

 So if for whatever
 reason XSLT is someones favorite method of AST-transformation because it
 fits her mindset - perfect. As I said: it wouldn't be mine either, but I
 can't see your concerns about efficiency. 

cf above.

 And XSLT certainly is suited for tree manipulation, so it might be that it
 would be good for e.g. recursivly stripping type annotations of some kind
 (think of e.g. type-verifying decorators that you want to get rid of for
 production.)
 
 Diez


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread bruno at modulix
Rony Steelandt wrote:
 Paolo Pantaleo wrote:

 I have a function

 def f(the_arg):
 ...

 and I want to state that the_arg must be only of a certain type
 (actually a list). Is there a way to do that?


 Yes and no. You can ensure that the passed object is a list, by
 calling e.g.

 def f(arg):
 if not isinstance(arg, list):
raise Not a list!


 Alternatively, you can just use it as an iterable - and the exception
 will
 come from arg not being iterable.

 But what you can't do is make python complain about this:

 def f(arg):
 for e in arg:
 print e


 f(100)

 before actually calling f. It will always fail at runtime.

 Diez
 
 
 What about
 def f(arg):
if type(arg)=='list':

FWIW, type(some_type) returns a type object, not a string. So your
test will always fail. A right way to write this is:
  if type(arg) is type([]):
 ...

#do something

Usually a very bad idea. It defeats the whole point of duck-typing. In
most cases, you don't care about the concrete class - all you want is an
object that implements an (implied) interface.

NB : I say 'usually' because there are a very few cases where testing
the concrete class can make sens - but there again, better to use
isinstance() than type().



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-20 Thread bruno at modulix
K.S.Sreeram wrote:
 bruno at modulix wrote:
 
  if type(arg) is type([]):
 
 
 Just a tiny nitpick
 You can just use 'list' instead of 'type([])'

I know. Note that I wrote *A* right way to write this, not *The*
right way...

And FWIW, you could also use arg.__class__ instead of type(arg).

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling every method of an object from __init__

2006-06-20 Thread bruno at modulix
Tim Chase wrote:
(snip)

 class Foo(object):
 ... def __init__(self):
 ... for method in dir(self):
 ... if method == method.strip(_):
  if not method.startswith('_'):

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-20 Thread bruno at modulix
Max M wrote:
 bruno at modulix wrote:
 
 Or did you just like what you saw and decided to learn it for fun?


 Well, I haven't be really impressed the first time - note that it was at
 the very end of the last century, with v1.5.2. 
 
 
 
 1.5.2 was an excellent version. Not really that different in use than
 current version.

Nope, not really that different - we were just missing list-comps,
generators, new-style classes, classmethods, staticmethods, usable
metaclasses, descriptors, @decorators sugar, extended slices, and a few
other goodies coming in 2.5 like coroutines and with: statement...


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-20 Thread bruno at modulix
Max M wrote:
 bruno at modulix wrote:
 
 Max M wrote:

 bruno at modulix wrote:

 Or did you just like what you saw and decided to learn it for fun?


 Well, I haven't be really impressed the first time - note that it
 was at
 the very end of the last century, with v1.5.2. 



 1.5.2 was an excellent version. Not really that different in use than
 current version.


 Nope, not really that different - we were just missing list-comps,
 generators, new-style classes, classmethods, staticmethods, usable
 metaclasses, descriptors, @decorators sugar, extended slices, and a few
 other goodies coming in 2.5 like coroutines and with: statement...
 
 I wrote different in use. 

Yes. It just happens that all this really changed a lot the way I use
Python (and the way I design and program in general).

 Which is not the same as saying it has not
 changed. The general feel of coding in Python is exactly the same to me.

AFAIC, the overall feeling that the language helps me instead of getting
in the way is still here, of course !-)

 I believe that most of those changes you mention are rarely used by most
 programmers.

Too bad for them then. Not that I use all of these nice features all the
time, but I have a use case for at least one of them almost everyday -
and I do miss them when using other languages.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any subway web dev experiences

2006-06-19 Thread bruno at modulix
a wrote:
 subway is pythons ruby on rails competitor

Nope - it's a Python MVC web framework. Like Django, Pylons and
Turborgears. And FWIW, there have been recently some discussions about
merging Subway and Turbogears.

 pls tell me if u hav any expereinces

Please take time to learn and write readable english sentences.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] code is data

2006-06-19 Thread bruno at modulix
Anton Vredegoor wrote:
 With the inclusion of ElementTree (an XML-parser) in Python25 and recent
 developments concerning JSON (a very Pythonesque but somewhat limited
 XML notation scheme, let's call it statically typed XML)

JSON stands for JavaScript Object Notation, and has *nothing* to do with
XML - except for the fact that it's more and more used instead of XML
for AJAX stuff.

 Python seems to
 have reached a stage where it now seems to be possible to completely
 swallow lesser languages code, modify it, and spit out new source code
 targeting the original language the code was written in, or even make a
 translation to other languages.

If you mean parsing source in a given format and outputting another -
modified or not - representation, in the same or another format, Python
as always been able to do so.

 The idea is that we now have a fast parser (ElementTree) with a
 reasonable 'API' and a data type (XML or JSON) that can be used as an
 intermediate form to store parsing trees. Especially statically typed
 little languages seem to be very swallow-able. Maybe I will be able to
 reimplement GFABasic (my first love computer language, although not my
 first relationship) someday, just for fun.
 
 Then there are things like cTypes (calling functions from native DLL's)
 and PyPy (implementing Python in Python).
 
 All this taken together, to me it starts looking like we're now entering
 a territory that traditionally was exclusively in the Lisp domain.

Sorry, but I just don't get the point. Parsing, working with trees and
calling native code are in no way exclusively in the Lisp domain.

 Yes, Python had eval and exec for a long time already, and metatypes and
 generators are having some strange unexplored possibilities too, but the
 day will come soon (and at last when PyPy is reaching execution speeds
 close to cPython) where Python will be able to swallow smaller
 languages, and finally it will be able to swallow its own tail, like
 Lisp but then more powerful

I'm afraid Python is still very far from Lisp - and will never get there
(FWIW, this seems not to be the goal anyway).

 (because of the widely used standard data
 types and the code exchange between languages that that makes possible).

I still don't get the point.

 Your thoughts please.
 
 Anton


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code is data

2006-06-19 Thread bruno at modulix
BJörn Lindqvist wrote:
 Personally, I would like to see macros in Python (actually Logix
 succeeding is good enough). But I am no language designer and the
 community has no interest in it. When I absolutely need macros, I will
 go elsewhere.
 
 
 One must wonder, when is that? When do you absolutely need macros?
 
One must wonder, when do you absolutely need HOFs, closures, OO,
functions, or even structured programming. All we 'absolutely' need is
tests and gotos... (and love, of course !-).

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code is data

2006-06-19 Thread bruno at modulix
Ravi Teja wrote:
 BJörn Lindqvist wrote:
 
Personally, I would like to see macros in Python (actually Logix
succeeding is good enough). But I am no language designer and the
community has no interest in it. When I absolutely need macros, I will
go elsewhere.

One must wonder, when is that? When do you absolutely need macros?
 
 
 Whenever there is significant boiler plate code that functions and
 classes cannot eliminate alone.
 Whenever there is a more elegant way to express your code.
 
 Python 2.5 introduced conditional expressions and with statement. With
 macros, one would not have to wait for the language team to implement
 them. More so for features which only a small part of the community has
 an interest in.
 
 I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would
 have done it myself for *my* code.

And that's the downside with macros - and with anything that's not
officially part of the language or it's standard lib : everybody
implements it it's own way, and you end up with dozens non-standard ways
of doing the same thing.

Not to say this is absolutely bad, but there's a balance to be found
here. One could do function decorators long before we had official
syntactic sugar for it, but it only started to be a common idiom with
the @decorator syntax. Python 2.5 introduces a 'partial' type, that is
quite easy to implement with 2.4 (and probably with older versions too),
but having it in the builtins or standard lib means it will become the
standard way to do it - no need to deal with half a dozen half-backed
implementations of it no more.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code is data

2006-06-19 Thread bruno at modulix
Ravi Teja wrote:

(snip)
 Annoted variables, symbols and code
 layout visually cue more efficiently to the object nature than do
 explicit text definitions. Of course, this is only sensible when there
 aren't too many of any of those. In that case, the cognitive cost of
 notation outweighs the representational cost of text.
 
 Representational minimalism is troublesome in general code (ala Perl),
 but not so in a DSL where the context is constrained.

This still impose the need to learn a new language.

 I would also like to symbolize field types since they occur so commonly
 in a definition file and only a few of them are commonly used. I admit
 though that I find the code below a bit visually jarring and I might
 use something else. But it serves to illustrate the point. I chose the
 respective symbols based on their colloquial use and association with
 the field types.
 
 @Poll:
 $question: length 200
 %pub_date('date published')
 
 @Choice:
 poll - Poll
 $choice: length 200
 #votes

IMHOYuck/IMHO.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check if a file is closed

2006-06-19 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
 How to check if a file is closed?

 f = open('trashme.txt', 'w')
 f
open file 'trashme.txt', mode 'w' at 0x2ab66e40
 dir(f)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__',
'__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding',
'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read',
'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell',
'truncate', 'write', 'writelines', 'xreadlines']
 f.closed
False
 f.close()
 f.closed
True


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just out of curiosity: Which languages are they using at Google and what for?

2006-06-19 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
 I know Google are using Python for testing purposes.

Not only:

Where is Python used?

* The Google build system is written in python.  All of Google's
corporate code is checked into a repository and the dependency and
building of this code is managed by python.  Greg mentioned that to
create code.google.com took about 100 lines of python code.  But since
it has so many dependencies, the build system generated a 3 megabyte
makefile for it!
* Packaging.  Google has an internal packaging format like RPM.
These packages are created using python.
* Binary Data Pusher.  This is the area where Alex Martelli is
working, on optimizing pushing bits between thousands of servers
* Production servers.  All monitoring, restarting and data
collection functionality is done with python
* Reporting.  Logs are analyzed and reports are generated using Python.
* A few services including code.google.com and google groups.  Most
other front ends are in C++ (google.com) and Java (gmail).  All web
services are built on top of a highly optimizing http server wrapped
with SWIG.


http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] code is data

2006-06-19 Thread bruno at modulix
Anton Vredegoor wrote:
 bruno at modulix wrote:
 
 I still don't get the point.
 
 
 Well, I've got to be careful here, lest I'd be associated with the
 terr.., eh, the childp..., eh the macro-enablers.
 
 The idea is to have a way to transform a Python (.py) module into XML
 and then do source code manipulations in XML-space using ElementTree.

My my my... I'm not against the idea of dynamic source code
transformation, but for heaven's sake, *why* would one put XML in the
mix ???


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formatted string to object

2006-06-19 Thread bruno at modulix
Tim Chase wrote:
 Can you use strings or %s strings like in the above or

 aaa = 'string'
 aaa.%s() % 'upper'

 Somehow?
 
 
 Looks like you want to play with the eval() function.
 
 aaa = 'hello'
 result = eval(aaa.%s() % 'upper')
 result
 'HELLO'

Using eval() or exec should be really avoided whenever possible IMHO.
This one is best done with getattr(obj, attribute_name [,default]), ie:

 aaa = string
 getattr(aaa, 'upper')()
'STRING'



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formatted string to object

2006-06-19 Thread bruno at modulix
janama wrote:
 Hi,
 
 can such a thing be done somehow?
 
 
 aaa = self.aaa
 bbb = %s.%s % ('parent', 'bbb')

Given the first line, I assume this is inside a method body, and parent
is a local var. Then the answer is:

bbb = getattr(locals()['parent'], 'bbb')

read the doc for these two functions to get more infos.

 Can you use strings or %s strings like in the above or
 
 aaa = 'string'
 aaa.%s() % 'upper'
 
 Somehow?

Not directly - but here again, getattr() is your friend.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] code is data

2006-06-19 Thread bruno at modulix
Fredrik Lundh wrote:
 Laurent Pointal wrote:

 Bruno Desthuilliers wrote:
 Anton Vredegoor wrote:

 The idea is to have a way to transform a Python (.py) module into XML
 and then do source code manipulations in XML-space using ElementTree.
 

 
 My my my... I'm not against the idea of dynamic source code
 transformation, but for heaven's sake, *why* would one put XML in the
 mix ???
 
 
 because lots of people know how to describe XML transformations, and
 there are plenty of tools that implement such transformations efficiently ?

Efficiently enough for dynamic (runtime) use ?

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any subway experiences

2006-06-17 Thread bruno at modulix
a wrote:
 thanks for reading
 
Too long experience with Paris (France) subway... Left Paris, feel
better now !-)

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Legitimate use of the is comparison operator?

2006-06-17 Thread bruno at modulix
Mike Duffy wrote:
 I just recently realized that the comparison operator is actually
 works for comparing numeric values.

It's only an implementation detail of CPython (and is only true for
small integers - you'll find the limit in the CPython source code), not
part of the language specifications.  You should *not* relie on this
behaviour.

 Now, I know that its intended use
 is for testing object identity, but I have used it for a few other
 things, such as type checking,

Don't use it for this neither unless you know exactly what you do. Use
isinstance(obj, klass) instead - and yet better, don't check type at all
if you can avoid it.

 and I was just wondering whether or not
 it is considered bad practice in the Python Community to use it for
 numerics as well.

It's even worse than a bad practice : it's an error.


 Example:
 
 a = range(5)
 b = range(5)
 
 if len(a) is len(b):
 print They're the same size!
 else:
 print They're not the same size!
 
 a = range(32000)
 b = range(32000)
 len(a) is len(b)
False


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-17 Thread bruno at modulix
John Salerno wrote:
(snip)

 So out of curiosity, I'm just wondering how everyone else came to learn
 it. If you feel like responding, I'll ask my questions for easy quoting:
 
 Did you have to learn it for a job?

It has never been an official requirement for any of the jobs I got
since I'm a programmer, if that's what you mean. I discovered it while
learning C++ / wxWidgets (someone talked me about Python as being pretty
good for rapid prototyping).

 Or did you just like what you saw and decided to learn it for fun?

Well, I haven't be really impressed the first time - note that it was at
the very end of the last century, with v1.5.2. But still I found the
language suprisingly simple to get up and running with - seemed like the
language was almost always reading my mind about how I would have named
a librairy, function or whatever !-) So I ended up using it more and
more when wanting to play with an idea or write a quick script... Until
I realised than it was not the toy language I first thought it was (my,
no access restrictors, not static typing, this just could not be a
serious language, could it ?-), but a fantastic application programming
language - far better than anything I had seen before (mostly 'modern'
basics, C, C++, Pascal and Java...).

 Also, how did you go about learning it? (i.e., like I described above, I
 started with the main stuff then moved on to the different available
 frameworks)

Just used it, played with it, and lurked here.

 Was there any necessity in the specifics you learned, or did you just
 dabble in something (e.g. wxPython) for fun?

I first used it for scripts, then turned to web programming (job
opportunity), so I never really went very far in GUI programming with
Python.

 Are there still some things you feel you need to learn or improve?

Yes - all and everything...


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a good programming text editor (not IDE)

2006-06-16 Thread bruno at modulix
John Salerno wrote:
(snip)
 Based on another thread, I tried out Scite, but no matter what I do it
 doesn't seem to remember the window size and position, or any options I
 choose (like showing line numbers). 

This is in the configuration files. Don't remember which and where, but
I clearly remember having done this.

 
 And naturally there are Emacs and Vim, but I just don't know if I need
 to invest *that* much time into learning one of them

If you have a lot of file editing to do in a lot of various formats,
then investing time on learning how to effectively use a powerful and
extensible test editor is the WiseThingTodo(tm).

 (probably Vim,
 since I hear it's lighter and faster).

It's a bit faster at startup, yes. Else, I'm not sure it makes a real
difference wrt/ performances and power. It's more a matter of personal
preference than anything else IMHO.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a good programming text editor (not IDE)

2006-06-16 Thread bruno at modulix
BartlebyScrivener wrote:
 I see Eclipse mentioned here a lot. 

If you go for a Mammoth-weight GUI-only Java IDE and have a really
powerful computer, why not ?

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a good programming text editor (not IDE)

2006-06-16 Thread bruno at modulix
John Salerno wrote:
 Ant wrote:
 
 jEdit is for me still the best text editor available. Very extensible
 with macros (which can be written in Jython with the appropriate plugin
 installed). 
 
 
 I like the idea of being extensible, but of course I can only write in
 Python.

Jython is Python on Java.

 Are there any editors that support that?

Emacs.

plug
Which BTW is just great for python programming  - not only do you have
an embedded interactive python shell - the default one or IPython -  but
much more, you can with a simple keystroke eval either the whole buffer
or a selected block in this embedded shell. Could'nt live without it no
more !-)

(and you have ecb if you want a file/class browser)
/plug

But learning other languages might be a good idea too (even if once
spoiled by Python, if can be quite frustrating).

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a good programming text editor (not IDE)

2006-06-16 Thread bruno at modulix
BartlebyScrivener wrote:
 Emacs must be dying if this thread could get all the way to 20 with
 nobody arguing with the vi folks. 

No need to argue. I started with vim, and finally switched to emacs less
than one year later.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a good programming text editor (not IDE)

2006-06-16 Thread bruno at modulix
BartlebyScrivener wrote:
Most IDEs are rather weak as text editors compared to emacsen.
 
 
 That's true, but even emacs and xemacs don't offer simple automatic
 word wrap (i.e. wrap a line without splitting words or putting an eol
 or hard carriage return at the end of every line). I don't know if vim
 allows this. 

line-wrapping in an IDE ???

 It's something writers just take for granted in non-Unix
 text editors. 

Ah, ok. It's about vim/emacs as a general text editor. Emacs provides
word-wrapping, but true, it split words. I maybe wrong, but I don't
think it would be that hard to make it more word-friendly.

Now I wonder: what the use for line-wrapping at first ? Both emacs and
vim are text *editors*, not text *formatters*. Might be a unix-vs-others
cultural difference, but the general use on unix is to use some markup
(tex/LaTex, html, ReST or any 'structured-text' variant etc) and the
appropriate formater/renderer for presentation stuff.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-16 Thread bruno at modulix
BartlebyScrivener wrote:
(snip)

 Also, it seems to be a minimalist
 language. 

*seems* minimalist, but is really not - have a look at the object model
(metaclasses, descriptors etc), at closures and HOFs and decorators, at
list-comp and generators and (coming in 2.5) coroutines... Definitively
not minimalist in fact !-)


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-16 Thread bruno at modulix
BartlebyScrivener wrote:
I'd like something a bit like a module,
but I'd like to make several of them,
and not have them interfere with each other.
 
 
 Thank you. I sense what you are saying, but at this point I'd be
 thinking, Why not just make several modules? :) 

Because you want an unknown number of the *same* module ?-)

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-16 Thread bruno at modulix
Scott David Daniels wrote:
 BartlebyScrivener wrote:
 
  I am not touching OO, classes, or GUIs until I understand
 EVERYTHING else. Could take a few years. ;)
 
 
 You know how modules separate globals, right?  That is, what you
 write in one module doesn't affect the names in another module.
 What classes (and hence OO) give you is a way of saying, I'd
 like something a bit like a module, but I'd like to make several
 of them, and not have them interfere with each other.  That is
 the big intuition about objects, the rest is just details.

Another way to put it:

You know what are dicts, right ? That is, containers with keyword-access
to values ? Then you probably have dicts with a known, defined
structure, and functions working on it. What classes (and hence 00)
gives you is a way to associate these functions with the dicts
themselves. That is the big intuition about objects, the rest is just
details.

!-)

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-16 Thread bruno at modulix
BartlebyScrivener wrote:
(snip)
 I am not touching OO, classes, 

You may not be aware of this, but as soon as you're programming in
Python, you *are* using OO. Strings are objects, dicts are objects,
tuples are objects, lists are objects, numbers are objects, and even
functions and modules are objects. Classes are just a way to create your
own object types.

 or GUIs until I understand EVERYTHING

The answer is 42. That's all you need to know.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __cmp__ method

2006-06-15 Thread bruno at modulix
JH wrote:
 Hi
 
 Can anyone explain to me why the following codes do not work? I want to
 try out using __cmp__ method to change the sorting order. I subclass
 the str and override the __cmp__ method so the strings can be sorted by
 the lengh. I expect the shortest string should be in the front. Thanks

AFAIK (please a Guru correct me if I'm wrong), __cmp__ is used as a
fallback when other comparison operators ( __lt__ etc) are not implemented :

 class MyStr(str):
... def __lt__(self, other):
... return len(self)  len(other)
... def __le__(self, other):
... return len(self) = len(other)
... def __gt__(self, other):
... return len(self)  len(other)
... def __ge__(self, other):
... return len(self) = len(other)
...
 items = [MyStr(lolo lala), MyStr(lolo), MyStr(alal), MyStr(a)]
 sorted(items)
['a', 'lolo', 'alal', 'lolo lala']


But anyway, all this is a WTF. Just using the correct params for sorted
is enough:
 items2 = ['lolo lala', 'lolo', 'alal', 'a']
 sorted(items2, key=len)
['a', 'lolo', 'alal', 'lolo lala']


 
class myStr(str):
 
 def __init__(self, s):
 str.__init__(self, s) # Ensure super class is initialized

This is useless. If you don't override it, parent's init will be called
anyway.

(snip)

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how you get Python files on websites?

2006-06-15 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
(snip)
 i have a few questions about Python
 
 1. Can Python work with databases like MySql,Oracle? (i think it sounds
 silly)

http://www.google.com/search?q=%2Bpython+%2Bdb

 2.the Python files have .py extension and i used Windows Command
 Prompt(DOS) to execute the file,how can i use the programs written in
 Python on the web? (for large-scale search engines)

http://www.google.com/search?q=%2Bpython+%2Bweb

In both cases, the second entry should be a good starting point and
answer most of these 2 questions.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Test functions and test discovery

2006-06-14 Thread bruno at modulix
Ben Finney wrote:
(snip)
 if __name__ == __main__:
 test_funcs = [x for name, x in globals()
 if name.startswith(test) and hasattr(x, __call__)
 ]

Any reason not to use callable(x) here ? (instead of hasattr(x, __call__))

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looping through a file a block of text at a time not by line

2006-06-14 Thread bruno at modulix
Rosario Morgan wrote:
 Hello
 
 Help is great appreciated in advance.
 
 I need to loop through a file 6000 bytes at a time.  I was going to 
 use the following but do not know how to advance through the file 6000 
 bytes at a time.
 
 file = open('hotels.xml')

while True:
  block = file.read(6000)
  if not block:
break
  do_something_with_block(block)

or:

block = file.read(6000)
while block:
  do_something_with_block(block)
  block = file.read(6000)


 newblock = re.sub(re.compile(r'Rate.*?/Rate'),'',block)

Either you compile the regexp once and use the compiled regexp object:

  exp = re.compile(r'Rate.*?/Rate')
  (...)
  newblock = exp.sub('', block)

or you use a non-compiled regexp:

  newblock = re.sub(r'Rate.*?/Rate','',block)

Here, the first solution may be better. Using a SAX parser may be an
option too... (maybe overkill, or maybe the RightThingToDo(tm),
depending on the context...)

 
 I cannot use readlines because the file is 138MB all on one line.

So much for the XML is human readable and editable


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tiddlywiki type project in Python?

2006-06-14 Thread bruno at modulix
jkn wrote:
 Hi all
 I'm trying out, and in general finding really useful, the various
 TiddlyWiki variants that I guess many people here know about, for
 organising my activities in a GTD way. One mild annoyance is in the
 speed of the Javascript applications. I fancy having a go at writing
 something like this for myself, where update speed would be a higher
 priority.
 
 I don't know Javascript (although it looks moderately simple from a
 brief peruse,

It's not as simple as it may seem at first look. There are some real
gotchas. But if you want a more pythonic javascript, you should have a
look at mochikit.

 and I know enough languages to know I'll be able to pick
 it up); however I do know and use Python, although not nuch in a
 web-oriented way. Since unlike JS, python is at least pre-compiled, I
 have hopes that this would make things quicker. I do appreciate that JS
 is built into the browser, which might make my Python approach slower.
 I'm not sure of the 'architectural' approach to this; any suggestions,
 and maybe pointers to previous work?

I don't really understand what you're after here, since TiddlyWikiLikes
can *not* work without javascript.

Anyway, there's at least a Zope-based TiddlyWikiLike, so you may want to
have a look here:
http://ziddlywiki.org/

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tiddlywiki type project in Python?

2006-06-14 Thread bruno at modulix
jkn wrote:
(snip)
 Does the idea of embedding python in a browser instead of Javascript
 make any sense at all?

From a purely theoretical POV, yes, this idea makes sens - Python could
be an interesting alternative to javascript for client-side scripting
(and I'd really prefer using Python for this - but I may be a bit biased
!-). But note that there may be some issues wrt/ significative
indentation and security.

Now the problem is that no browser actually supports Python for
client-side scripting. And I really doubt this will change in a near
future.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Quacker

2006-06-14 Thread bruno at modulix
Quacker wrote:
 Very interesting!
 
indeed.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parent in a class __init__ def?

2006-06-13 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
 bruno at modulix wrote:
 
[EMAIL PROTECTED] wrote:

 Intuitively, the name lookup on
self.parent.foo would be faster than if you passed in the object in
question


Each dot means doing a lookup in a namespace. The more dots, the more
lookups. And lookups do have a cost.
 
 hmm, intuition may not be right in this case.

 Lookups do have a cost - now Im almost tempted to write and run a test
 for this - but the cost of each lookup is also relative to the current
 scope. 

A common optimization trick is to 'localize' references before a heavy
loop, to avoid lookup cost, ie:

def method(self, *args):
  dothis = self.dothis
  dothat = somemodule.somefunc
  CONST = othermodule.CONST
  # heavy processing loop here


 I haven't looked over the implementation of the python
 interpreter - but I would hope the lookup on self would be optimized
 and trivial.

It's certainly not trivial. Must take into account instance attributes
(in __dict__ or __slots__), class attributes, inherited attributes,
overriding descriptors, non-overriding descriptors, __getattr__,  etc...
The incredible felxibility of Python's object model comes with a cost.

  The next relevant question would be is it cheaper to
 lookup self.parent or to look up a method variable, 

The second - cf above.

 which I supsect
 would depend on the number of names in self vs. number of names in the
 method.

Namespaces are mostly built upon hashtables, so the number of names
should be mostly irrelevant.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong in this HTML Source file of a Bank

2006-06-13 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
 Several times I logged-in successfully but after log-in I can't use
 features/services which were shown prior to my login. Can anyone exoert
 
 from this forum check , is it technical fault of Bank Web Site or this
 problem pertaining to the user(me).

bofh
It's definitively a problem with the user.
The problem is : user posts in the wrong newsgroup.
/bofh


(snip a whole page of crappy tag soup)


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong in this HTML Source file of a Bank

2006-06-13 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
 I have posted the same question in alt.html but no one yet replied.

You should ask your butcher. Now please stop posting off-topic.



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python or Ajax?

2006-06-12 Thread bruno at modulix
Redefined Horizons wrote:
 I've been hearing a ot about AJAX lately. I may have to build a web
 application in the near future, and I was curoius:
 
 How does a web application that uses Python compare with one that uses
 AJAX?

How does a car that has a diesel motor compare with one that is red ?

 I've done some basic web page design with HTML and CSS, but never any
 web applications.

Obviously !-)

So the first steps would be to learn what is AJAX (hint: it's not a
lnaguage), and what is the difference between client-side scripting and
server-side scripting.

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parent in a class __init__ def?

2006-06-12 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
(meta : please don't top-post)
  Intuitively, the name lookup on
 self.parent.foo would be faster than if you passed in the object in
 question


Each dot means doing a lookup in a namespace. The more dots, the more
lookups. And lookups do have a cost.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parent in a class __init__ def?

2006-06-12 Thread bruno at modulix
Ray Schumacher wrote:
 What is the feeling on using parent in a class definition

parent is just a name. What is the semantic for this name ? Parent
class (ie: superclass) ? Container ? Else ?

 that class
 methods 

Takes care, class method has a very defined meaning in Python - a
class method is a method that takes the class object - not the instance
- as first param.

 can refer to, vs. some other organization ?
 Should all relevant objects/vars just be passed into the method as needed?

There's no absolute rule about this - at most some guidelines :
- What constitutes the state of an object should be an attribute of the
object.
- What is not part of the state and is only used for a given operation
should be passed as param.

 It seems like including parent in the class def is just like a class
 variable,

Here again, class variable has a well defined meaning in Python: it's
an attribute of the class object itself, that is shared by all instances
of the class.

 which most do not recommend.
 
 An example:
 class LXSerial:

do yourself a favour : use new-style classes whenever possible.

 def __init__(self, parent, debug=False):
 ...
 def connect(self, port, baud=9600, ptimeout=10):
 if self.debug:
 self.connectedPort = StringIO.StringIO(':A#')
 else:
 if self.parent.model=='LX200GPS': ptimeout = 240
 ...

We still don't know what's the semantic for this 'parent'. But anyway,
having this test on self.parent.model smells of a design error. If the
timeout value depends on the 'parent' object, then it's clearly a
responsability of this parent object to know that value. Your code here
should read:

  def connect(self, )
# ...
ptimeout = self.parent.timeout
# ...

You may also want to have a look at the strategy pattern, to avoid
cluttering your code with if self.debug...

wrt/ your original question, I don't see how one could give a sound
answer without knowing more about this parent object and it's
relationship with the LXSerial class/instance of.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to remove elements from a list not working

2006-06-12 Thread bruno at modulix
Girish Sahani wrote:
 Hi,
  I am trying to convert a list of pairs (l4) to list l5 by removing those
 pairs from l4 which are not present in a third list called pairList.




  The following is a simplified part of the routine i have written. However
 it does not give the correct output. Please help!
  Its possible i have made a trivial mistke since i am a newbie.
 
 def getl5():
ot
Please avoid this kind of names : it's both meaningless (what the ... is
'l5', I wonder ???) and confusing (is it 'l5' or '15' ?)

FWIW, read this:
http://mindprod.com/jgloss/unmain.html
/ot
 l5 = []
 pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]

From a semantic POV, you should use tuples for pairs - not lists.

 l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
 for pair in l4:
 if pair not in pairList:
err... see below...
 element.remove(l4)
 l5.append(element)
This is outside the for loop, so this would be executed only once (if
the rest of the code was correct, of course...)

 print l5 is,l5
 

You did not test this code, did you ?

 getl5()
Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/tmp/python-961l_S.py, line 7, in getl5
NameError: global name 'element' is not defined


The SimpleStupid(tm) way to do this is far more simple - at least if I
understood your specifications:

pairList = [(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)]
l4 = [(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)]
l5 = [pair for pair in l4 if pair in pairList]
print l5 is : , l5

Now this is not necessarily the most efficient solution...

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to remove elements from a list working, but python hangs :((

2006-06-12 Thread bruno at modulix
Girish Sahani wrote:
(please don't top-post)
 Hey Bruno...you are seeing the wrong post :P...please ignore this and
 check out the one with (corrected) appended at the end...

ot
You should have posted the correction in the same thread.
/ot

 Also, i used the list comprehension thingy which u have given, but now the
 problem is python just hangs if my list l4 contains around 50
 pairs...considering its not that big a data, this shouldnt happen
 Should it??

It shouldn't.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Searching and manipulating lists of tuples

2006-06-12 Thread bruno at modulix
MTD wrote:
 Hello,
 
 I'm wondering if there's a quick way of resolving this problem.
 
 In a program, I have a list of tuples of form (str,int), where int is a
 count of how often str occurs
 
 e.g. L = [ (X,1),(Y,2)] would mean X occurs once and Y occurs
 twice
 
 If I am given a string, I want to search L to see if it occurs already.
 If it does, I find the corresponding tuple and increment the integer
 part. If not, I append the new element with int = 1.
 
 e.g.
 
 algorithm(L, X) would produce output L = [(X,2),(Y,2)]
 algorithm(L,Z) would produce L = [(X,1),(Y,2),(Z,1)]

if you don't mind about ordering:

def algorithm(items, target):
  d = dict(items)
  try:
d[target] += 1
  except KeyError:
d[target] = 1
  items[:] = d.items()

Now it would probably be better to directly use a dict instead of a list
of tuples if possible...

 I tried to create an algorithm of the following form:
 
def algorith(list,str):

Using 'list' and 'str' as identifiers will shadow the eponym builtin
types in this function. This may or may not be a problem here, but it's
usually better to avoid doing so.

 ...   flag = True
 ...   for l in list:
 ...   if l[0] == str:
 ...   l[1] += 1
tuples are immutable. Hence the exception.

 ...   flag = False
'break'ing here would avoid useless iterations. And also allow the use
of the 'else' clause of the for loop, si you don't need a flag.
 ...   if flag:
 ...   list.append((str,1))


 ...

While there are pretty good reasons to favor the dict-based solution
(unless you really insist on having sub-optimal code of course !-), the
following is a somewhat more pythonic rewrite of your original code:

def algogo(alist, astring):
  for i, (name, count) in enumerate(alist):
if name == astring:
  alist[i] = (name, count+1)
  break
  else:
alist.append( (astring, 1) )


(snip)
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic inheritance

2006-06-09 Thread bruno at modulix
alf wrote:
 is there any way to tell the class the base class during runtime?
 
Technically, yes - the solution depending on your definition of during
runtime

FWIW, the class statement is evaled at import/load time, which is
during runtime So if you want to use one or other (compatible)
classes depending on configuration or system or like, you can use a
conditionnal at the top level, *before* the class statement is eval'd. ie:

import os
if os.name == 'posix':
  import posixmodule as basemodule
elif os.name == 'nt':
  import ntmodule as basemodule
# etc...

class MyClass(basemodule.baseclass):
  # class def here


If you want to dynamically change the base class (or one of the base
classes) during execution (ie: after the class statement has been
eval'd), read Kay Schluehr's answer.

*But* you'd probably better tell us about the problem you're trying to
solve. Since in Python, inheritance is mostly about implementation (ie:
 not needed for subtyping), your problem would probably be best solved
with composition/delegation, for which Python offers a good support:

class MyClass(object):
   def __init__(self, delegate):
   self._delegate = delegate

  def __getattr__(self, name):
   return getattr(self._delegate, name)

or, if you don't want to explicitely pass the delegate at instanciation
time:

import os
if os.name == 'posix':
  import posixmodule as basemodule
elif os.name == 'nt':
  import ntmodule as basemodule
# etc...

class MyClass(object):
_delegate_class = basemodule.SomeClass

def __init__(self):
self._delegate = self._delegate_class()

# etc

there are of course some variants of the above solutions, but one can't
tell you which one to use without knowing more about your actual problem.

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error in Chain of Function calls

2006-06-09 Thread bruno at modulix
Girish Sahani wrote:
 Hi,
 
 There is a code in my main function which is something like:
 
 while prunedFinal != []:
 prunedNew = genColocations(prunedK) ***
 tableInstancesNew = genTableInstances(prunedNew,tableInstancesK)
 tiCountDict = tiCount(tableInstancesNew)
 tiDict = findPI(tableInstancesNew)
 prunedFinal = pruneTI(tiDict,pi)
 rulesDict = genRules(prunedFinal)
 cpDict = findCP(rulesDict)
 prunedRulesList = pruneCP(cpDict,cp)
 prunedK = prunedFinal
 tableInstancesK = tableInstancesNew
 else:
 return prunedRulesList
 
 prunedK and tableInstancesK are defined in the main function.

defined as what ? functions, strings, lists, classes, ... ?

 Before the
 main function, i have defined the other functions such as
 genColocations,genTableInstances,etc. Output of genColocations is to be
 given to the next function genTableInstances,output of this function to
 tiCount and findPI, and so on.
 However i am getting an error at the line marked with ***.

Which error ? How do you hope us to be of any help here if you don't *at
least* provide the full traceback ? FWIW, the canonical way to do things
is to:
- provide minimal *runnable* code exposing the problem
- explain what you hoped to get
- explain what you got instead (including full traceback)

As a matter of fact, it's often the case that one solves the problem
when working on the first point !-)

(snip)

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what are you using python language for?

2006-06-09 Thread bruno at modulix
baalbek wrote:
 To score with the chicks!
 
 A Python script roams the nightclubs for beautiful women, finds an
 appropriate woman based on my preferances, charms her with its sleek
 Pythonic manners, calls for a cab and brings the lady to my recidency.
 
 Works like a charm!

Is that OSS ?-)



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error in Chain of Function calls

2006-06-09 Thread bruno at modulix
Girish Sahani wrote:
Girish Sahani wrote:


However i am getting an error at the line marked with ***.

what error ?
 
 ...line 266, in colocationMiner

Great. We now know at which line of an unknown file an unknown error
happens. Will use my PythonPsychicPowers(tm) now to see waht's there...

 
Also,i am getting a ValueError in the code below:
(snip)
The error is:
prunedNew.remove(s)
ValueError: list.remove(x): x not in list

the ValueError means exactly what it says -- have you verified that the
value of s really is present in the list?  did you really mean to
remove s and not, say, string ?
 
 Yes. I want to remove s from the prunedNew list if that condition is not
 satisfied.

Anyway the error message is very clear : you're trying to remove a
non-existant item from a list. Don't try to remove non-existent items,
and you'll be fine.

Hint 1 : in-place modifying a list you're iterating upon is a sure way
to get into trouble
Hint 2 : once you removed an item from that list, you shouldn't have to
worry about deciding once again if you need to remove it...


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: removing dictionary key-pair

2006-06-09 Thread bruno at modulix
JD wrote:
 Hello,
 
 I try to remove a dictionary key-pair (remove an entry), 
 but I'm unsuccessful. Does anyone know how to achieve this?
 
 Thanks

mydict = {key : value}
del mydict(key)

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: removing dictionary key-pair

2006-06-09 Thread bruno at modulix
bruno at modulix wrote:
 JD wrote:
 
Hello,

I try to remove a dictionary key-pair (remove an entry), 
but I'm unsuccessful. Does anyone know how to achieve this?

Thanks
 
 
 mydict = {key : value}
 del mydict(key)

grmf... Typo. This is:

del mydict['key']

of course...
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [noob question] References and copying

2006-06-09 Thread bruno at modulix
zefciu wrote:
 Hello!
 
 Where can I find a good explanation when does an interpreter copy the
 value, and when does it create the reference.

Unless you explicitely ask for a copy (either using the copy module or a
specific function or method), you'll get a reference.

  I thought I understand
 it, but I have just typed in following commands:
 
 
a=[[1,2],[3,4]]

- creates a list object containing 2 list objects, the first one
containing 2 integer objects with respective values 1 and 2, the second
one containing 2 integer objects with respective values 3 and 4

- associates ('binds') the name 'a' with the list object. Now in the
current namespace, 'a' refers to this list.

b=a[1]

- binds the name 'b' with the second element of [the list bound to] 'a'

b=[5,6]

- *re*binds 'b' to a new list containing two integer objects with
respective values 5 and 6.

a
 
 [[1, 2], [3, 4]]
 
b
 
 [5, 6]


Which is exactly what you asked for (while not being what you thought
you asked for...).

 And I don't understand it.  I thought, that b will be a reference to a,

It was - before you rebind it to another object.

 so changing b should change a as well.

To be pedantic, you don't change 'b'. You can either modify the object
bound to 'b' (which you did not) or rebind 'b' to another object (which
you did).

  What do I do wrong.  

confusing rebinding a name and modifying an object.

Try this to better see what happens
NB :
 - id() returns the unique identifier of an object - actually, in
CPython, it's memory address,
- 'is' test for identity ( a is b = id(a) == id(b)

 a = [[1, 2], [3, 4]]
 id(a)
46912496884192
 id(a[1])
46912496914656
 b = a[1]
 id(b)
46912496914656
 b is a[1]
True
 b = [5, 6]
 id(b)
46912496915520
 b is a[1]
False


Now to modify a[1] thru b :
 b = a[1]
 id(b)
46912496914656
 b is a[1]
True
 # add an item
 b.append(5)
 b
[3, 4, 5]
 b is a[1]
True
 a[1]
[3, 4, 5]
 # remove the first item
 del b[0]
 a[1]
[4, 5]
 # replace actual content with something else
 b[:] = [5, 6]
 b
[5, 6]
 b is a[1]
True
 a
[[1, 2], [5, 6]]



 And a
 second question - can I create a reference to element of a list of
 floating points and use this reference to change that element?

Not directly - but this has nothing to do with a reference-or-value
problem. It's just that floats (like ints, strings and tuples) are
immutable. You'll need either to work with indices or to wrap your
floats in mutable objects. I'd recommand the first solution.

 Greets to all PyFans
 zefciu


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: References and copying

2006-06-09 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
Where can I find a good explanation when does an interpreter copy the
value, and when does it create the reference.
 
 Any good Python book. I have Learning Python and Programming Python 2nd
 edition and they are very good IMO.
 
 
I thought I understand
it, but I have just typed in following commands:


a=[[1,2],[3,4]]
b=a[1]
b=[5,6]
a

[[1, 2], [3, 4]]

b

[5, 6]

And I don't understand it.  I thought, that b will be a reference to a,
so changing b should change a as well.
 
 
 No, you've set the name b to reference a slice of a. Slicing a list
 always returns a new list.

Please verify before asserting:

 a = [[1, 2], [3, 4]]
 b = a[1]
 b is a[1]
True
 id(b)
46912496915448
 id(a[1])
46912496915448




-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regexp questoin

2006-06-09 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
 hi
 
 i created a script to ask user for an input that can be a pattern
 right now, i use re to compile that pattern
 pat = re.compile(r%s %(userinput) )  #userinput is passed from
 command line argument
 if the user key in a pattern , eg [-] ,  and my script will search some
 lines that contains [-]
 
 pat.findall(lines)
 
 but the script produce some error: sre_constants.error: unexpected end
 of regular expression

If you feed re.compile() something that is not a valid regexp, it will
choke.

 how can i successful catch  patterns such as [-] in my regexp
 compilation where input is unknown...?

If what you want is to validate that the input is a valid regexp, just
try to compile it. In your case (cli argument), there's not much you can
do if the arg is not a valid regexp, except printing a message to stderr
and sys.exit()ing with a non-zero value.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error in Chain of Function calls (Code Attached)

2006-06-09 Thread bruno at modulix
Girish Sahani wrote:
Girish Sahani wrote:

(snip)

Before the
main function, i have defined the other functions such as
genColocations,genTableInstances,etc. Output of genColocations is to be
given to the next function genTableInstances,output of this function to
tiCount and findPI, and so on.
However i am getting an error at the line marked with ***.

Which error ? How do you hope us to be of any help here if you don't *at
least* provide the full traceback ? FWIW, the canonical way to do things
is to:
- provide minimal *runnable* code exposing the problem
- explain what you hoped to get
- explain what you got instead (including full traceback)

As a matter of fact, it's often the case that one solves the problem
when working on the first point !-)

(snip)
 
 Ohh...I was thinking that posting the whole code would not be a good idea.

It's *not* a good idea - unless the code is *very* short and has no
dependencies on anything else than the stdlib. Please re-read
*carefully* the first point :

- provide minimal *runnable* code exposing the problem

and notice the use of the word minimal. I *never* suggested that you
post the *whole* code.

 The error i get above is:
 line 266, in colocationMiner
 prunedNew = genColocations(prunedK)

This is *not* the error. It's a line number (which is totally useless if
 you don't have the corresponding file). Please re-read what I wrote
about posting *the full traceback*. Tracebacks are not here to be
beautiful on your screen, there here to give you as much possible
informations about what went wrong.

  Anyways, i've attached the file colocations.py. 

Don't attach files. Reduce your code to the *minimal* *runnable* code
snippet reproducing the problem.

(snip a few hundred lines of code I won't certainly take time to read
unless I'm being paid for fixing 'em)


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: language-x-isms

2006-06-08 Thread bruno at modulix
Bryan wrote:
 does anyone know if there is a collection somewhere of common python
 mistakes or inefficiencies or unpythonic code that java developers make
 when first starting out writing python code? 

Try googling for python is not java !-)


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Instead of saving text files i need as html

2006-06-08 Thread bruno at modulix
Shani wrote:
 I have the following code which takes a list of urls
 http://google.com;, without the quotes ofcourse, and then saves there
 source code as a text file. I wan to alter the code so that for the
 list of URLs an html file is saved.

What you write in a text file is up to you  - and AFAICT, HTML is still
a text format.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: follow-up to FieldStorage

2006-06-08 Thread bruno at modulix
Tim Roberts wrote:
 John Salerno [EMAIL PROTECTED] wrote:
 
 
Bruno Desthuilliers wrote:

John Salerno a écrit :

If I want to get all the values that are entered into an HTML form and 
write them to a file, is there some way to handle them all at the same 
time, or must FieldStorage be indexed by each specific field name?

AFAIK, FieldStorage is a somewhat dict-like object, but I'm not sure it 
supports the whole dict interface. At least, it does support keys(), so 
you should get by with:

for k in fs.keys():
  print  myfile, k, :, fs[k]

But reading the doc may help...

Thanks. The cgi docs don't seem to get into too much detail, unless I 
wasn't thorough enough. But your method seems like it might work well if 
I can't find something after another read through.
 
 
 On the other hand, 45 seconds with the source code shows that class
 FieldStorage has member functions called keys() and has_key().
 
 Use the source, Luke.  To me, that's one of the big beauties of Python.

FWIW, reading the source is not even needed to know this:

Python 2.4.3 (#1, Jun  3 2006, 17:26:11)
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type help, copyright, credits or license for more information.
 import cgi
 dir(cgi.FieldStorage)
['FieldStorageClass', '_FieldStorage__write', '__contains__', '__doc__',
'__getattr__', '__getitem__', '__init__', '__iter__', '__len__',
'__module__', '__repr__', 'bufsize', 'getfirst', 'getlist', 'getvalue',
'has_key', 'keys', 'make_file', 'read_binary', 'read_lines',
'read_lines_to_eof', 'read_lines_to_outerboundary', 'read_multi',
'read_single', 'read_urlencoded', 'skip_lines']


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to a certain line?

2006-06-07 Thread bruno at modulix
Tommy B wrote:
 bruno at modulix wrote:

(snip)

import os
old = open(/path/to/file.txt, r)
new = open(/path/to/new.txt, w)
for line in old:
  if line.strip() == Bob 62
line = line.replace(62, 66)
  new.write(line)
old.close()
new.close()
os.rename(/path/to/new.txt, /path/to/file.txt)

(snip)
 
 Umm... I tried using this method and it froze. Infiinite loop, I'm
 guessing.

Wrong guess - unless, as Fredrik suggested, you have an infinite disk
with an infinite file on it. If so, please share with, we would be
*very* interested !-)

Seriously : a for loop can only become an infinite loop if the iterable
is infinite. AFAIK, file objects (created from regular files on a
standard filesystem) are definitively not infinite.

Problem is elsewhere. But since you prefered to guess - instead of
providing relevant informations - we just can't help.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to a certain line?

2006-06-07 Thread bruno at modulix
Christophe wrote:
 bruno at modulix a écrit :
(snip)
 Wrong guess - unless, as Fredrik suggested, you have an infinite disk
 with an infinite file on it. If so, please share with, we would be
 *very* interested !-)
 
 
 Use /dev/zero as source and /dev/null as destination :D

Lol !-)


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating and naming objects

2006-06-07 Thread bruno at modulix
Brian wrote:
 Thank you all for your response.  I think that I am getting it.  Based
 on those responses, would I be correct in thinking that this would be
 the way to initialize my Student object and return the values?
 
 class Student:

Do yourself a favour: use new-style classes

class Student(object):

 def __init__(self, name, id):
 self.name = name
 self.id = id

ok until here.

 def getName(self):
 return self.name
 
 def getId(self):
 return self.id

These to getters are totally useless in Python. Python doesn't have
access restrictors [1], so you can directly access the attributes.
Python also has support for computed attributes (looks like an ordinary
attribute but is accessed thru a getter/setter), so there's no problem
wrt/ encapsulation. Just get rid of these two methods and you'll be fine.

[1] it's on purpose - we prefer to use conventions like using
_names_starting_with_a_leading_underscore to denote implementation stuff
that should not be accessed by client code.

 Additionally, correct me if I am wrong but I can recycle:
 
 foo = Student()

This won't work - will raise a TypeError. You defined Student.__init__()
to take 2 mandatory parameters name and id,so you must pass them at call
time.

FWIW, you would have noticed this just by trying it into your Python
shell. The interactive Python shell is a very valuable tool. It makes
exploring APIs and testing ideas a breeze, with immediate feedback. It
is one of the things that makes Python so easy and usable (not that it's
a Python invention - but it's a GoodThing(tm) Python have it).

 And doing so will just create a new instance of Student (with whatever
 attributes it is given) and the original foo is gone?

Yes. Or more exactly, the identifier 'foo' will refer to the newly
created Student object, and if there are no other references to the
object previously pointed by 'foo', it will be disposed of...

 Thanks for your help and patience.  After reading my original post and
 then this one, I could see that it may look suspiciously like a home
 work assignment.  Trust me it's not.

It could have been homework, this is not a problem - as long as you
effectively tried to do your homework by yourself, and only ask for help
when stuck. FWIW, in this job, knowing when and how to ask for help is
as important as knowing how to first try to solve the problem oneself !-)

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [0T]Use of Python in .NET

2006-06-07 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
 Hi,
   I am developing a code which has MVC (Model - View - Controler)
 architecture.My view is in .NET. And my controller is in Python.So can
 i call Python script from .NET? 

ot
This is a question that I would have asked myself before actually trying
to do anything else...
/ot


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to a certain line?

2006-06-06 Thread bruno at modulix
Tommy B wrote:
 I was wondering if there was a way to take a txt file and, while
 keeping most of it, replace only one line.

meta
This is a FAQ (while I don't know if it's in the FAQ !-), and is in no
way a Python problem. FWIW, this is also CS101...
/meta

You can't do this in place with a text file (would be possible with a
fixed-length binary format).

The canonical way to do so - whatever the language, is to write the
modified version in a new file, then replace the old one.

import os
old = open(/path/to/file.txt, r)
new = open(/path/to/new.txt, w)
for line in old:
  if line.strip() == Bob 62
line = line.replace(62, 66)
  new.write(line)
old.close()
new.close()
os.rename(/path/to/new.txt, /path/to/file.txt)

If you have to do this kind of operation frequently and don't care about
files being human-readable, you may be better using some lightweight
database system (berkeley, sqlite,...) or any other existing lib that'll
take care of gory details.

Else - if you want/need to stick to human readable flat text files - at
least write a solid librairy handling this, so you can keep client code
free of technical cruft.

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the most efficient method of adding elements to the list

2006-06-06 Thread bruno at modulix
alf wrote:
 Hi,
 
 Would it be .append()? Does it reallocate te list with each apend?
 
 l=[]
 for i in xrange(n):
   l.append(i)
 

dumb
FWIW, you'd have the same result with:
l = range(n)
/dumb


More seriously (and in addition to other anwsers): you can also
construct a list in one path:

  l = [i for i in xrange(n)]

or if you want operations and conditionals :

  l = [trasform(i) for i in xrange(n) if match_some_cond(i)]



HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: check for dictionary keys

2006-06-06 Thread bruno at modulix
John Machin wrote:
 On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote:
 
 [EMAIL PROTECTED] a écrit :

 hi
 in my code, i use dict(a) to make to a into a dictionary , a comes
 from user input, so my program does not know in the first place. Then
 say , it becomes

 a = { '-A' : 'value1' , '-B' : value2 , -C : value3 , '-D' :
 'value4' }

 somewhere next in my code, i will check for these..:

 1)  -A and -B cannot exist together
 2) -A and -C cannot exist together
 3) -A and -B and -D cannot exist together
 4) and lots of other combinations to check for


 Looks like an option parser... If so, there's all you need in the
 standard lib (look for the optparse module).


 how can i efficiently check for the above? At first as i do simple
 checks , i use if and else.
 But as i began to check for more combinatoiuns, it gets messy


 First : use boolean logic (truth table, Kernaugh diagram, etc) to
 simplify things. As an example, rule #3 is useless - it's a subset of
 rule #1 (-A and -B and -D implies -A and -B). This should greatly
 reduce the number of needed tests.
 
 
 Good idea, but doesn't scale well.

Does it need to scale ? If there are lot of rules and frequently
changing, yes, automating the process will be a good idea - but if it's
about a program options, just using one's brain might be enough. At
least it forces one to think about what's going on...

 Simple code can weed out redundant
 rules,

Simple code can weed out redundant *simple* rules !-)

(snip)

 Then, write a simple rule system describing either valid inputs or
 invalid inputs (preferably the smallest set !-). FWIW, it can be as
 simple as a list of lambdas/error messages pairs, with lambdas being
 predicate taking dict keys as params:


 _RULES = [
   (lambda keys : '-A' in keys and '-B' in keys,
can't have both options -A and -B),
   (lambda keys : '-A' in keys and '-C' in keys,
can't have both options -A and -C),
   # etc...
 ]

 
 The evil HR director won't let the PHB pay me on a per LOC basis, so
 I've had to come up with a compact table-driven approach :-)

otI'm my own evil HR director and PHB  !-)/ot

Don't like table-driven programming, John ?

This solution takes very few lines, and while it's surely not a
full-blown rule engine, it's at least reasonably flexible.

(Not to say it's better than yours - it's of course a matter of
effective use case).

 def validate(options, rules):
   keys = options.keys()
   for predicate, message in rules:
 if not predicate(keys):
   raise ValueError(message)
 
 
 
 C:\junktype option_combos.py
 bad_combos = ['ABD', 'AC', 'AB', 'CA']
 
 def rule_compaction(bc_list, verbose=False):
 # The next few lines are admittedly oldfashioned :-)
 bc_sets = [set(x) for x in bc_list]
 deco = [(len(y), y) for y in bc_sets]
 deco.sort()
 bc_sets = [z[1] for z in deco]
 del deco
 if verbose:
 print bc_sets #1:, bc_sets
 for k in xrange(len(bc_sets)-1, 0, -1):
 candidate = bc_sets[k]
 for ko in bc_sets[:k]:
 if ko = candidate:
 if verbose:
 print candidate, knocked out by, ko
 del bc_sets[k]
 break
 if verbose:
 print bc_sets #2:, bc_sets
 return bc_sets
 

Nice code - but how does it handle more complex predicates ? Seems you
can only deal with 'and' rules here. nitpickDoesn't scale well, you
said ?-)/nitpick

(snip)
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to a certain line?

2006-06-06 Thread bruno at modulix
Rene Pijlman wrote:
 bruno at modulix:
 
You can't do this in place with a text file (would be possible with a
fixed-length binary format).
 
 
 More precise: it's possible with any fixed-length change, in both binary
 and text files, with both fixed and variable formats.
 
Granted. But this is somewhat limited in what you can do when working
with text files...

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditional Expressions in Python 2.4

2006-06-02 Thread bruno at modulix
A.M wrote:
 Hi,
 
 
 
 I am using Python 2.4. I read the PEP 308 at:
 
 http://www.python.org/dev/peps/pep-0308/
 
 I tried the statement:
 
 a= Yes if 1==1 else No
 
 but the interpreter doesn't accept it.
 
 Do we have the conditional expressions in Python 2.4?

No, AFAIK they'll be in for 2.5

In the meanwhile, there are (sometime trickyà ways to get the same result:

a = 1 == 1 and Yes or No
a = (No, Yes)[1 == 1]


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance structure less important in dynamic languages?

2006-06-02 Thread bruno at modulix
Marvin wrote:
 Hi,
 
 It's been claimed 

s/claimed/observed/

In Python and Ruby, class hierarchies tends to be *really* flat when
compared to Java or C++.

 that inheritance structures are less important in dynamic
 languages like Python. Why is that

Don't you guess ?-)

A very obvious point is that in a dynamically typed language,
inheritence is only about implementation - it's not used for class-based
polymorphism (subtyping).

Also, dynamic languages are usually very strong on introspection and
offer good support for automatic delegation (DoesNotUnderstand in
Smalltalk, __getattr__ in Python, etc), which tend to lower the use of
inheritence for private inheritence (ie: implementation reuse without
any subtyping semantic).

This leaves with only three real use-case for inheritence :
 * factoring common features of a set of related classes in an abstract
base class
 * specialisation of an existing class (proper subclassing),
 * mixins.

 and where can i read more about that?

duck typing, implied interface and composition/delegation could be
good starting points for a google search.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to define a static field of a given class

2006-06-02 Thread bruno at modulix
feel_energetic wrote:
 Hi,
 
 I already knew how to define a static method of a class( using
 staticmethod() ),

FWIW, it's probably one of the most useless construct in Python IMHO.
classmethod are really much more useful to me.

 but I find there isn't a built-in func to build a
 static field ( something like staticfield() )

Please define static field, I just don't understand what it could be.

Now if what you want is a class attribute (ie: an attribute that is
shared by all instances of a class), just declare it at the class level:

class MyClass(object):
  shared_attrib = 42

# can be accessed via the class
# or via an instance
MyClass.shared_attrib
m = MyClass()
m.shared_attrib

# but you don't want to rebind it via an instance
m.shared_attrib = 33
m.shared_attrib
MyClass.shared_attrib

# note that the problem is only with rebinding - mutating is ok
class MyOtherClass(object):
  shared_attrib = [42]
mo = MyOtherClass()
mo.shared_attrib

mo.shared_attrib.append(33)
mo.shared_attrib
MyOtherClass.shared_attrib

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Package

2006-06-02 Thread bruno at modulix
Matthieu Pichaud wrote:
 I have a problem organizing my programs in packages and subpackages.
 
 I use python.2.3.3
 I built a test structure to try to understand how it worked:
 
 /test
 /test/__init__.py(containing: __all__=['test1'])
 /test/test1/
 /test/test1/__init__.py(containing: __all__=['test2'])
 /test/test1/test2/
 /test/test1/test2/__init__.py(containing: __all__=['test3'])
 /test/test1/test2/test3.py(containing: print 'test3')
 
 Then I run:
 from test import *
 test1
 module 'test.test1' from 'test/test1/__init__.py'
 test2
 Traceback (most recent call last):
   File stdin, line 1, in ?
 NameError: name 'test2' is not defined


 So it seems that I am very limited in the number of subpackages I can
 create.

Not at all.

 Is it normal?

Yes : when you have nested namespaces, it won't magically become a flat
namespace. There's a mostly clear documention on this in the official
Python tutorial.

 Am I silly organizing my programs like that?

Dunno - it depends on the program. But still:
python -c import this | grep nested

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you practice Python?

2006-06-01 Thread bruno at modulix
Ray wrote:
 In our field, we don't always get to program in the language we'd like
 to program. So... how do you practice Python in this case? Say you're
 doing J2EE right now.

Hopefully not !

 How do you practice Python to keep your skills
 sharp?

How *would* I do ? Well, perhaps I'd use Jython ?


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you practice programming?

2006-06-01 Thread bruno at modulix
Ray wrote:
 OK, maybe I shoot a more general question to the group since there are
 so many great programmers here: how do you practice your craft?

I'm certainly not one of them, but...

(snip)
 How do you do your practice?
 

1/ programming
2/ programming
3/ lurking here, reading posts and sometimes trying to answer, reading
source code of the oss apps/frameworks I'm working with, searching
practical solutions in the cookbook etc
4/ programming

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to do data source abstraction

2006-06-01 Thread bruno at modulix
Arthur Pemberton wrote:
 What is the best way to do data source abtraction? For example have
 different classes with the same interface, but different
 implementations.
 
 I was thinking of almost having classA as my main class, and have
 classA dynamically absorb classFood into to based on the extension
 of the input file received by classA. But this doesn't seem possible.

Could you explain more accurately what you're trying to do ? FWIW, it
seems that a plain old factory function would do ?

class DatasourceAbstraction(object):
   base class, factoring common stuff 
  # implementation here

class JpegFile(DatasourceAbstraction):
  # 


class PdfFile(DatasourceAbstraction):
  # 

class TxtFile(DatasourceAbstraction):
  # 

# etc
_classes = {
  'jpg' : JpegFile,
  'txt' : TxtFile,
  'pdf' : PdfFile,
  # etc..
}

def Datasource(inputfile):
  ext = os.path.splitext(inputfile)
  return _classes.get(ext, SomeDefaultClassHere)(inputfile)

The fact that there's no 'new' keyword in Python, and that classes are
callable objects acting as factories means that it's a no-brainer to use
a plain function (eventually disguised as a Class - the client code just
doesn't care !-) as factory...

Now if I missed the point, please give more explanations...

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you practice Python?

2006-06-01 Thread bruno at modulix
Ray wrote:
 bruno at modulix wrote:
 
In our field, we don't always get to program in the language we'd like
to program. So... how do you practice Python in this case? Say you're
doing J2EE right now.

Hopefully not !
 
 
 I am :-(
 

Can we do something to help you out of this bad situation ?

(sorry...)

How do you practice Python to keep your skills
sharp?

How *would* I do ? Well, perhaps I'd use Jython ?
 
 
 Um, I mean, what if you have to use something other than
 Python/Jython/IronPython? :) 

Ruby or Smalltalk, then ? No ? J2EE ? Argh ! (me run away)

 How do you keep your Python skill sharp?

Just by thinking about how I would solve the problem at hand in Python -
and then cry :(

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you practice programming?

2006-06-01 Thread bruno at modulix
Ray wrote:
 bruno at modulix wrote:
 
1/ programming
2/ programming
3/ lurking here, reading posts and sometimes trying to answer, reading
source code of the oss apps/frameworks I'm working with, searching
practical solutions in the cookbook etc
4/ programming
 
 
 Yeah, but that's what most of us are doing too, we are programmers
 after all. But you know, it's like a boxer cannot get better just by
 going into a lot of fights, he needs good instruction from a good
 coach.

I learned the guitar mostly by watching other guitarists (good and bad
ones), trying to teach whoever asked me what I already knew, and
practicing many hours a day (until my fingers hurt too much in fact). In
programming, like in any other form of art - and like in spirituality
for that matters - *everyone* can be your master - sometimes without
even being aware of it - if you let him teach you.

 So what would you do? (I guess it's your number #3 above).

The #3 only would not be of any use without at least the #1, the #2 and
the #4. But I admit that #1, #2 and #4 would be equally useless without
the #3 !-)

How, and yes, also : using one's head - not only to wear a hat - may be
of some help too.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function mistaken for a method

2006-06-01 Thread bruno at modulix
Peter Otten wrote:
 Eric Brunel wrote:
 
 
My actual question is: why does it work in one case and not in the other?
As I see it, int is just a function with one parameter, and the lambda is
just another one. So why does the first work, and not the second? What
'black magic' takes place so that int is not mistaken for a method in the
first case?
 
  
 A python-coded function has a __get__ attribute, a C-function doesn't.
 Therefore C1.f performs just the normal attribute lookup while C2.f also
 triggers the f.__get__(C2(), C2) call via the descriptor protocol which
 happens to return a bound method.

FWIW:

class Obj(object):
  def __new__(cls, val, *args, **kw):
print in Obj.__new__
print - called with :
print   cls :, cls
print   val :, val
print   args:, str(args)
print   kw  :, kw
obj = object.__new__(cls, *args, **kw)
print got : %s - %s % (obj, dir(obj))
return obj

class CPlus(C):
  f = Obj


 Peter
 
 


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function mistaken for a method

2006-06-01 Thread bruno at modulix
Eric Brunel wrote:
 Hi all,
 
 I just stepped on a thing that I can't explain. Here is some code
 showing  the problem:
 
 -
 class C:

Do yourself a favour : use new-style classes.
class C(object)

   f = None
   def __init__(self):
 if self.f is not None:
   self.x = self.f(0)
 else:
   self.x = 0
 
 class C1(C):
   f = int
 
 class C2(C):
   f = lambda x: x != 0
 
 o1 = C1()
 print o1.x
 
 o2 = C2()
 print o2.x
 -
 
 Basically, I want an optional variant function across sub-classes of
 the  same class. 

 I did it like in C1 for a start, then I needed
 something like  C2. The result is... surprising:
 
 0
 Traceback (most recent call last):
   File func-vs-meth.py, line 18, in ?
 o2 = C2()
   File func-vs-meth.py, line 5, in __init__
 self.x = self.f(0)
 TypeError: lambda() takes exactly 1 argument (2 given)

Not surprising at all.

Functions implement the descriptor protocol[1]. When bound to a class
and looked up via an instance, it's the __get__ method of the function
object that get called - with the instance as param, as defined by the
descriptor protocol. This method then return the function wrapped - with
the instance - in an Method object - which itself, when called, returns
the result of calling the function *with the instance as first
parameter*. Which is how methods can work on the instance, and why one
has to explicitly declare the instance parameter in functions to be
used as methods, but not explicitly pass it at call time.

(please some guru correct me if I missed something here, but AFAIK it
must be a correct enough description of method invocation mechanism in
Python).

[1] about descriptors, see:
http://docs.python.org/ref/descriptors.html
http://www.geocities.com/foetsch/python/new_style_classes.htm#descriptors

 So the first works and o1.x is actually 0. 

int is not a function.
 type(int)
type 'type'

int is a type. A Python type is  a callable object, and act as a factory
for instances of it. If the type doesn't implement the descriptor
protocol, when bound to a class and looked up via an instance, normal
lookup rules apply. So the type object  is returned as is.


In your case, since int does'nt implement the descriptor protocol, once
looked up (and returned as is), it's called with a correct argument - so
everything runs fine.

Try this:

class Obj(object):
  def __new__(cls, val, *args, **kw):
print in Obj.__new__
print - called with :
print   cls :, cls
print   val :, val
print   args: %s % str(args)
print   kw  : %s % kw
obj = object.__new__(cls, *args, **kw)
print got : %s - %s % (obj, dir(obj))
return obj

  def __init__(self, *args, **kw):
print in Obj.__init__
print - called with :
print   args: %s % str(args)
print   kw  : %s % kw


class C4(C):
  f = Obj

 But the second fails because 
 self is also being passed as the first argument to the lambda. 

Of course. It's a function, and it's bound to a class, and looked up via
an instance of the class.

Try this:

def truc(*args, **kw):
  print in truc()__
  print - called with :
  print   args: %s % str(args)
  print   kw  : %s % kw
  if len(args)  1:
return args[1]

class C6(C):
  f = truc


 Defining
 a  real function doesn't help: the error is the same.

What' a real function ?-) lambdas *are* real functions.
 type(lambda x: x)
type 'function'


 My actual question is: why does it work in one case and not in the
 other? 

cf above.

 As I see it, int is just a function with one parameter,

Nope, it's a type. Functions are just one kind of callable. Types are
callables too, as are any object overloading the call operator - which
is '()' - by implementing the __call__(self, ...) method.

class NotAFunc(object):
   def __call__(self):
  print I'm not a function
  return 42

func = NotAFunc()
func()

 and the
 lambda is  just another one. 

True. And functions implement the descriptor protocol.

 So why does the first work, and not the
 second? What  'black magic' takes place so that int is not mistaken for
 a method in the  first case?

cf above.

If you understood all my explanations, you now know how to solve the
problem.

Else, here the solution:

class C3(C):
  f = lambda self, x: return x


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best Python Editor

2006-05-31 Thread bruno at modulix
Manoj Kumar P wrote:
 Hi,
 
 Can anyone tell me a good python editor/IDE?
 It would be great if you can provide the download link also.

I hate to be the one answering this, but this is *really* a FAQ - as you
would have known if you had google'd this group for this.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TIming

2006-05-30 Thread bruno at modulix
WIdgeteye wrote:
 HI,
 I am trying to write a little program that will run a program on
 scedule.

ot
There are usually existing programs to do so on most platforms (cron on
*n*x, the Windows scheduler, etc).
/ot

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Very good Python Book. Free download : Beginning Python: From Novice to Professional

2006-05-30 Thread bruno at modulix
Moneyhere wrote:
 Good :)
 Can someone  provide this ebook? web programming in python.
 I'm looking forwards it.
 
http://www.amazon.com/gp/product/0130410659/002-1715230-0496030?v=glancen=283155

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict literals vs dict(**kwds)

2006-05-24 Thread bruno at modulix
George Sakkis wrote:
 Bruno Desthuilliers wrote:
 
 
George Sakkis a écrit :

Although I consider dict(**kwds) as one of the few unfortunate design
choices in python since it prevents the future addition of useful
keyword arguments (e.g a default value or an orderby function), I've
been finding myself lately using it sometimes instead of dict literals,
for no particular reason. Is there any coding style consensus on when
should dict literals be preferred over dict(**kwds) and vice versa ?

using dict literals means that you'll always have a builtin dict - you
cannot dynamically select another dict-like class. OTHO, you can only
use valid python identifiers as keys with dict(**kw).
 
 
 This is all good but doesn't answer my original question: 

I thought it did - at least partly.

 under which
 circumstances (if any) would  {'name':'Mike, 'age':23} be preferred
 over dict(name='Mike', age=23) 

When you're sure you want a builtin dict (not any other dictlike) and/or
some keys are invalid Python identifiers.

 and vice versa, 

When all your keys are valid Python identifiers, and you may want to use
another dict-like instead of the builtin dict. It's easy to replace the
dict() factory in a function, class, or whole module :

class MyDict(...):
  # dict-like class

dict = MyDict

then all following calls to dict(**kw) in this namespace will use MyDict
instead of the builtin's one. Can't do that with dict litterals.

 or if it's just a matter
 of taste, 

Partly also, but...

 similar to using single vs double quote for string literals
 (when both are valid of course).

Nope, this is not so similar, cf above.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to handle exceptions with try/finally

2006-05-24 Thread bruno at modulix
Carl J. Van Arsdall wrote:
(snip)

Not an answer to your question, just a few comments on your code:

 class Shared:

class Shared(object):


def __init__(self):
self.__userData= {}
self.__mutex = threading.Lock() #lock object

Don't use __names unless you have a *really* strong reason to do so.
'protected' attributes are usually noted as _name.

def getVar(self, variableName):
temp = None
error = 0
self.__mutex.acquire() #accessing shared dictionary
try:
try:
temp = self.__userData[variableName]
except:

Don't use bare except clauses. Specify the exceptions you intend to
handle, let the other propagate.

I once spent many hours trying to debug a badly written module that has
such a catch-all clause with a misleading error message saying some file
could not be opened when the actual problem was with a wrong login/pass
for a connection.

print Variable doesn't exist in shared
 space

stdout is for normal program outputs. Error messages should go to stderr.

raise ValueError

Should be a LookupError subclass. And the message should go with the
exception:
  raise MyLookupErrorSubclass(Variable '%s' doesn't exist in shared
space % variableName)


finally:
self.__mutex.release()
return temp
 
def putVar(self, variableName, value):
self.__mutex.acquire() #accessing shared dictionary
try:
self.__userData[variableName] = value
finally:
self.__mutex.release()
return

The return statement is useless here.

My 2 cents.
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Programming Books?

2006-05-24 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
(snip)

 So now i'm hear to use all of your collective expertise for the ideal
 book for a beginning programming who want's to start with python.

'ideal' greatly depends on the reader !-)

But FWIW, this is a FAQ (well : 2):
http://www.python.org/doc/faq/general/#i-ve-never-programmed-before-is-there-a-python-tutorial
http://www.python.org/doc/faq/general/#are-there-any-books-on-python

And you may get good answers here:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

and by googling this ng (someone asked the same question yesterday...).

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python keywords vs. English grammar

2006-05-24 Thread bruno at modulix
defcon8 wrote:
 1. Does it matter?
 2. Is it affecting your productivity.
 3. Are you not trying to programme?
 4. It is open source, change it and stop whining.
 

What about trying emacs alt+x doctor return ?

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class probkem - getting msg that self not defined

2006-05-23 Thread bruno at modulix
Andrew Robert wrote:
 Hey Bruno,
 
 
 Although I have not tested it, this appears to be it exactly.
 
 
 Some confusion though.
 
 snip
 
 /snip
 
import struct

class TriggerMessage(object):
def __init__(self,data):

Unpacks the passed binary data based on the
MQTCM2 format dictated in
the MQ Application Programming Reference

 
 I am okay up to here :).
 
 After that, well..
 
 What does the _ before the variables mean?

It's a convention for implementation attributes (not part of the class
public interface).

 Why are you defining _format and _data here? 

Since the data object is passed at instanciation time (at least this was
the case in your code), this is the only place where I can bind it to an
instance attribute. As for the format string, it's really an attribute
of the class, and something that won't change, so better to have it in
the __init__ too. In fact, from what I saw of your code, it may as well
be a class attribute (ie : defined outside a method, and shared by all
instances), since the same format apply for all instances.

 I would have thought it
 belongs in the decode section.

It is used in the _decode method, but that does not mean it must be
defined in the _decode method.

 I think it is very slick but I would like to try and understand your
 approach.
 
 Also, why assert in calculating the struct size?

You don't *need* this calculation. struct.calcsize() is meant to let do
you check that the format string and the data string match (at least in
size). The assert here is mostly for developpement...


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: global name not defined

2006-05-23 Thread bruno at modulix
NetKev wrote:
(snip)
 def process_log(self, logfile, offset):
 if new_denied_hosts:
 info(new denied hosts: %s, str(new_denied_hosts))
 [warn_Admin(ip) for ip in new_denied_hosts]

This uselessly builds a list. List comprehension is meant to create
lists, not to replace for loops.

  for ip in new_denied_hosts:
  warn_admin(ip)


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to change sys.path?

2006-05-23 Thread bruno at modulix
Ju Hui wrote:
 is python search module by paths in sys.path?

sys.path is the list of path where the Python interpreter will search
modules, yes.

 how to change it manuallly?

manually ?-)

You mean dynamically, by code ? If yes, it's just a list. You can
modify it like you'd do for any other list.

Else, you may want to look at the PYTHON_PATH environnement variable.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Name conflict in class hierarchy

2006-05-23 Thread bruno at modulix
Scott David Daniels wrote:
 bruno at modulix wrote:
 
 Ralf Muschall wrote:

 Jeffrey Barish wrote:

 [overriding of base class member functions by subclass] 
 In Python, a function not intended to be overriden should be either
 have a name starting with an underscore


 actually with *two* underscores. The single-leading-underscore naming
 scheme is the convention for 'protected' (read: 'implementation, not
 API') attributes.
 
 
 The double-underscore is there to generate names that are unlikely to
 accidentally conflict. 

Yes, I do know this, and uses it when appropriate (that is : almost never)

I was just correcting Ralf's wrong statement about the single leading
underscore convention meant to denote functions not intended to be
overriden.



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python - Web Display Technology

2006-05-23 Thread bruno at modulix
Ben Finney wrote:
 SamFeltus [EMAIL PROTECTED] writes:
 
 
I keep trying to understand why people like HTML/JS, I don't think I
am gonna understand.
 
 
 It's fairly simple: HTML, CSS and JavaScript have all been
 standardised independent of any single corporation, and are freely
 implementable, resulting in competing free software
 implementations. We can choose or improve upon the implementation we
 like, or make our own, and share the result with others.

Also: HTML is an easy to parse text format. I can programatically grab
infos from HTML pages. Search engines can do it to.

 
I guess for better or worse, Flash is a very different mindset and
approach to the web. 
 
 One that shares none of the above qualities.
 
indeed.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: altering an object as you iterate over it?

2006-05-22 Thread bruno at modulix
Paul McGuire wrote:
 Bruno Desthuilliers [EMAIL PROTECTED] wrote in
 message news:[EMAIL PROTECTED]
 
bruno at modulix a écrit :
(snip)

(responding to myself)
(but under another identity - now that's a bit schizophrenic, isn't it ?-)

 
 
 Do you ever flame yourself?

class Myself(Developper, Schizophrenic):
  def _flame(self):
  implementation left as an exercice to the reader...
 Note that this is *not* part of the public API !-)
 
 pass


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Name conflict in class hierarchy

2006-05-22 Thread bruno at modulix
Ralf Muschall wrote:
 Jeffrey Barish wrote:
 
 [overriding of base class member functions by subclass]
 
(snip)
 
 In Python, a function not intended to be overriden should be either
 have a name starting with an underscore

actually with *two* underscores. The single-leading-underscore naming
scheme is the convention for 'protected' (read: 'implementation, not
API') attributes.

 or be documented.

s/or/and/


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP-xxx: Unification of for statement and list-comp syntax

2006-05-22 Thread bruno at modulix
Edward Elliott wrote:
 George Sakkis wrote:
 
 
Em Dom, 2006-05-21 às 17:11 +0200, Heiko Wundram escreveu:

for node in tree if node.haschildren():
do something with node

as syntactic sugar for:

for node in tree:
if not node.haschildren():
continue
do something with node
 
 [snip]
 
2) There should be one and preferably only one way to do it.
 
 
 You mean like this:
 
 s = foo + bar
 s = 'foo' + 'bar'
 s = 'foo' 'bar'
 s = '%s%s' % ('foo', 'bar')
 
 This one and only one way stuff is overrated.  I don't care how many ways
 there are as long as:
 1. at least one way is intuitive
 2. every way is easily comprehendible (readable, no side effects, etc)

The real mantra is actually :
There should be one-- and preferably only one --obvious way to do it

Please note the should, preferably, and obvious.

My 2 cents
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: string.count issue (i'm stupid?)

2006-05-22 Thread bruno at modulix
Matteo Rattotti wrote:
 Hi all,
 
 i've noticed a strange beaviour of string.count:
 
 in my mind this code must work in this way:
 
 str = a_a_a_a_

dont use 'str' as an identifier, it shadows the builtin str type.

 howmuch = str.count(_a_)
 print howmuch - 3
 
 but the count return only 2
 
 Ok this can be fine, but why? The doc string tell that count will
 return the number of substring in the master string, if we spoke about
 substring i count 3 substring...

depends on how you define number of substring, I mean, overlapping or
not. FWIW, I agree that this may be somewhat unintuitive, and would at
least require a little bit more precision in the docstring.

 Can someone explain me this? 

It seems obvious that str.count counts non-overlapping substrings.

 And in which way i can count all the
 occurrence of a substring in a master string? (yes all occurrence
 reusing already counter character if needed)

Look at the re module.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with writing a simple module

2006-05-22 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
 ello there. i am having a problem getting a module to work right.
 
 i wrote a class that is going to be used in a few different scripts in
 the same directory.
 
 it looks like this:
 
 #!/usr/bin/python

This is not needed for a module.

(snip code)
 the file is saved as DbConnector.py 

The most common convention is to name modules all_lower, and keep
CamelCaseNames for classes.

 and made executable.

This is not needed for a module.

You may want to make scripts (ie: modules that has to be runned as
main program executables and then add the shebang. Other modules (the
ones that are meant to be used via import) don't need this.

 then i get this in idle
 
 
import DbConnector
x = DbConnector()
 
 
 then it tells me that the module object is not callable.

cf Larry's answer. You may also want to browse the very recent (may 19)
thread named noob import question.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling python functions using variables

2006-05-19 Thread bruno at modulix
Ben Finney wrote:
 Peter Otten [EMAIL PROTECTED] writes:
(snip)

You want
getattr(commands, VARIABLE)()
 
 You'll also need to anticipate the situation where the value bound to
 VARIABLE is not the name of an attribute in 'commands'.
 
 Either deal with the resulting NameError exception (EAFP[0])

try:
  getattr(commands, VARIABLE)()
except NameError:
  print  sys.stderr, Unknown command, VARIABLE

 or test
 first whether the attribute exists (LBYL[1]).

command = getattr(commands, VARIABLE, None)
if command is None:
  print  sys.stderr, Unknown command, VARIABLE
else:
  command()

I'd go for the first solution.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: who can give me the detailed introduction of re modle?

2006-05-19 Thread bruno at modulix
softwindow wrote:
 the re module is too large and difficult to study

Too bad.

 i need a detaild introduction.

That's fine. Then write it. Or pay someone to do so.

Just for the record : that's the only answers you would have get on most
usenet groups. Hopefully, c.l.py is a very friendly and tolerant newsgroup.

Seriously, do yourself a favour, read this:
http://www.catb.org/~esr/faqs/smart-questions.html

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: memory error with zipfile module

2006-05-19 Thread bruno at modulix
Hari Sekhon wrote:
 I do
 
 import zipfile
 zip=zipfile.ZipFile('d:\somepath\cdimage.zip')
 zip.namelist()
 ['someimage.iso']
 
 then either of the two:
 
 A)   file('someimage.iso','w').write(zip.read('someimage.iso'))
 or
 B)   content=zip.read('someimage.iso')
 
 but both result in the same error:
 
 Traceback (most recent call last):
  File stdin, line 1, in ?
  File D:\u\Python24\lib\zipfile.py, line 357, in read
bytes = dc.decompress(bytes)
 MemoryError

otIs that the *full* traceback ?/ot

 I thought python was supposed to handle memory for you?

Err... This doesn't mean that it bypasses system's memory management.

http://pyref.infogami.com/MemoryError

http://mail.zope.org/pipermail/zope/2004-October/153882.html

MemoryError is raised by Python when an underlying (OS-level) allocation
fails.
(...)
Normally this would mean that you were out of even virtual memory
(swap), but it could also be a symptom of a libc bug, a bad RAM chip, etc.


What do you think will append if you try to allocate a huge block when
you've already eaten all available memory ? Do you really hope that
Python will give you extra ram for free ?-)

Please try this code:

import zipfile
zip=zipfile.ZipFile('d:\somepath\cdimage.zip')
info = zip.getinfo('someimage.iso')
csize = info.compress_size
fsize = info.file_size
print someimage compressed size is : %s % csize
print someimage real file  size is : %s % fsize
print 
So, knowing how zipfile.read() is actually implemented,
total needed ram is :  %s
 % (csize + fsize)

print Well... Do I have that much memory available ???


 The python zipfile module is obviously broken...

s/is obviously broken/could be improved to handle huge files/

Making such statements may not be the best way to make friends...

 Any advise?
Yes : Python is free software ('free' as in 'free speach' *and* as in
'free beer'), mostly written by benevolent contributors. So try and
improve the zipfile module by yourself, and submit your enhancements.
Then we all will be very grateful, and your name will be forever in the
Python Hall of Fame.

Or choose to behave as a whiny-whiny clueless luser making dumb
statements, and your name will be buried for a long long time in a lot
of killfiles.

It's up to you !-)

NB : If you go the first route, this may help:
http://www.python.org/doc/2.4.2/lib/module-zlib.html
with particular attention to the decompressobj.

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: noob import question

2006-05-19 Thread bruno at modulix
Brian Blazer wrote:
 OK, I have a very simple class here:
 
 class Student:

class Student(object):

 Defines the student class
 
 def __init__(self, lName, fName, mi):
 self.lName = lName
 self.fName = fName
 self.mi = mi

Do yourself a favour: use meaningful names.

 Then I have a small script that I am using as a test:
 
 from Student import *

So your module is named Student.py ? The common convention is to use
all_lower for modules, and CapNames for classes. BTW, unlike Java, the
common use is to group closely related classes and functions in a same
module.

 s1 = Student(Brian, Smith, N)
 
 print s1.lName
 
 This works as expected.  However, if I change the import statement to:
 import Student
 
 I get an error:
 TypeError: 'module' object is not callable

Of course. And that's one for the reason for naming modules all_lower
and classes CapNames.

With
 from Student import *

you import all the names (well... not all, read the doc about this)
defined in the module Student directly in the current namespace. So,
since the module Student contains the class Student, in this current
namespace, the name Student refers to the class Student.

With
  import Student

you import the module name Student in the current namespace. You can
then refer to names defined in module Student with the qualified name
module.name. So here, to refer to the class Student, you need to use the
qualified name Student.Student.

You wouldn't have such a confusion if your module was named students !-)


 I have tried to look up what is going on, but I have not found 
 anything.  

you could have done something like this:

import Student
print dir()
print dir(Student)
print type(Student)
del Student
from Student import *
print dir()
print dir(Student)
print type(Student)


Also, reading the doc migh help:
http://www.python.org/doc/2.4.2/tut/node8.html

HTH
-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   >