Pattern-match & Replace - help required

2012-12-19 Thread AT
Hi,

I am new to python and web2py framework. Need urgent help to match a pattern in 
an string and replace the matched text.

I've this string (basically an sql statement):
stmnt = 'SELECT  taxpayer.id, 
 taxpayer.enc_name, 
 taxpayer.age,
 taxpayer.occupation
 FROM taxpayer WHERE (taxpayer.id IS NOT NULL);'

The requirement is to replace it with this one:
r_stmnt = 'SELECT  taxpayer.id, 
   decrypt(taxpayer.enc_name), 
   taxpayer.age,
   taxpayer.occupation
   FROM taxpayer WHERE (taxpayer.id IS NOT NULL);'

Can somebody please help?

Thanks & Regards
 

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


Re: Pattern-match & Replace - help required

2012-12-19 Thread AT

On Wednesday, 19 December 2012 15:51:22 UTC+5, Steven D'Aprano  wrote:
> On Wed, 19 Dec 2012 02:42:26 -0800, AT wrote:
> 
> 
> 
> > Hi,
> 
> > 
> 
> > I am new to python and web2py framework. Need urgent help to match a
> 
> > pattern in an string and replace the matched text.
> 
> > 
> 
> > I've this string (basically an sql statement): 
> 
> >
> 
> > stmnt = 'SELECT taxpayer.id,
> 
> >  taxpayer.enc_name,
> 
> >  taxpayer.age,
> 
> >  taxpayer.occupation
> 
> >  FROM taxpayer WHERE (taxpayer.id IS NOT NULL);'
> 
> > 
> 
> > The requirement is to replace it with this one: 
> 
> > 
> 
> > r_stmnt = 'SELECT taxpayer.id,
> 
> >decrypt(taxpayer.enc_name),
> 
> >taxpayer.age,
> 
> >taxpayer.occupation
> 
> >FROM taxpayer WHERE (taxpayer.id IS NOT NULL);'
> 
> > 
> 
> > Can somebody please help?
> 
> 
> 
> Can you do this?
> 
> 
> 
> stmnt = r_stmnt
> 
> 
> 
> That should do what you are asking.
> 
> 
> 
> If that doesn't solve your problem, you will need to explain your problem 
> 
> in more detail.
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven


I just wanted to change taxpayer.enc_name in stmnt to decrypt(taxpayer.enc_name)

hope it clarifies?

thanks


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


Re: Pattern-match & Replace - help required

2012-12-19 Thread AT
On Wednesday, 19 December 2012 16:27:19 UTC+5, Thomas Bach  wrote:
> On Wed, Dec 19, 2012 at 02:42:26AM -0800, AT wrote:
> 
> > Hi,
> 
> > 
> 
> > I am new to python and web2py framework. Need urgent help to match a
> 
> > pattern in an string and replace the matched text.
> 
> > 
> 
> 
> 
> Well, what about str.replace then?
> 
> 
> 
> >>> 'egg, ham, tomato'.replace('ham', 'spam, ham, spam')
> 
> 'egg, spam, ham, spam, tomato'
> 
> 
> 
> 
> 
> If the pattern you want to match is more complicated, have a look at
> 
> the re module!
> 
> 
> 
> Regards,
> 
>   Thomas.


The pattern is '%s.enc_%s', and after matching this pattern want to change it 
to 'decrypt(%s.enc_%s)' 

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


Re: Pattern-match & Replace - help required

2012-12-19 Thread AT
On Wednesday, 19 December 2012 18:16:18 UTC+5, Peter Otten  wrote:
> AT wrote:
> 
> 
> 
> > I am new to python and web2py framework. Need urgent help to match a
> 
> > pattern in an string and replace the matched text.
> 
> > 
> 
> > I've this string (basically an sql statement):
> 
> > stmnt = 'SELECT  taxpayer.id,
> 
> >  taxpayer.enc_name,
> 
> >  taxpayer.age,
> 
> >  taxpayer.occupation
> 
> >  FROM taxpayer WHERE (taxpayer.id IS NOT NULL);'
> 
> > 
> 
> > The requirement is to replace it with this one:
> 
> > r_stmnt = 'SELECT  taxpayer.id,
> 
> >decrypt(taxpayer.enc_name),
> 
> >taxpayer.age,
> 
> >taxpayer.occupation
> 
> >FROM taxpayer WHERE (taxpayer.id IS NOT NULL);'
> 
> > 
> 
> > Can somebody please help?
> 
> 
> 
> > The pattern is '%s.enc_%s', and after matching this pattern want to change
> 
> > it to 'decrypt(%s.enc_%s)'
> 
> 
> 
> after = re.compile(r"(\w+[.]enc_\w+)").sub(r"decrypt(\1)", before)

Thanks a million
Can you recommend a good online book/tutorial on regular expr. in python?

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


Conditional iteration

2006-12-13 Thread at

I would like to spark the discussion about the following syntax problem I
encounter.

THE PROBLEM

I have a lot times the following code:

for x in [-2, -1, 0, 1, 2, 3, 4]:
if x > 0:
... more code...


It is not the addional line containing 'if x > 0:' that bothers me, but the
additional indentation.


THE SOLUTION

More pythonic in view would be:

for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0:
... more code ...


This blends basically 

[x for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0]

and

x = y if x > 0 else 10


EXTENDING

And maybe a few usefull variants, like:

for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0 else -x:
... more code ...

In this case x will be 2, 1, 0, 1, 2, 3, 4.




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


Re: Conditional iteration

2006-12-13 Thread at
You proposal, seems nice to me but it doesn't work with Python 2.4.3, should
it work with 2.5?

Again I am just wondering if the approach for 

[x for c x in some_list if some_condition]

and
x = a if b else c

could be generalized for normal straight forward iterations:

for x in some_list if some_condition:

--- etc...

I am not looking for a work around but more interest if other people might
judge this syntax would come in handy?

Interested in any feedback!

Kind regards,

@






Paul Rubin wrote:

> at <[EMAIL PROTECTED]> writes:
>> I have a lot times the following code:
>> 
>> for x in [-2, -1, 0, 1, 2, 3, 4]:
>> if x > 0:
>> ... more code...
> 
> Use:
> 
>  for x in (x in [-2, -1, 0, 1, 2, 3, 4] if x > 0):
>   ... more code ...

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


Re: Conditional iteration

2006-12-13 Thread at
Forget 'pythonic'.

I just need to get work done and I see this type of conditional iteration
showing up many times obscuring my code because of the additional
indentation.

In line with previous syntax improvements made in Python my proposal (or
obvious variants) seems a logical next step. Unless of course nobody
appreciates it. That's the discussion I'd like to have here in the forum.

All the best
@



Roberto Bonvallet wrote:

> at wrote:
>> More pythonic in view would be:
>> 
>> for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0:
>>... more code ...
> 
> Pythonic?  Do you realize that Python hasn't even adopted well-known
> statements like 'switch' and 'do while' because they would be redundant?
> 
> This could be more convenient to you, but certainly not pythonic.
> Cheers,

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


Re: Iterating over several lists at once

2006-12-13 Thread at
Sorry for breaking into this thread, but I agree completely that any
unnecessary indentations should be avoided. For the same reason I advocate
that the following syntax should work:

for x in some_list if some_condition:
... code ...

in stead of 

for x in some_list 
if some_condition:
... code ...

All the  best!

@

PS: maybe using 'sets' can help you out for a particular problem.


Gal Diskin wrote:

> Nothing seriously wrong, but it's not too elegent. Especially when the
> number of lists you want to iterate over gets bigger (especially
> because of the indentation in python). As you noticed (an phrased
> better than me), what I was wondering is if there is a way to iterate
> over the cartesian product, but without actually doing all n for loops
> but using a single "for" loop.
> 
> Thanks for replying me.
> 
> 
> On Dec 13, 3:58 pm, Roberto Bonvallet <[EMAIL PROTECTED]>
> wrote:
>> Gal Diskin wrote:
>> > Hi,
>> > I am writing a code that needs to iterate over 3 lists at the same
>> > time, i.e something like this:
>>
>> > for x1 in l1:
>> >for x2 in l2:
>> >for x3 in l3:
>> >print "do something with", x1, x2, x3What's wrong with this?
>>
>> [...]
>>
>> > I'd be very happy to receive ideas about how to do this in one loop and
>> > with minimal initialization (if at all required).def
>> > cartesian_product(l1, l2, l3):
>> for i in l1:
>> for j in l2:
>> for k in l3:
>> yield (i, j, k)
>>
>> for (i, j, k) in cartesian_product(l1, l2, l3):
>> print "do something with", i, j, k
>> 
>> --
>> Roberto Bonvallet

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


Re: Conditional iteration

2006-12-13 Thread at
No offense, but my conclusions from your mail is that readability is a
matter of taste. 

My brains need to process a whole lot more information with your solution
than in my proposal...

but I read somewhere else that GvR rejected the proposal :-(

Ciao,
@


[EMAIL PROTECTED] wrote:

> The proposed solution impairs readability because there's a "surprise"
> at the end.  List comprehensions already open the language up to
> readability abuse.  Lets not add more.
> 
> To avoid the unwanted indentation, I would go with the already
> suggested "if not x>0: continue" solution or else something like this:
> 
> positiveMembers = [x for x in [-2, -1, 0, 1, 2, 3, 4] if x>0]
> for x in positiveMembers:
> #do stuff
> 
> This has the advantage of being more self-documenting.
> 
> at wrote:
>> I would like to spark the discussion about the following syntax problem I
>> encounter.
>>
>> THE PROBLEM
>>
>> I have a lot times the following code:
>>
>> for x in [-2, -1, 0, 1, 2, 3, 4]:
>> if x > 0:
>> ... more code...
>>
>>
>> It is not the addional line containing 'if x > 0:' that bothers me, but
>> the additional indentation.
>>
>>
>> THE SOLUTION
>>
>> More pythonic in view would be:
>>
>> for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0:
>> ... more code ...
>>
>>
>> This blends basically
>>
>> [x for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0]
>>
>> and
>>
>> x = y if x > 0 else 10
>>
>>
>> EXTENDING
>>
>> And maybe a few usefull variants, like:
>>
>> for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0 else -x:
>> ... more code ...
>> 
>> In this case x will be 2, 1, 0, 1, 2, 3, 4.

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


Re: Conditional iteration

2006-12-13 Thread at
Dear Carl,

Well, all I can say that for me as a user it would make sense...

Curiosity: in what sense is it redundant?
All solution/workarounds I have seen so far involve creation of new lists
(subsets) adding to more processing/computation/memory usage. Redundant
suggests that you know alternatives that don't do that.

Does Guido ever change his mind?

Cheers,

@


Carl Banks wrote:

> at wrote:
>> I am not looking for a work around but more interest if other people
>> might judge this syntax would come in handy?
> 
> Of course people have expressed interest in this in the past, but it's
> not going to happen.  There's a way to nest for and if statements, and
> a different way to nest for and if clauses in listcomps, and the two
> methods are considered distinct.  Although Guido has said that saving
> indentation levels is important, he hasn't said  anything (that I'm
> aware of) that suggests it's important enough to add this complexity
> and redundancy to the language.  Sorry.
> 
> 
> Carl Banks

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


Re: Conditional iteration

2006-12-13 Thread at
My comments below.

Kind regards,
@


Carl Banks wrote:

> at wrote:
>> Well, all I can say that for me as a user it would make sense...
> 
> Which is, like, step one out of a hundred for getting a syntax change
> into the language.
> 
>> Curiosity: in what sense is it redundant?
> 
> It creates syntactical support for two different ways to do something.
> If your plan were adopted, then we'd have two different spellings for
> the same thing:
> 
> for i in a:
> if i != 0:
> use(i)
> 
> for i in a if i != 0:
> use(i)

With the current Python syntax, I can create for every two lines of code a
dozen alternative implementations:

# example 1
a = {}
a['b'] = 'c'

versus:
a = {'b': 'c'}


# example 2
l = []
for l in some_list:
if some_condition:
l.append(l)

versus:
l = []
for x in some_list:
if some_condition:
l = l + [x]

or:
l = [x for x in some_list if some_condition]

(the beautiful one)

So your argument doesn't mean much I would say! 

> 
> Now, redundant syntax isn't a deal breaker by itself.  You have to ask
> what is buys you.  In this case, all it does is save you a single level
> of indentation--that's it.  There's no performance benefit.  It doesn't
> simplify logic.  It doesn't make the code any more readable of clear.
> It's only a minor improvement in conciseness.  It hardly saves any
> typing (unless you indent by hand).  Even its one clear benefit, saving
> indentation, is something you can already get with "if not x:
> continue".


Well there is a clear performance benefit, or more precisely a productivity
benefit. And -please- do not underestimate this for a language like Python,
which has many supporters due to its perceived and high productivity and
challenged on this point by languages like Ruby.

'for x in some_list if some_condition:'

is psychological very strong, because the brain will most likely treat the
in the same way as :

for every apple in the fruitbasket take one if green


Basically upon reading this first line you know exactly to what list of
items your next section of code applies. 

But again everything is a matter of taste and I assume that's why the change
control body is put into the hand of one person.



> Considering how little this syntax change buys, it really doesn't make
> a lot of sense for a language that places high emphasis on avoiding
> redundancy.
> 
> 
>> All solution/workarounds I have seen so far involve creation of new lists
>> (subsets) adding to more processing/computation/memory usage. Redundant
>> suggests that you know alternatives that don't do that.
>>
>> Does Guido ever change his mind?
> 
> Yes, but I guarantee "it makes sense for me" isn't going to convince
> him.  By the way, I'd suggest when posting to comp.lang.python and/or
> python-list in the future, you put your replies beneath the quoted text
> for the benefit of any future readers (not to mention present readers).
>
I hope this this thread will support the "it makes sense for me" with
arguments. Again it is not my intention to fight windmills, but to see if
there are strong arguments against it on one hand and if there supporters
on the other hand.


> 
> Carl Banks

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


Re: Conditional iteration

2006-12-13 Thread at
Thanx Paul!

Do you know if this generates a new list internally (memory consumption?)

@


Paul Rubin wrote:

> at <[EMAIL PROTECTED]> writes:
>> You proposal, seems nice to me but it doesn't work with Python 2.4.3,
>> should it work with 2.5?
>> 
>> Again I am just wondering if the approach for
>> 
>> [x for c x in some_list if some_condition]
>> 
>> and
>> x = a if b else c
>> 
>> could be generalized for normal straight forward iterations:
>> 
>> for x in some_list if some_condition:
> 
> Sorry, I got it wrong.  Should have said:
> 
>for x in (x for x in some_list if some_condition):
>   ...
> 
> So your example would have been:
> 
>   for x in (x for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0):
>... more code ...
> 
> It should work in 2.4.

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


Re: Conditional iteration

2006-12-13 Thread at
Hi Greg,

Well point is that the condition is the only thing happening and does not
really apply to the indented code section, but basically to the list used
in the indented code section.

When I read this code back its like, 'oh we use this list' and by the if
some_condition the next thing I think is 'hm, not all of the list' and even
worse should I worry if more restrictions can be found when I read
further...

All the best,

@

greg wrote:

> at wrote:
> 
>> It is not the addional line containing 'if x > 0:' that bothers me, but
>> the additional indentation.
> 
> I don't find the additional indentation bothersome.
> In fact I think it's helpful, because it makes it
> obvious that there is something else going on besides
> just a loop.
> 
> --
> Greg

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


Re: Conditional iteration

2006-12-14 Thread at
By the way,

I think by approving

a = b if condition else c

used to avloind

if condition:
a = b
else:
a = c

which is dealing with same psychological problem, Guido also recognizes some
need...

Is it redundant according to your criteria, yes I would say:

a = {True: a, False: c}[condition]

or 

a = [c, a][condition]

would yield exactly the same even in one sentence

Cheers,

@


at wrote:

> My comments below.
> 
> Kind regards,
> @
> 
> 
> Carl Banks wrote:
> 
>> at wrote:
>>> Well, all I can say that for me as a user it would make sense...
>> 
>> Which is, like, step one out of a hundred for getting a syntax change
>> into the language.
>> 
>>> Curiosity: in what sense is it redundant?
>> 
>> It creates syntactical support for two different ways to do something.
>> If your plan were adopted, then we'd have two different spellings for
>> the same thing:
>> 
>> for i in a:
>> if i != 0:
>> use(i)
>> 
>> for i in a if i != 0:
>> use(i)
> 
> With the current Python syntax, I can create for every two lines of code a
> dozen alternative implementations:
> 
> # example 1
> a = {}
> a['b'] = 'c'
> 
> versus:
> a = {'b': 'c'}
> 
> 
> # example 2
> l = []
> for l in some_list:
> if some_condition:
> l.append(l)
> 
> versus:
> l = []
> for x in some_list:
> if some_condition:
> l = l + [x]
> 
> or:
> l = [x for x in some_list if some_condition]
> 
> (the beautiful one)
> 
> So your argument doesn't mean much I would say!
> 
>> 
>> Now, redundant syntax isn't a deal breaker by itself.  You have to ask
>> what is buys you.  In this case, all it does is save you a single level
>> of indentation--that's it.  There's no performance benefit.  It doesn't
>> simplify logic.  It doesn't make the code any more readable of clear.
>> It's only a minor improvement in conciseness.  It hardly saves any
>> typing (unless you indent by hand).  Even its one clear benefit, saving
>> indentation, is something you can already get with "if not x:
>> continue".
> 
> 
> Well there is a clear performance benefit, or more precisely a
> productivity benefit. And -please- do not underestimate this for a
> language like Python, which has many supporters due to its perceived and
> high productivity and challenged on this point by languages like Ruby.
> 
> 'for x in some_list if some_condition:'
> 
> is psychological very strong, because the brain will most likely treat the
> in the same way as :
> 
> for every apple in the fruitbasket take one if green
> 
> 
> Basically upon reading this first line you know exactly to what list of
> items your next section of code applies.
> 
> But again everything is a matter of taste and I assume that's why the
> change control body is put into the hand of one person.
> 
> 
> 
>> Considering how little this syntax change buys, it really doesn't make
>> a lot of sense for a language that places high emphasis on avoiding
>> redundancy.
>> 
>> 
>>> All solution/workarounds I have seen so far involve creation of new
>>> lists (subsets) adding to more processing/computation/memory usage.
>>> Redundant suggests that you know alternatives that don't do that.
>>>
>>> Does Guido ever change his mind?
>> 
>> Yes, but I guarantee "it makes sense for me" isn't going to convince
>> him.  By the way, I'd suggest when posting to comp.lang.python and/or
>> python-list in the future, you put your replies beneath the quoted text
>> for the benefit of any future readers (not to mention present readers).
>>
> I hope this this thread will support the "it makes sense for me" with
> arguments. Again it is not my intention to fight windmills, but to see if
> there are strong arguments against it on one hand and if there supporters
> on the other hand.
> 
> 
>> 
>> Carl Banks

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


Re: Conditional iteration

2006-12-14 Thread at

Hi Paul,

I appreciate your explanation!

Thanx

@

Paul Rubin wrote:

> at <[EMAIL PROTECTED]> writes:
>> >   for x in (x for x in [-2, -1, 0, 1, 2, 3, 4] if x > 0):
>> >... more code ...
> 
>> Do you know if this generates a new list internally (memory consumption?)
> 
> It does not.  That parenthesized expression is a called generator
> expression.  It compiles to a small subroutine, more or less, that
> gets invoked repeatedly as you iterate through it.
> 
> A similar expression with square brackets is called a list
> comprehension and does generate a new list.

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


Re: Conditional iteration

2006-12-14 Thread at
Dear Diez,

True, I was just mentioning a workaround for a typical case.

Kind regards,

Arjan

Diez B. Roggisch wrote:

>> Is it redundant according to your criteria, yes I would say:
>> 
>> a = {True: a, False: c}[condition]
>> 
>> or
>> 
>> a = [c, a][condition]
>> 
>> would yield exactly the same even in one sentence
> 
> Obviously it is _not_ the exact same.
> 
> 
> def fac(n):
>   return n * fac(n-1) if n else 1
> 
> 
> Try that with your recipes above.
> 
> Diez

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


Re: Conditional iteration

2006-12-14 Thread at
Dear Duncan,

Points taken. Its just a workaround for a specific case, I know. Maybe I
just love the elegance of

new_list = [x for x in some_list if some_cond]

and like to see it extended...

I got I nice tip on generators however which would allow me to something
similar without consuming too much additional resources.

Kind regards,

Arjan




Duncan Booth wrote:

> at <[EMAIL PROTECTED]> wrote:
> 
>> By the way,
>> 
>> I think by approving
>> 
>> a = b if condition else c
>> 
>> used to avloind
>> 
>> if condition:
>> a = b
>> else:
>> a = c
> 
> Neither of those is much of an improvement over the other, and in fact if
> b or c are complex expressions I would definitely favour the longhand
> form. The benefit of having a conditional expression though is that in
> some situations it can make the code clearer by allowing you to avoid
> creating a name at all. e.g. if 'a' was then used as a parameter in a
> function call:
> 
> d = fn(b if condition else c)
> 
> and a has disappeared entirely.
> 
>> 
>> which is dealing with same psychological problem, Guido also
>> recognizes some need...
>> 
>> Is it redundant according to your criteria, yes I would say:
>> 
>> a = {True: a, False: c}[condition]
>> 
>> or
>> 
>> a = [c, a][condition]
>> 
>> would yield exactly the same even in one sentence
> 
> You do realise, I hope, that neither of these last two gives the same
> results as the inline 'if'?
> 
>>>> x = 0
>>>> print 3/x if x != 0 else -1
> -1
>>>> print {True: 3/x, False: -1}[x != 0]
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> print {True: 3/x, False: -1}[x != 0]
> ZeroDivisionError: integer division or modulo by zero
>>>> print [-1, 3/x][x != 0]
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> print [-1, 3/x][x != 0]
> ZeroDivisionError: integer division or modulo by zero
>>>> 
> 
> and before you suggest the good old standby and/or technique, that fails
> for other values:
> 
>>>> print x != 0 and 3/x or -1
> -1
>>>> x=5
>>>> print x != 0 and 3/x or -1
> -1
>>>> 
> 
> You need to use the messy:
> 
>>>> print (x != 0 and (3/x,) or (-1,))[0]
> 0
> 
> to get exactly the same effect as the inline if with loss of both
> readability and performance.

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


Re: Conditional iteration

2006-12-14 Thread at
I am not claiming that it was THE motivation, but it solves my problem...

Carl Banks wrote:

> 
> at wrote:
>> By the way,
>>
>> I think by approving
>>
>> a = b if condition else c
>>
>> used to avloind
>>
>> if condition:
>> a = b
>> else:
>> a = c
>>
>> which is dealing with same psychological problem, Guido also recognizes
>> some need...
> 
> If you think that this change was made for "psychological" reasons, you
> are terribly deluded.
> 
> 
> Carl Banks

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


Re: 10 sec poll - please reply!

2012-11-20 Thread mherrmann . at
That's a very good suggestion Emile!! So I might eventually need both 'press' 
and 'release' (or press_key/release_key). Thanks for this!

To everyone else who has been so kind to reply thus far: What do you think of 
generate_keystrokes? It's a bit long but describes exactly what the function 
would be doing. 

All of you are a great help and I really appreciate it. Thank you!

Michael

On Tuesday, 20 November 2012 17:21:38 UTC+1, emile  wrote:
> On 11/20/2012 04:18 AM, Michael Herrmann wrote:
> 
> > Hi,
> 
> >
> 
> > I'm developing a GUI Automation library (http://www.getautoma.com) and am 
> > having difficulty picking a name for the function that simulates key 
> > strokes. I currently have it as 'type' but that clashes with the built-in 
> > function. Example uses of 'type':
> 
> >
> 
> > type(ENTER)
> 
> >
> 
> > type("Hello World!")
> 
> >
> 
> > type(CTRL + 'a')
> 
> >
> 
> > What, in your view, would be the most intuitive alternative name?
> 
> >
> 
> > Here are my thoughts so far: I could call it 'press'
> 
> 
> 
> I have several tools that distinguish between press and release for 
> 
> this.  You may want to consider having both.
> 
> 
> 
> Emile

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


Jython but portable?

2020-07-19 Thread vjp2 . at
How do you use Jython Standalone Jar?

Do you have to "Intall"?

I usually use most standalone jars directly without intalling.  And I want to
use this thing in Portable Apps, so I din't want to install anything.
Because it might end up in my Windows system and I won't know until I try it
at another computer (whish is hard during apandemic).  I've got a lot of java
jars in protable apps that work fine.

i'm trying to use RDKit thru a call like
Java RDKIT.jar;jython.jar -Djava.library.path=/lib/

I probably should post this here, but I've outstayed my welcome on the java ng
asking very stupid questions


- = -
 Vasos Panagiotopoulos, Columbia'81+, Reagan, Mozart, Pindus
  blog: panix.com/~vjp2/ruminatn.htm - = - web:  panix.com/~vjp2/vasos.htm
   facebook.com/vasjpan2 - linkedin.com/in/vasjpan02 -  biostrategist.com
  ---{Nothing herein constitutes advice.  Everything fully disclaimed.}---




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


Re: Packaging a proprietary Python library for multiple OSs

2013-12-05 Thread mherrmann . at
On Thursday, 5 December 2013 16:52:45 UTC+1, [email protected] wrote:
> Or you could just sue anyone who steals your code.

I see your point but I don't think it's very practical. If the person who stole 
the code sits in some remote country with a completely different legal system, 
I think I'll have a hard time getting at this person. If I even manage to find 
out where the person is at all.
-- 
https://mail.python.org/mailman/listinfo/python-list


Jython from bathc file?

2015-05-08 Thread vjp2 . at
How do I do this in a .bat file?
Do I include the Jython or pipe it?

% CLASSPATH=$CLASSPATH:$RDBASE/Code/JavaWrappers/gmwrapper/org.RDKit.jar; jython
 -Djava.library.path=$RDBASE/Code/JavaWrappers/gmwrapper
Jython 2.2.1 on java1.6.0_20
Type "copyright", "credits" or "license" for more information.
>>> from org.RDKit import *
>>> from java import lang
>>> lang.System.loadLibrary('GraphMolWrap')
>>> m = RWMol.MolFromSmiles('c1c1')
>>> m.getNumAtoms()


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


Re: Jython from bathc file?

2015-05-09 Thread vjp2 . at
Thanks.. I suspected it wasn't meant to be taken as in the file

THe one thing I'm not sure if Jython is suppsosedto keep running
after the initisl stuff is loaded in..


To put the question in purely DOS terms if you run a program can you pipe it
some commands and then keep it running to take the remaining commands from
the console?

- = -
 Vasos Panagiotopoulos, Columbia'81+, Reagan, Mozart, Pindus, BioStrategist
http://www.panix.com/~vjp2/vasos.htm
  ---{Nothing herein constitutes advice.  Everything fully disclaimed.}---
   [Homeland Security means private firearms not lazy obstructive guards]
 [Urb sprawl confounds terror] [Phooey on GUI: Windows for subprime Bimbos]




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


Re: Jython from bathc file?

2015-05-09 Thread vjp2 . at
Tee from gnuutils??



- = -
 Vasos Panagiotopoulos, Columbia'81+, Reagan, Mozart, Pindus, BioStrategist
http://www.panix.com/~vjp2/vasos.htm
  ---{Nothing herein constitutes advice.  Everything fully disclaimed.}---
   [Homeland Security means private firearms not lazy obstructive guards]
 [Urb sprawl confounds terror] [Phooey on GUI: Windows for subprime Bimbos]




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


Re: Jython from bathc file?

2015-05-09 Thread vjp2 . at
I have to try this and see if there is ome kind of init file in jython/python
sorta like autoexec.bat. Ialso have no idea if the commands they provide are
all it takes to run the app or I have to stay in jython.. sorry, I'm thinking
at loud.. ok, thanks to all..



- = -
 Vasos Panagiotopoulos, Columbia'81+, Reagan, Mozart, Pindus, BioStrategist
http://www.panix.com/~vjp2/vasos.htm
  ---{Nothing herein constitutes advice.  Everything fully disclaimed.}---
   [Homeland Security means private firearms not lazy obstructive guards]
 [Urb sprawl confounds terror] [Phooey on GUI: Windows for subprime Bimbos]




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


Jython standalone

2015-11-13 Thread vjp2 . at
I click jython.org standalone jar and it just does a wait cycle.

What does it need to give me a prompt?


- = -
 Vasos Panagiotopoulos, Columbia'81+, Reagan, Mozart, Pindus, BioStrategist
http://www.panix.com/~vjp2/vasos.htm
  ---{Nothing herein constitutes advice.  Everything fully disclaimed.}---
   [Homeland Security means private firearms not lazy obstructive guards]
 [Urb sprawl confounds terror] [Phooey on GUI: Windows for subprime Bimbos]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Jython standalone

2015-11-14 Thread vjp2 . at

Jython is python in java at jython.org. 

I tried clicking and double clicking.

I does a wait cycle (rotating arrow) 
then returns to attention.

I'm trying to run RDKIT, an app written for jython.
THen I realised jython wasn't working at all.

I've had same problem with some java jars. 
I only keep java jars that respond.
If they don't respond, I assume they don't work.
But now I'm wondering.

- = -
 Vasos Panagiotopoulos, Columbia'81+, Reagan, Mozart, Pindus, BioStrategist
http://www.panix.com/~vjp2/vasos.htm
  ---{Nothing herein constitutes advice.  Everything fully disclaimed.}---
   [Homeland Security means private firearms not lazy obstructive guards]
 [Urb sprawl confounds terror] [Phooey on GUI: Windows for subprime Bimbos]




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


Problem using cx_Freeze

2022-08-15 Thread David at Booomer
I’m trying to use cx_Freeze (https://pypi.org/project/cx-Freeze/) in a python 
app but running into an error message:

AttributeError: module 'cx_Freeze' has no attribute ‘BdistDMG’

I’m using Anaconda and error appears with the import command: from cx_Freeze 
import *

 From the terminal the command: python setup.py build gives much the same error.

I believe there is an issue specifying the output file name but don’t know how 
to resolve it.

Any suggestions, thanks. David


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


Re: Problem using cx_Freeze

2022-08-15 Thread David at Booomer
Hi Jim

Thanks for your suggestions.

I changed

from cx_Freeze import *

to

from cx_Freeze import setup, Executable

And no longer get the BdistDMG error

—
I had found the page
https://cx-freeze.readthedocs.io/en/latest/setup_script.html
But hadn’t tried the setup, Executable option in the from statement
—

However I now get an error

init() takes from 2 to 12 positional arguments but 14 were given

I found a couple instances of init in two .py files that were part of the whole.

One .py file
def __init__(self):

Another .py file
class Aboutwindow(QtGui.QMainWindow, Ui_Aboutwindow):
def __init__(self,parent=None):
QtGui.QMainWindow.__init__(self,parent)
—
class Main(QtGui.QMainWindow):

def __init__(self):
QtGui.QMainWindow.__init__(self)

When searching for this error the answers found suggested including self in the 
init parameter list but the code already has self.

Thanks, David

> On Aug 15, 2022, at 5:51 PM, Jim Schwartz  wrote:
> 
> This link covers how to use BDist_dmg. 
> 
> https://cx-freeze.readthedocs.io/en/latest/setup_script.html
> 
> Sent from my iPhone
> 
>> On Aug 15, 2022, at 12:11 PM, David at Booomer  wrote:
>> 
>> I’m trying to use cx_Freeze (https://pypi.org/project/cx-Freeze/) in a 
>> python app but running into an error message:
>> 
>> AttributeError: module 'cx_Freeze' has no attribute ‘BdistDMG’
>> 
>> I’m using Anaconda and error appears with the import command: from cx_Freeze 
>> import *
>> 
>> From the terminal the command: python setup.py build gives much the same 
>> error.
>> 
>> I believe there is an issue specifying the output file name but don’t know 
>> how to resolve it.
>> 
>> Any suggestions, thanks. David
>> 
>> 
>> -- 
>> https://mail.python.org/mailman/listinfo/python-list

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


Re: Problem using cx_Freeze

2022-08-17 Thread David at Booomer
Hi Dennis

Thank you for your reply. I’m am trying to get LaTex-to-Speech 
(https://github.com/SGanesh19/LaTeX-to-Speech) to run as an accessibility aid, 
converting equations into speech. I haven’t used cx_Freeze before so stumbling 
somewhat.

The error returned is

  File 
"/Users/duser/Documents/Win_ShareFolder/LaTeX-to-Speech-master/setup.py", line 
9, in 
Executable(
TypeError: __init__() takes from 2 to 12 positional arguments but 14 were given

The setup.py file is currently

import cx_Freeze
# from cx_Freeze import *
from cx_Freeze import setup, Executable

setup(
name="Latex2Speech",
options = {'build_exe':{'packages':['gtts','pyglet','PyQt4']}},
executables=[
Executable(

"prjui.py","Maiui.py","about.py","dict.py","geometry.py","getEquation.py",

"gtrail.py","main.py","matchingstring.py","producelatex.py","readfile.py",
"separete.py","speak.py",
)
]
)

I am/was worried about the trailing ‘,' after ',"speak.py”,’ <- but deleting it 
or moving it after the ] didn’t help. Adding base = None also didn’t help.

Searching for ‘__init__(' in the 13 *.py files returned five lines in two files 
(algorithm.py and prjui.py). As mentioned searching for this error only 
produced mention of adding self which is in these lines already. Previously I 
had search for __init__() which returned no lines due to the closing ).

I had visited the page you provided 
(https://cx-freeze.readthedocs.io/en/latest/setup_script.html#cx-freeze-executable)
 but didn’t noticed the 11 plus self as 12 arguments.

Thanks again for any suggestions.

David


> From: Dennis Lee Bieber 
> Subject: Re: Problem using cx_Freeze
> Date: August 15, 2022 at 8:18:54 PM MDT
> To: [email protected]
> 
> 
> On Mon, 15 Aug 2022 18:00:48 -0600, David at Booomer 
> declaimed the following:
> 
> 
>> However I now get an error
>> 
>> init() takes from 2 to 12 positional arguments but 14 were given
>> 
>> I found a couple instances of init in two .py files that were part of the 
>> whole.
>> 
>> One .py file
>> def __init__(self):
>> 
> 
>   Please cut&paste the TEXT of the console where the errors are displayed
> -- don't paraphrase!
> 
>   init() is NOT the same as __init__()
> 
>   WHAT "One .py file"? This is a meaningless bit of information.
> 
>   The most likely __init__() involved is the one where
> cx_Freeze.Executable is instantiated.
> https://cx-freeze.readthedocs.io/en/latest/setup_script.html#cx-freeze-executable
> shows 11 parameters (and "self" would make the 12th).
> 
> -- 
>   Wulfraed Dennis Lee Bieber AF6VN
>   [email protected]://wlfraed.microdiversity.freeddns.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem using cx_Freeze > auto-py-to-exe

2022-08-18 Thread David at Booomer
From: Dennis Lee Bieber 
> 
> On Wed, 17 Aug 2022 12:09:14 -0600, David at Booomer 
> declaimed the following:
> 
>>   executables=[
>>   Executable(
>>   
>> "prjui.py","Maiui.py","about.py","dict.py","geometry.py","getEquation.py",
>>   
>> "gtrail.py","main.py","matchingstring.py","producelatex.py","readfile.py",
>>   "separete.py","speak.py",
>>   )
>>   ]
>> )
>> 
>   You are defining a list "executables" with only ONE member... (and is
> that really how you spelled "separate").

Not my spelling, although I do have to be careful when typing that word.

From before:
"I’m trying to get LaTex-to-Speech 
(https://github.com/SGanesh19/LaTeX-to-Speech) to run as an accessibility aid, 
converting equations into speech. I haven’t used cx_Freeze before so stumbling 
somewhat."

> 
>> Searching for ‘__init__(' in the 13 *.py files returned five lines in two 
>> files (algorithm.py and prjui.py). As mentioned searching for this error 
>> only produced mention of adding self which is in these lines already. 
>> Previously I had search for __init__() which returned no lines due to the 
>> closing ).
>> 
>   You are still searching the wrong place... The __init__() that is
> complaining is the one in cx_Freeze.Executable().
> 
>> I had visited the page you provided 
>> (https://cx-freeze.readthedocs.io/en/latest/setup_script.html#cx-freeze-executable)
>>  but didn’t noticed the 11 plus self as 12 arguments.
> 
>   Really? Please count (reformatted from cut&paste):

I did count but hadn’t noticed this argument list before you mentioned it. 
However, I still don’t see any of these argument names in the Executable list 
or anywhere else.

> """
> argument name description
> 
> #1
> scriptthe name of the file 
> containing the script
> which is to be frozen
> 
> ...
> 
> #11
> trademarksthe trademarks value to include 
> in the version
> resource associated with the executable (Windows only).
> """
> 
>   You are passing 13 .py file names. There are only two arguments that
> really want file names: script, and init_script. Most of the other
> arguments are either optional or Windows specific (#6-11).
> 
>   I suspect you need to pass JUST main.py or Maiui.py (based on casing)
> -- which ever is really the file you'd invoke to start the program running.
> I'd hope the freeze system then scans (recursively) that file to find
> anything imported, and include those in the final product.
> 

I tried passing just main.py or one of the others that might be a starting 
point but just got ’NoneType has no len()

I was hoping to use someone else’s code to turn Latex equations into Speech. 
Maybe easier to just narrated each equation to create an audio file.

Thanks for your suggestions Dennis. This was the first time I saw the 
possibility of creating a python executable.

Then I searched for ‘python executable’ and found auto-py-to-exe and 
pyinstaller which I must/might explore later. First tries ran into PyQt4 to 
PyQt5 conversions. Good start at 
https://towardsdatascience.com/how-to-easily-convert-a-python-script-to-an-executable-file-exe-4966e253c7e9

I might wait for the original author to respond to an issue I posted on GitHub.

Thanks again. David

> -- 
>   Wulfraed Dennis Lee Bieber AF6VN
>   [email protected]://wlfraed.microdiversity.freeddns.org/
> 
...

> From: "Peter J. Holzer" 
> Subject: Re: Problem using cx_Freeze
> Date: August 17, 2022 at 3:17:27 PM MDT
> To: [email protected]
> 
> On 2022-08-17 12:09:14 -0600, David at Booomer wrote:
>>Executable(
>>
>> "prjui.py","Maiui.py","about.py","dict.py","geometry.py","getEquation.py",
>>
>> "gtrail.py","main.py","matchingstring.py","producelatex.py","readfile.py",
>>"separete.py","speak.py",
>>)
> [...]
>> I am/was worried about the trailing ‘,' after ',"speak.py”,’ <- but
>> deleting it or moving it after the ] didn’t help.
> 
> This has nothing to do with your problem but:
> 
> Python allows a trailing comma in any comma-separated list of values. It
> will just be ignored.
> 
> This is really common in modern pro

Re: How to replace all None values with the string "Null" in a dictionary

2005-10-28 Thread bruno at modulix
dcrespo wrote:
> Hi all,
> 
> How can I replace all None values with the string 'Null' in a
> dictionary?
> 
> For example:
> convert this:
> a = {'item1': 45, 'item2': None}
> 
> into this:
> a = {'item1': 45, 'item2': 'Null'}
> 

I think it would be time for you to read the Fine Manual...

for key in a:
  if a[key] is None:
a[key] = 'Null'


-- 
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: data hiding/namespace pollution

2005-10-31 Thread bruno at modulix
Alex Hunsley wrote:
> There's no really specific questions in this post, but I'm looking for
> people's thought on the issues within...
> 
> 
> The two main versions I've encountered for data pseudo-hiding
> (encapsulation) 


Hmmm... Are data-hiding and encapsulation really the same things ?


> in python are:
> 
> method 1:
> 
> _X  - (single underscore) - just cosmetic, a convention to let someone
>   know that this data should be private.
> 
> 
> method 2:
> 
> __X - (double underscore) - mangles the name (in a predictable way).
>   Avoids name pollution.
> 
> 
> How often does either tend to get used? Personally, I'd be a little
> worried about using method 1, because namespace clashes could happen. Is
> this overly paranoid?

Probably.

Note that prefixing names with a single underscore have a 'protected'
semantic - which means that such names (well, the objects that are bound
to...) can be overriden/extends by child classes.

I personnally only use the double-underscore notation only for things
that are *really* implementation-specific *and* should *really not* be
overriden.

> 
> Also, I presume that rather than people writing their own manual getter
> and setter methods, they tend to use either overloading on __getattr__
> and __setattr__, or the Property class (which itself uses aforementioned
>  methods). 

Yeps... This is the pythonic way.

> Overloading __getattr__ etc. seems more attractive to me, as
> then I can capture access to unknown names, and raise an exception!
> (I really don't like the idea of random attribute name typos going
> unnoticed when accessing attributes in a class!)

Err... Have you *really* tried to access an inexistant attribute ?  This
is usually not 'unnoticed' (unless you consider the raising of an
AttributeError as being the same as 'unnoticed' !-)

I personnaly use 'magic' accessors only for delegation or like, and
properties (or custom descriptors) for anything else (that requires
it...). This avoid the Big-Switch-Syndrom in __getattr__ and setattr__,
and is much more explicit (API, documentation, introspection etc...).

> Note: I do know that the use of the above things is quite dependent on
> what exactly you're coding, the size of the project etc., but what I'm
> trying to find out about is the python communities' recognised good
> practices.

Then launch your python interactive shell and type "import this"

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: data hiding/namespace pollution

2005-10-31 Thread bruno at modulix
Alex Hunsley wrote:
> bruno at modulix wrote:
> 
>> Alex Hunsley wrote:
>>
(snip)
>>>
>>> method 1:
>>>
>>> _X  - (single underscore) - just cosmetic, a convention to let someone
>>>  know that this data should be private.
>>>
>>>
>>> method 2:
>>>
>>> __X - (double underscore) - mangles the name (in a predictable way).
>>>  Avoids name pollution.
>>>
>>>
>>> How often does either tend to get used? Personally, I'd be a little
>>> worried about using method 1, because namespace clashes could happen. Is
>>> this overly paranoid?
>>
>> Probably.
>>
>> Note that prefixing names with a single underscore have a 'protected'
>> semantic - which means that such names (well, the objects that are bound
>> to...) can be overriden/extends by child classes.
> 
> 
> Ah, my mistake, not merely cosmetic then! Thanks.

Well, to be more exact, the point is not that _names can be overriden,
but that, due to name mangling, the following won't work, or, at least,
not as expected:

class Base(object):
def __dothis(self):
print "Base dothis"

def dothat(self):
print "Base dothat"

def run(self):
self.__dothis()
self.dothat()

class Child(Base):
def __dothis(self):
print "__%s_dothis" % self.__class__.__name__

def dothat(self):
print "%s dothat" % self.__class__.__name__

c = Child()
c.run()

(snip)

> Sorry, I wasn't being clear. What I should have said is that I don't
> like the idea of a typo in an assignment causing the assigning of the
> wrong thing.
> e.g. imagine a simple value-holding class:
> 
> class Values:
> pass
> 
> v = Values()
> 
> v.conductoin = 10
> 
> 
> ... I meant to type 'conduction' in the source but spelt it wrong.
> My value won't be there when elsewhere I refer to the correct attribute:
> "conduction".
> 

This kind of mistakes are usually not too hard to spot and not too hard
to correct. You'd have the same problem with a dict (and your Values
class is not much more than a dotted_syntax dict in disguise). BTW,
Pylint or Pychecker would catch this, and most unittests too.

Now if you have a case where this could really matter (like a user's
script), you can then define a more bondage_and_the_whip class with slots.

My overall experience with programming and Python is that keeping it
stupid simple where you can is usually the best approach. Your
__setattr__as_a_typo_catcher solution looks to me like a case of
arbitrary complexification. Better to go with the language than to fight
against it.

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: 'super' to only be used for diamond inheritance problems?

2005-10-31 Thread bruno at modulix
Alex Hunsley wrote:
> I've seen a few discussion about the use of 'super' in Python, including
> the opinion that 'super' should only be used to solve inheritance
> diamond problem. (And that a constructor that wants to call the
> superclass methods should just call them by name and forget about super.)
> What is people's opinion on this? Does it make any sense?


Since you'll never know how your class will be used, better to stick
with super... super(MyClass, self).dothis() is no more difficult to use
than MySuperClass.dothis(self), and does not require much more typing,
so I don't see any reason not to use 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: About the Python Expert

2005-11-02 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> Hey, i didnt say i need an expert. wel i did... anyways, i m just 
> saying that Fan is not a good python programmer, he doesnt know enough 
> python to help those who have joined his group, i know its askin a 
> lot, and i m not askin for a private tutor, just someone(s), to pop 
> into the group, see the discussions and help the people. but it is ur 
> decision.

Why would someone "pop into the group" when there are already this
newsgroup and the tutor ml ?

And if you are not happy with whatever group you joined, just quit.

-- 
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: expanding dictionary to function arguments

2005-11-02 Thread bruno at modulix
Noah wrote:
> Bruno Desthuilliers a écrit :
> 
>>Noah a écrit :
>>If you have control over the API functions declarations, makes them so:
>>def my_api_func(arg1='', arg2='whatever', **kwargs):
>>   code_here
> 
> 
> Unfortunately I cannot change the API functions.
> I should have mentioned that.

Yeps... That what I thought, but you didn't mention it, and it was not
that clear (or it's me being stupid...).

I'm no great expert, but apart from writing a generic decorator for the
API objects and decorating them all with your smart_apply function -
which won't by you much in this case imho -, I don't see a much better
solution...

Some guru around ???

-- 
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: when and how do you use Self?

2005-11-03 Thread bruno at modulix
Tieche Bruce A MSgt USMTM/AFD wrote:
> I am new to python,
> 
>  
> 
> Could someone explain (in English) how and when to use self?
> 
Don't use self. Use other.
-- 
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 write a blog system with Python

2005-11-03 Thread bruno at modulix
ice wrote:
> I am a fresh here , and I have no idea of it.
> Do you have any comments?
> 
Learn Python
Learn web programming
Write the specs for your blog system
Design the solution
Implement 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: when and how do you use Self?

2005-11-03 Thread bruno at modulix
Chris Cioffi wrote:

as a point of style, top-posting is a Bad Thing(tm)
(fixed)


> 
> On 03/11/05, bruno at modulix <[EMAIL PROTECTED]> wrote:
> 
>>Tieche Bruce A MSgt USMTM/AFD wrote:
>>
>>>I am new to python,
>>>
>>>Could someone explain (in English) how and when to use self?
>>>
>>
>>Don't use self. Use other.

> As a point of style:  the 'other' identifier should only be used in
> Zen Metaclass programming as an implicit reference to the calling
> object or as a list of references to all other instances of the class.

As a point of style, if it refers to a list, it should be 'others' and
not 'other'.

Also, this was supposed to be a joke. I can well understand that my sens
of humour is somewhat disastrous and that this was not a _good_ joke,
but "context should have made both clear and obvious" that it was one.

>  Context will make it both clear and obvious which use case is
> desired.

import 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: when and how do you use Self?

2005-11-03 Thread bruno at modulix
Steven D'Aprano wrote:
> On Thu, 03 Nov 2005 10:14:23 +0100, bruno at modulix wrote:
> 
> 
>>Tieche Bruce A MSgt USMTM/AFD wrote:
>>
>>>I am new to python,
>>>
>>> 
>>>
>>>Could someone explain (in English) how and when to use self?
>>>
>>
>>Don't use self. Use other.
> 
> 
> Are you serious? 

Are you seriously wondering if I am serious ?


-- 
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: I Need Motivation Part 2

2005-11-04 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> i m currently in a network (LAN). i started python because i heard 
> that it has great ability for networking programs and/or scripts, but 
> i m losing my motivation with python because there are sooo many 
> modules, that i cant just learn them all,

Why would you learn them all ? Learn the one you need when you need them
- jus don't forget to have a quick look at the existings modules before
reinventing the square wheel (I wrote a Q&D CSV parser before realinzing
there was a pretty good one in the stdlib... But what, my Q&D solution
took me laess than one hour to write and did what it had to do, so...)

> this deters from c or c++ in 
> which there are only a limited number of header files. 

In the stdlib, yes. Now there are thousands of librairies/frameworks
each reimplenting all the basic datastructure and algorithm (strings,
lists, hashtables, trees and the like), so you almost have to learn a
new language each time you use a new library.

> what loses my 
> interest is that if i cant learn these modules,

Once again : you don't have to.

> and there are lots and 
> lots of python modules, how can i ever be a good enough 
> programmer/scripter. 

Like everybody else: write programs. That's the only way to become a
programmer.

-- 
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: recursive function call

2005-11-08 Thread bruno at modulix
Nicolas Vigier wrote:
> Hello,
> 
> I have in my python script a function that look like this :
> 
> def my_function(arg1, arg2, opt1=0, opt2=1, opt3=42):
> if type(arg1) is ListType:

How should it behave with tuples or subclasses of List ? Or if it's any
other iterable ?

Testing against the *exact* type of an object is usually not a good idea
in Python. You should at least replace this test with something like:
  if isinstance(arg1, list): #code here

or even better:
  if hasattr(arg1, '__iter__'): # code here


or still even better (for maintenance at least):

def my_function(arg1, ...):
  def kind_of_list(arg):
return hasattr(arg1, '__iter__')

  if kind_of_list(arg1): # code here

> for a in arg1:
> my_function(a, arg2, opt1=opt1, opt2=opt2, opt3=opt3)
> return
> if type(arg2) is ListType:
> for a in arg2:
> my_function(arg1, a, opt1=opt1, opt2=opt2, opt3=opt3)
> return
>  ... then here the real function code
> 
> I'm new to python, so I was wondering if there is a better way to do that.

> The reason for a recursive function here is to be able to give lists for
> the first 2 args 


If possible, you'd better decide for a simplest API. Either always pass
a kind_of_list, or let the user take care of the loop.


You can also use two functions, one that actually do the job and the
other that do the test and wrap the call to the first (note that the
first function doesn't need to be part of the public API). This makes
code more readable, and cleany decouple effective task from the
test_type_and_dispatch mechanism. ie:

def doTheJob(arg, opt1=None, opt2=None, opt3=None):
  # effective code here
  pass

def callDoTheJob(arg1, arg2, opt1=0, opt2=1, opt3=42):
   if is_kind_of_list(arg1):
 for a in arg1:
callDoTheJob(a, arg2, )
   elif is_kind_of_list(arg2):
 for a in arg2:
callDoTheJob(arg1, a, )
   else:
  doTheJob(arg1, arg2, ...)

> (I could as well use only a simple 'for' without a
> recursive call). 

This can be better when it comes to perfs. I find the recursive solution
to be more readable (but this is a matter of taste), and it has the
advantage/drawback (depends on the real usage) that nested lists are
handled for (almost) any depth of nesting.

> The problem I have here, is that as I'm working on this
> script, I often change the prototype of the function, and each time I
> have to think about changing the recursive call too. Is there a way that
> I can do a recursive call and say something like "keep all the same
> arguments except this one" ?

If this only concern the 'opts' args:

def callDoTheJob(arg1, arg2, **kw):
   if is_kind_of_list(arg1):
 for a in arg1:
callDoTheJob(a, arg2, **kw)
   elif is_kind_of_list(arg2):
 for a in arg2:
callDoTheJob(arg1, a, **kw)
   else:
  doTheJob(arg1, arg2, **kw)


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: which feature of python do you like most?

2005-11-08 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> which feature of python do you like most?
> 
> I've heard from people that python is very useful.
> Many people switch from perl to python because they like it more.
> 
> I am quite familiar with perl, I've don't lots of code in perl.
> Now, I was curious and interested in the python people.
> They certainly made their best choice from perl to python.
> 
> but i have no interesting python experence before, thought i've read a
> few chapters
> of a python tutorial book. The things are much like the perl one.
> 
> I have no idea why people are so facinating with python.
>
> So I post this question:  What do you use in your dairy work with
> python?

Err... Python ?-)

> what is the thing that python makes you happy?

readability, expressivity, simplicity. And also everything-is-an-object.
And also list comprehensions. And also iterators and generators. And
also  properties, descriptors and metaclasses. And also anonymous
functions, callable objects and decorators. And the librairies too. And
a lot of other things, in fact...

> 
> I certainly don't want to miss a language if it's so great!
> can anyone share your happy experence with python?

Just install Python and use it, and you'll share our happy experience !-)



-- 
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: Diff. between Class types and classic classes

2005-11-08 Thread bruno at modulix
venk wrote:
> Hi,
>   can some one properly explain the differences between class types and
> classic classes? ... Still face problems in identifying what is what.

I'm not sure I understand your question. Are you talking about the diff
between old-style and new-style classes, or the diff between classes and
metaclasses ?

-- 
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: Hi, from my login i want to login as a other user ,

2005-11-09 Thread bruno at modulix
sumi wrote:
> Hi,  from my login i want to login as a other user ,  how can i do it
> using python.

http://www.catb.org/~esr/faqs/smart-questions.html

-- 
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: append to non-existing list

2005-11-09 Thread bruno at modulix
Yves Glodt wrote:
> Hello,
> 
> if I do this:
> 
> for row in sqlsth:
> pkcolumns.append(row[0].strip())
> etc
> 
> 
> without a prior:
> 
> pkcolumns = [];
> 
> 
> I get this error on first iteration:
> UnboundLocalError: local variable 'pkcolums' referenced before assignment
> 
> 
> 
> I guess that's normal as it's the way python works...?!?

yes sir.

> My question is: Is there no way to append to a non existing list?

No. Definitively. And that's a Good Thing(tm).

How would you use something that doesn't exist ???

> I am lazy for declaring it first,

s/declaring/instantiating/

If you were to use your own class Toto, would you ever hope that the
following code would work :

for v in some_seq:
  toto.dothis(v)

without instantiating Toto and binding it to the name 'toto' before ?
Well, in Python, a list is an instance of class list. There are
syntactic sugar to instanciate a list (or a tuple or a string or a dict
etc), but this:

my_list = []

is strictly equivalent to this:

my_list = list()

Now let's try something else:

class Machin(object):
  def append(self, value): pass

class Bidule(object):
  def append(self, value): pass

for i in range(10):
  m.append(i)


How should Python interpret this ? Should it create a list, or a Machin,
 or a Bidule, or an instance of whatever imported class having a
append() method ?

> IMHO it bloats the code,

run your python interpreter and type:
import this

Then read carefully.

Now if being explicit still hurts your personal convictions, there's
this other language with a name starting with p... !-)

> and (don't
> know if it's good to say that here) where I come from (php) I was used
> to not-needing it...

Not creating an Array before using it is Bad Style in PHP (and generate
a Warning BTW).

There are warts in Python (as in any other languages), and there are
things that sometimes bore me but are not really warts. But having to
explicitely instanciate objects can't be seen as a wart in any language
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: append to non-existing list

2005-11-09 Thread bruno at modulix
Yves Glodt wrote:
(snip)
> 
> ok I see your point, and python's...
> 
> (just FYI, and not to start a flamewar ;-):
> In php, the [] means "append to an array object".

yes, I know this.

> If the array does not exist yet, it's created.

Which is what I don't like. It should crash.

> [] *is* explicit for
> arrays, 

IIRC, you can also use it to sbscript strings, but I wouldn't bet my
life on this.

> thus for php it's clear what you want.)

Nope. You may be in the case where you think the array already exists,
and then you (well, I at least...) would prefer that PHP don't try to
second-guess you... If and when I want to create an object, I tell it.
If I dont tell "create me an array", I don't want one to come in existence.

(snip)
> an "undefined" notice, yes, not a warning... ;-)
> 
(snip)
>
> Ok... I thank you for all the explanations.
> 
> It helps me to see more far. I (and will continue to) use php for web,
> and wanna standardize on python for all non-web stuff we are doing, 

You might discover that Python is just great for web programming too !-)

> so I
> might be a frequent guest on this list...

You're welcome !-)
And if you're a french speaker, there's also french-speaking mailing
list and newsgroups.


-- 
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: iterate over class variables

2005-11-10 Thread bruno at modulix
Yves Glodt wrote:
> Yves Glodt wrote:
> 
>> Hello list,
>>
>> I need to iterate over a class and get all her variable names and
>> values, e.g. considering this example:
>>
>>
>> class testclass:
>> var1 = 'ab'
>> var2 = 'cd'
>> var3 = 'ef'

Take care, these are *class* variables, not instance variables.

>> test = testclass()
>>
>> Then I wanna do sonmething like this:
>>
>> for name,value in test:
>> print name
>> print value
>>
(snip)
>
> sorry for selfreplying, but I found a solution:
> 
> for key in dir(test):
> if '__' not in key:
> value = getattr(test,key)
> print key, value
> 
> Does anything speak about this?

1/ dir() doesn't necessary returns all the attributes of an object:
"""
dir(...)
dir([object]) -> list of strings

Return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it:
"""

But I don't think this is a problem here.

2/ everything being an object, dir() also returns methods (a method
being a - callable - attribute of the object's class).

If you're only interested in data attributes, you may want to try this:

for key in dir(test):
if not key.startswith('__'):
value = getattr(test,key)
if not callable(value):
print key, value


You can also check inspect.getmember()

-- 
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: getting results into one variable

2005-11-10 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> hi
(snip)
> 
> in python, can we do something like
> 
> a = db.execute(stmt) and then expand variable 'a'
> instead of doing
> (a,b) =  db.execute(stmt) for return of 2
> (a,b,c) = for return of 3
> (a,b,c,d) for return of 4


Did you try ?-) Took me about 30'':

>>> def fun(): return 1,2,3
...
>>> a = fun()
>>> a
(1, 2, 3)
>>> def fun2(): return 1,2,3,4,8,9
...
>>> b = fun2()
>>> b
(1, 2, 3, 4, 8, 9)
>>>

It of course works since a function *always* returns a *single* value.
Now this value *can* be a sequence, and this sequence *can* be unpacked
- directly at the return of the function, or latter:

>>> a = fun()
>>> a
(1, 2, 3)
>>> v1, v2, v3 = a
>>> v1
1
>>> v2
2
>>> v3
3
>>>

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: What do you use as symbols for Python ?

2005-11-10 Thread bruno at modulix
Pierre Barbier de Reuille wrote:
> When you need some symbols in your program, what do you use in Python ?
> 
> For example, an object get a state. This state is more readable if
> expressed as a symbols, for example "opened", "closed", "error".
> Typically, in C or C++, I would use an enum for that:
> enum OBJECT_STATE
> {
>   opened, closed, error
> }
> 
> In CAML or Haskell I would use the union types:
> 
> type ObjectState = Opened | Closed | Error
> 
> In Ruby I would use the symbols :
> 
> object.state = :opened
> object.state = :closed
> object.state = :error
> 
> ... but I don't know what to use in Python !

Depends on the job... If I need to do bitmask operations, I'll use
integer flags. If I want the symbol to be human-readable, I'll use
strings. But everything in Python being an object, you can use whatever
seems appropriate

Since we're in a 'state' exemple, here's a possible state pattern
implementation:

class MyObject(object):
def __init__(self, name):
self.name = name
self.__class__ = ClosedState

state = property(fget=lambda self: self.__class__)

def open(self, arg):
if arg == 1:
self.__class__ = OpenedState
else:
self.__class__ = ErrorState

def close(self):
self.__class__ = ClosedState


class OpenedState(MyObject):pass
class ClosedState(MyObject):pass
class ErrorState(MyObject):pass

m = MyObject('toto')
assert m.state is ClosedState
m.open(1)
assert m.state is OpenedState
m.close()
assert m.state is ClosedState
m.open(2)
assert m.state is ErrorState

I made states 'dummy' objects, but you could make this a real state
pattern implementation by defining default methods in the base class and
overriding appropriate methods in the 'state' subclasses.

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: derived / base class name conflicts

2005-11-11 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
(snip)
> So putting two underscores in front of an instance variable (or any
> identifier used inside the scope of a class statement) invokes a name
> mangling mechanism 

(snip)

> Is it commonplace to use underscores

I assume you mean double underscore...

> when defining derived class
> instance variables,
> or is this considered against the grain of python?

I don't know if it's 'commonplace', but that's something I only do when
I absolutely want to protect a given attribute of a base class from
being accidentally overriden by a derived class. Else I use the usual
convention ('_name' => implementation, 'name' => API), and assume users
 of my code will read the documentation (or the source FWIW) before
subclassing. Note that since 'users of my code' are mostly my coworkers
and I, this is a quite sensible assumption !-)

-- 
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: Command-line tool able to take multiple commands at one time?

2005-11-11 Thread bruno at modulix
Peter A. Schott wrote:
> Per subject - I realize I can copy/paste a line at a time into an interactive
> session when I'm trying to debug, but was wondering if there is any tool out
> there that allows me to copy sections of working Python scripts to paste into 
> my
> interactive console and let those run so I don't have to copy line-by-line.

There's much better than that : emacs + python-mode let you evaluate
either the whole script, a single class or def statement, or an
arbitrary region in an interactive Python interpreter running as an
emacs sub-process. Of course, this interpreter don't die after, so you
can inspect/play with/do whatever with the results of this evaluation.

-- 
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: Import statements for timeit module

2005-11-11 Thread bruno at modulix
ChaosKCW wrote:
> Hi
> 
> I was wondering if someone could help with the import statements needed
> to use the timeit module in the following code. I need to access the
> "cur" object.
> 
> Thanks,
> 
> import cx_Oracle
> import timeit
> 
> def VerifyTagIntegrity(con, TableOwner):
> cur = con.cursor()
> sql = 'select (select count(*) from %s.f4111) as F4111_COUNT,
> (select count(*) from %s.f4111_tag) as TAG_COUNT from dual;' %
> (TableOwner, TableOwner)
> print "  SQL: %s" % (sql)
> timer = timeit.Timer('cur.execute(sql)', 'from __main__ import
> cur')
> print timer.timeit()
> 

'cur' is local to the function, so it's not an attribute of your module,
so you can't hope to import it anyway.


-- 
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: Nufox : Nouveaux examples...

2005-11-11 Thread bruno at modulix
Salvatore wrote:
> Sur : http://www.salvatore.exolia.net:9090/
> (Nécessite Firefox ou Mozilla)
> 


Heu, Salvatore, tu te serais pas un peu trompé de ng, là ?-)
(x-post et fu2 f.c.l.py)



-- 
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 values from a webform to Python

2005-11-11 Thread bruno at modulix
mjakowlew wrote:
> hi,
> 
> I'm trying to pass some values from a webform into a python script.
> 
(snip)
> Also this
> is done through Zope if that makes a difference to anyone.

Yes, it makes a difference. Zope is a world in itself, and is slighty OT
here. Note that there's a Zope mailing-list:
http://mail.zope.org/mailman/listinfo/zope

(Zope answers sent in private)
-- 
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: Import statements for timeit module

2005-11-11 Thread bruno at modulix
ChaosKCW wrote:
> So timeit is mostly useless then ?
> 
I wouldn't say so.

-- 
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: replacing multiple instances of commas beginning at specific position

2005-11-14 Thread bruno at modulix
striker wrote:
> I have a comma delimited text file that has multiple instances of
> multiple commas.  Each file will contain approximatley 300 lines.  For
> example:
> 
> one, two, threefour,fivesix
> one, two, three,four,,eighteen,   and so on.
> 
> There is one time when multiple commas are allowed.  Just prior to the
> letters ADMNSRC there should be one instance of 4 commas. (
> ,eightADMNSRC,thirteen, ).  The text ADMNSRC is NOT in the same
> place on each line.
> 
> What would be the best approach to replace all instances of multiple
> commas with just one comma, except for the 4 commas prior to ADMNSRC?

Seems like a typical use case for the re module...
-> now you've got *2* problems- !-)


-- 
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: more newbie help needed

2005-11-15 Thread bruno at modulix
Steve Holden wrote:
> john boy wrote:
> 
>> using the following program:
>>  
>> fruit = "banana"
>> index = 0
>> while index < len (fruit):
>>  letter = fruit[index-1]
>>  print letter
>>  index= index -1
>>  

>> this program is supposed to spell "banana" backwards and in a vertical
>> patern...it does thisbut after spelling "banana" it gives an error
>> message:

(snip)


> Note, however, that there are more pythonic ways to perform this task.
> You might try:
> 
> for index in range(len(fruit)):
>   letter = fruit[-index-1]
>   print letter
> 
> as one example. I'm sure other readers will have their own ways to do
> this, many of them more elegant.

let's see... what about:

  for c in reversed(fruit): print c

or:

  print "\n".join(reversed(fruit))



-- 
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: Need advice on subclassing code

2005-11-15 Thread bruno at modulix
Rusty Shackleford wrote:
> Hi --
> 
> We have some code that returns an object of a different class, depending
> on some parameters.  For example:
> 
> if param x is 1 and y is 1, we make an object of class C_1_1.
> if param x is 1 and y is 2, we make an object of class C_1_2.
> 
> C_1_1 and C_1_2 share a common C ancestor, and in practice may be
> identical, but theoretically, could have the same function name with two
> different implementations underneath.
> 
> We have a file where all the C_X_Y classes are defined.  It looks sort
> of like this:
> 
(snip)

> 99% of the specific classes do the exact same thing.  For a tiny few,
> the class definition looks like this:
> 
(snip same code with minor differences...)
>
> The reason for this is that we want to allow different classes to do
> non-standard behavior.  In practice, however, it turns out that most of
> the time, we don't need anything special.
> 
> Is this the best solution? 

No, of course - but I guess you knew it already !-)

> Is there some way of doing a default vs.
> non-default deal, without having to manually hardcode all the different
> possible subclasses?

Here are the pieces of the puzzle:
- A dict is usually the best choice for lookups.
- A tuple can serve as key for a dict.
- A (reference to) a class object can be stored in a dict (or the name
of the class, as a string).
- the get() method of a dict allow for an optional default value to be
use if the requested key is not found

And here's a first go:

def get_object(x, y):
  specials = {
(1, 2): C_1_2,
(33, 42): C_33_42,
  }
  # assume class C is the default class
  klass = specials.get((x, y), C)
  return klass()

Now if you store the class names as strings, ie :


  specials = {
(1, 2): "C_1_2",
(33, 42): "C_33_42",
  }

you can use a config file (ini, XML, Yaml, or even plain old python) to
store the 'specials' mapping and the default class name, and have
get_object() read from that config file. The trick is to get the class
from the class's name, which is solved with getattr():

def get_object(x, y):
  specials = {
(1, 2): "C_1_2",
(33, 42): "C_33_42",
  }
  # assume class 'C' is the default class
  class_name = specials.get((x, y), "C")

  # from class name to class:
  klass = getattr(module_where_classes_live, class_name)
  return klass()


I think you should be able to solve your problem with this.

A last thing: the name of the module storing the classes can also be
stored in a conf file. Use __import__() to get the module object from
it's name.


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: Default method arguments

2005-11-15 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> Hello everybody!
> I have little problem:
> 
> class A:
> def __init__(self, n):
> self.data = n
> def f(self, x = )
> print x
> 
> All I want is to make self.data the default argument for self.f(). (I
> want to use 'A' class as following :
> 
> myA = A(5)
> myA.f()
> 
> and get printed '5' as a result.)
> 

class A(object): # Stop using old-style classes, please
  def __init__(self, n):
self.data = n
  def f(self, x = None):
if x is None:
  x = self.data
print 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: Default method arguments

2005-11-15 Thread bruno at modulix
Dennis Lee Bieber wrote:
> 
> 
(snip)
> but that may not be desirable if None is a valid value => myA.f(None),
> so...
> 
> class A(object):
> def __init__(self, n):
> self.data =n
> def f(self, *arg):
> if len(arg) == 0:
> x = self.data
> else:
> x = arg[0]
> print x

Another solution to this is the use of a 'marker' object and identity test:

_marker = []
class A(object):
def __init__(self, n):
self.data =n
def f(self, x = _marker):
if x is _marker:
x = self.data
print 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: HTML generation vs PSP vs Templating Engines

2005-11-16 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> Hello everybody,
> 
> I am in the process of writing my very first web application in Python,
> and I need a way to
> generate dynamic HTML pages with data from a database.  
(snip)
> After some thought I decided to leave the various frameworks
> aside for the
> time being and use mod_python.publisher 

I know this is not exactly an answer to your question, but have you
tried Django ?


-- 
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, Linux, Desktop Environment

2005-11-16 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> So, I've written my first GUI app in python.  I've turned it into a
> binary .exe and .app that runs on Windows and Mac respectively, but on
> my Linux box, where I wrote the thing, I still have to drop to the
> command line and ./myscript.py.  What can I do to make it a "click and
> run" sort of application in KDE or Gnome on Linux?

There are *no*  "click and run" on linux, since the GUI is an option,
not a part of the OS.

What you're looking for is WM/DesktopManager specific. You'll find the
answers in the Gnome and KDE manuals.


-- 
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 (rather) generic plugin framework?

2005-11-16 Thread bruno at modulix
Edvard Majakari wrote:
> Hi,
> 
> My idea is to create a system working as follows: each module knows
> path to plugin directory, and that directory contains modules which
> may add hooks to some points in the code.
> 
> Inspired by http://www.python.org/pycon/2005/papers/7/pyconHooking.html
> 
> I would create a class like this:
> 
> class Printer:
> 
> def printit(self, msg):
> stuff = self.beforePrintHook(msg)
> if stuff:
> msg = stuff
> print msg
> self.afterPrintHook(msg)
> 
> def beforePrintHook(self, msg): pass
> def afterPrintHook(self, msg): pass
> 
> Now, in the spirit of py.test, I'd like API to be practically no API at all :)
> moreover, deploying a plugin must consist simply of adding appropriate file to
> plugins directory, nothing more, and removing it would uninstall it. The
> plugin should be able to somehow result in all future invocations to
> Printer.printit() call hooks specified in the plugin. Now, the plugin module
> for class above /might/ be along the following lines (I'm thinking of stuff
> here, so I don't know yet what would be the most appropriate way):
> 
> ### a very simple plugin which uppercases all data fed to it.
> 
> extensions = {'Printer': 'PrinterHook'}
> 
> class PrinterHook:
> 
> def beforePrintHook(self, msg):
> return msg.upper()
> def afterPrintHook(self, msg):
> print "Called afterPrintHook with msg %s" % msg
> 
> 
> Now, I have a very rude (I think) implementation which has two methods, first
> the one that loads plugin modules:
> 

(snip code)

> 
> But hey, this has many downsides. First off, mechanism doesn't support
> arbitrary namespaces. Here, class identifier in the plugin must be as it is
> seen from the module which calls the plugin (not a problem for me, but could
> be more elegant; probably a mapping between logical class identifiers and
> actual class names, hmm?). Second, if one wants to use many hooks (with
> priority for conflicts), it is not possible now; set_hooks always overrides
> potentially existing hooks. And probably many other problems that are not
> obvious to me, but for the simple purpose I have in mind, it seems to work.

Just a couple of ideas:
- using decorators for plugin hooks ? ie:

import hooks

class Whatever(anything):
  @hooks.hook(for='Printer.beforePrintHook',priority=42)
  def my_function_with_a_long_name(self, *args, **kw):
 pass

The decorator would take care of "registering" the hook where relevant,
  ie, storing it in a class attribute of the hooked class ?

which leads to:

- in the hooked class, use a dict class attribute for hooks:

from hooks import run_hooks

class Printer
  # will be filled (and could even be created)
  # by the @hook decorator
  _hooks = {}

  def print(self, msg):
 # run_hooks will take care of selecting appropriate
 # hooks (by looking up the class attribute _hooks)
 # and running'em in order
 msg = run_hooks(self, 'Printer.beforePrintHook', msg)
 print msg
 run_hooks(self, 'Printer.afterPrintHook', msg)



My 2 cents... I don't even know if this can be implemented (but I don't
see why it couldn't).

> This is the first plugin system in Python I'm writing, so I can be a way off
> the correct path..



-- 
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: Zope vs Php

2005-11-18 Thread bruno at modulix
Steve wrote:
> I am going to go the mod_python route.
> 
> as for why a person would go route one over route 2
> 
> is that the number of lines of html/output vs python code are usually
> 10 to 1 and it's much easier to encapsulate the python code than to
> quote and escape all the html/css/xml
> 
> 
> <%
> #python code
> %>
>  some title
> 
> and
> 
> print output(python-code) + " some title".
> 
> are equivalent.

Yes, but this was *not* what I suggested.

There are a lot of HTML templating languages for Python, some being more
or less PHP-like (PSP, Cheetah, ...), some being way more
presentation-oriented (TAL, Kid, ...). I prefer the second category. I
share your opinion about html in code, but I also dislike code in html...



-- 
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: Zope vs Php

2005-11-18 Thread bruno at modulix
Mike Meyer wrote:
> Jorge Godoy <[EMAIL PROTECTED]> writes:
> 
>>Mike Meyer <[EMAIL PROTECTED]> writes:
>>
(snip)
>
> While I'm at it - how does KID do for things that aren't HTML?

It doesn't. Kid is explicitely for XML/HTML templating.


-- 
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 first element in the list of list

2005-11-22 Thread bruno at modulix
Ben Bush wrote:
> I have a lis:
> [[1,3],[3,4],[5,6],[8,9],[14,0],[15,8]]
> I want a code

Then write it.

And when (if) you have problems with it, repost, we'll then be happy to
help you.

> to test when the difference between the first element in
> the list of list is equal to or larger than 6,

I'm afraid you will never know what that difference is... Reminds me of
zen koan saying "the difference between a bird is that it neither know
how to fly".

Note that the use of "between" usually implies a second term !-)

BTW, also note that "the first element the first element in (a) list of
list(s)" is usually (well, I'd even say "always") a list itself.

> then move the previous
> lists to the end of the list. that is:
> [[14,0],[15,8],[1,3],[3,4],[5,6],[8,9]]


-- 
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 a curious assignment.

2005-11-23 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> [test 1]
> 
class A:
> 
> ...i = 1
> ...
> 
a = A()
A.i
> 
> 1
> 
a.i
> 
> 1
> 
A.i = 2
A.i
> 
> 2
> 
a.i
> 
> 2
> 
> 
> [test2]
> 
class A:
> 
> ...i = 1
> ...
> 
a = A()
A.i
> 
> 1
> 
a.i
> 
> 1
> 
a.i = 2
A.i
> 
> 1
> 
a.i
> 
> 2
> 
> 
> Is there somthing wrong

No.

-- 
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: strange behaviour when writing a large amount of data on stdout

2005-11-23 Thread bruno at modulix
Manlio Perillo wrote:
> Regards.
> 
> On my system:
> Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
> on win32, Windows XP
> 
> I have this problem:
> 
> 
n = 61409 + 1
data = 'x' * n
> 
> 
print data
> 
> 
> Traceback (most recent call last):
>   File "xxx", line xxx, in ?
> print data
> IOError: [Errno 12] Not enough space
> 
> Can someone reproduce this bug?

Not here, but it's a bipro amd64 with a couple Mb of ram !-)
(for the record, it works fine for far greater values, ie n = 12800)

> I begin to think that my system is messed up...


OF course it's messed up, else it wouldn't be a real Windows box !-)


-- 
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: user-defined operators: a very modest proposal

2005-11-23 Thread bruno at modulix
Joseph Garvin wrote:
> Tom Anderson wrote:
> 
>> Jeff Epler's proposal to use unicode operators would synergise most
>> excellently with this, allowing python to finally reach, and even
>> surpass, the level of expressiveness found in languages such as perl,
>> APL and INTERCAL.

s/expressiveness/unreadability/


-- 
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 new design pattern for Python Library?

2005-11-23 Thread bruno at modulix
Ben Sizer wrote:
> The Eternal Squire wrote:
> 
>>I tend to use this design pattern a lot in order to aid in
>>compartmentalizing interchangeable features in a central class that
>>depend on the central class's data.
> 
> 
> I'm afraid I've read this paragraph and the code 3 times and I still
> have no idea what you're trying to convey.



-- 
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 new design pattern for Python Library?

2005-11-23 Thread bruno at modulix
Ben Sizer wrote:
> bruno at modulix wrote:
> 
>>Ben Sizer wrote:
>>
>>>I'm afraid I've read this paragraph and the code 3 times and I still
>>>have no idea what you're trying to convey.
>>
>>
> 
> 
> Got anything more constructive to add?
> 

Why do you think I used this tag ?-)

-- 
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: books: Dive into Python vs Beginning Python

2005-11-25 Thread bruno at modulix
Franz Mueller wrote:
> Hi,
> 
> which of the following books would you recommend:
> "Dive into Python" or "Beginning Python: From Novice to Professional"?

I can't recommand the second since I've never read it. But you can
freely make your own opinion on the first, since it's freely available
online.


> I'm an experienced C++-programmer who wants to take a look at Python.

Then I'd say that Dive into Python may be a good choice.

Welcome BTW

-- 
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: Web functions idea

2005-11-29 Thread bruno at modulix
Mark Carter wrote:
> I was musing recently about how one could, for example, set up a really
> simple mailing subscription list. It occurred to me that a really simple
> way to implement it would be to use xmlrpc.
> So there could be a function
> subscribe(emailAddress),
> which would send an email for confirmation, and another function
> confirm(emailAddress, password)
> which would confirm the address ... and so on.
> 
> Now, the problem is that, if you use xmlrpc, it requires some kind of
> fiddly software that the client would have to install. What you would
> really want is some kind of web interface instead of xmlrpc - a kind of
> "web driven xmlrpc" (that would eliminate the need of an actual xmlrpc
> server).

Congratulations, you've just rediscovered REST !-)

> The point of it being this: a developer would just write the functions
> that he needed, a la xmlrpc, which would be "exposed" to this new module
> (let's call it webrpc) - and webrpc would examine the function, work out
> how many arguments it had, and display a form for the user to fill out.
> From an application writer's point-of-view, it abstracts away the whole
> web process, 

I'm afraid doing web developpement without a minimal knowledge of "the
whole web process" is somewhat unrealistic.

> leaving him free to just concentrate on the underlying
> function implementation.

Turbogears is probably what you're looking for (if not quite what you
describe).

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

2005-11-30 Thread bruno at modulix
David Rasmussen wrote:
> Frithiof Andreas Jensen wrote:
> 
>>
>> From the speed requirement: Is that correspondance chess by any chance??
>>
> 
> Regular chess at tournament time controls requires speed too. Any pure
> Python chess program would lose badly to the best C/C++ programs out
> there now.
> 
> I would also like to see Half Life 2 in pure Python.

There's nothing like "pure" Python. Python depends on a lot of libs,
most of them being coded in C++ or C (or assembly FWIW). The common
scheme is to use Python for the logic and low-level libs for the
critical parts.

And FWIW, I'd like to see any similar game in "pure" 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: mmm-mode, python-mode and doctest-mode?

2005-12-01 Thread bruno at modulix
John J Lee wrote:
> Is it possible to get doctest-mode to work with mmm-mode and python-mode
> nicely so that docstrings containing doctests are editable in doctest-mode?

I don't know.

(snip)
> 
> Any tips appreciated!
> 

Seems like comp.emacs could be a good place for this 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: [OT] mmm-mode, python-mode and doctest-mode?

2005-12-01 Thread bruno at modulix
John J. Lee wrote:
> bruno at modulix <[EMAIL PROTECTED]> writes:
> 
> 
>>John J Lee wrote:
>>
>>>Is it possible to get doctest-mode to work with mmm-mode and python-mode
>>>nicely so that docstrings containing doctests are editable in doctest-mode?
>>
(snip)
>>
>>Seems like comp.emacs could be a good place for this question
> 
> 
> I've only posted to gnu.emacs.help previously (the message you reply
> to was cross-posted there), 

Sorry, did not see that. But then you should have set the follow-up there.

> since the name seemed to suggest
> friendliness to people like me who use emacs a lot but are clueless
> with elisp :-)

You can script your emacs with Python too.

>.  But thinking again I guess comp.emacs is just the
> general emacs group, while gnu.emacs.help is the GNU-specific one?

Probably. I must say I don't spend that much time configuring my
emacs... Changing mode manually when needed is ok for me.

-- 
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: Instances behaviour

2005-12-02 Thread bruno at modulix
Inyeol Lee wrote:
(snip)

class A(object):
... def __init__(self, foo):
... if self.__class__ is A:
... raise TypeError("A is base class.")   


s/TypeError/NotImplementedError/
s/base class/abstract class/


-- 
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: Instances behaviour

2005-12-02 Thread bruno at modulix
Mr.Rech wrote:
> Thanks for your suggestions. They are very usefull and indeed bypass my
> problem. However, I've found a (perhaps) more elegant way to get the
> same result using metaclasses. 


(snip code)
> 
> I know metaclasses are a complete different beast, anyway I find this
> approach more pythonic. 

It's not. It's a case of ArbitraryOvercomplexification(tm).

The pythonic way is to use inheritence and make the base class abstract
by raising a NotImplementedError in it's __init__ (cf Inyeol Lee's
answer and my small correction)


-- 
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: Putting in an html table

2005-12-05 Thread bruno at modulix
Little wrote:
> Could someone start me on putting in a table into this code, and some
> HTML tags. I would to make the table below the map and have a header at
> the top. Thanks for the help.
> 
> """ Publisher example """
> 
> def query(req, building=""):
> # NOTE:  best way to understand this is to see the output,
> #  that is, to "view source" on the generated web page
> # read common header for any google mapping
> f = file('/home/ta/public_html/maplish/googleHead.html','r')

Never hardcode a path.

> t = f.read()
> f.close()
> # define the two buildings we know (because no SQL is done here)
> buildings =  [ ("cb", "Cambus Office",  "-91.552977", "41.659655")
> ]
> buildings +=  [ ("va/hardlib", "VA/Hardin Library", "-91.549501",
> "41.662348") ]
> buildings +=  [ ("hancher", "Hancher Auditorium",  "-91.538214",
> "41.669529") ]
> buildings +=  [ ("currier", "Currier Hall",  "-91.534996",
> "41.666163") ]
> buildings +=  [ ("schaeffer", "Schaeffer Hall",  "-91.535296",
> "41.660969") ]
> buildings +=  [ ("shospital", "South Hospital",  "-91.548900",
> "41.658885") ]

# avoid useless operations
 buildings =  [
   ("cb", "Cambus Office",  "-91.552977", "41.659655"),
   ("va/hardlib", "VA/Hardin Library", "-91.549501", "41.662348"),
   ("hancher", "Hancher Auditorium",  "-91.538214", "41.669529"),
   ("currier", "Currier Hall",  "-91.534996", "41.666163") ,
   ("schaeffer", "Schaeffer Hall",  "-91.535296", "41.660969"),
   ("shospital", "South Hospital",  "-91.548900", "41.658885")
]


> str = ''  #  in case no buildings match, use empty string
# don't use 'str' as an identifier, it will shadow the builtin str type.


> for x in buildings:
>a,b,c,d = x   # isolate all the tuple components into a,b,c,d
>if building.lower() == a:

If what you want is to find the building matching the one given as
argument, you should build a dict, not a list of tuples.

 buildings =  {
   "cb" : ("Cambus Office",  "-91.552977", "41.659655"),
   "va/hardlib" : ("VA/Hardin Library", "-91.549501", "41.662348"),
   "hancher" : ("Hancher Auditorium",  "-91.538214", "41.669529"),
   "currier" : ("Currier Hall",  "-91.534996", "41.666163") ,
   "schaeffer" : ("Schaeffer Hall",  "-91.535296", "41.660969"),
   "shospital" : ("South Hospital",  "-91.548900", "41.658885")
}

Now you don't need to loop and compare, a simple :
buildings.get(building.lower())
should be enough

(NB : Anyway, this dict should not be hardcoded. Put this in a separate
conf file, in a db, or whatever, but keep it out of the code.)


>   # construct javascript, using Python %s to substitute names
> and data
>   # see http://docs.python.org/lib/typesseq-strings.html if
> needed
>   str =  'var bldg%s = new GPoint( %s, %s);\n' % (a, c, d)
>   str += 'var mrk%s = new GMarker( bldg%s );\n' % (a, a)
>   str += 'var htm%s = "%s";\n' % (a, b)
>   str += 'GEvent.addListener(mrk%s,"click",function() {' % a
>   str += 'mrk%s.openInfoWindowHtml(htm%s); });\n' % (a, a)
>   str += 'map.addOverlay(mrk%s);\n' % a

string concatenation is not an efficient idiom. In a loop, the common
idiom is to use a list and join it, but here I guess a triple quoted
string and simple templating trick would be better.


> # output markers, if any
> t = t + str
> # then add trailing html to finish page
> trail = "//]]>   "
> t = t + trail
> return t

This is definitevely not how I would do HTML/js in Python. There are a
lot of templating / HTML generation tools available, that allow to
cleanly separate logic from presentation.

-- 
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: ADD HTML to the code

2005-12-05 Thread bruno at modulix
Little wrote:
> Could someone tell me how to add some HTML tags to this program. I want
> to be able to change the background color, add some headers, and put a
> table below the map that will be displayed. Could someone please tell
> me how to add this to the current program. Thanks in advance.
> 
(snip)
Do yourself a favor : check the various templating tools available,
choose one that fits you taste, and stop embedding half-baked html in
your Python code.


-- 
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: Efficient lookup in list of dictionaries

2005-12-05 Thread bruno at modulix
David Pratt wrote:
(snip)
> Can someone advise a more efficient lookup when using lists of
> dictionaries. Many thanks.
> 
> 
> TEST_CONSTANTS = [
> {'color':'red', 'shape':'octagon'},
> {'color':'yellow', 'shape':'triangle'},
> {'color':'green', 'shape':'circle'}]

COLOR_INDEX = dict([(item['color'], item) for item in TEST_CONSTANT])
SHAPE_INDEX = dict([item['shape'], item) for item in TEST_CONSTANT])

def getShapeForColor(color):
  return COLOR_INDEX.get(color, {'shape':None})['shape']

def getColorForShape(shape):
  return SHAPE_INDEX.get(color, {'color': None})['color']

This of course assume that there are no duplicate colors nor shapes.

-- 
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 with "lambda x : print x/60,x%60"

2005-12-05 Thread bruno at modulix
Gary Herron wrote:
> Mohammad Jeffry wrote:
> 
>> Dear All,
>>
>> Can't a lambda uses the input parameter more then once in the lambda
>> body?
>> eg:
>> lambda x : print x/60,x%60
>>
>> I tried with def and it works but got syntax error with lambda. Below
>> is an interactive sample:
> 
> 
> Lambda evaluates a single *expression* and returns the result.  As print
> is a statement it does not qualify (and would provide nothing to return
> even if it did).  So just use a def. 

or use sys.stdout.write in your lambda:
import sys
lambda x : sys.stdout.write("%d %d\n" % (x/60, x%60))

> It is constantly pointed out on
> this list that the lambda provides no extra expressive power, 

They do, when one need a very trivial callable for callbacks - which is
probably the main (if not the only) use case.

> it is
> merely a shortcut and, as you just found out, a rather restrictive one
> at that.

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: dynamic variable referencing

2005-12-07 Thread bruno at modulix
Michael Williams wrote:
> I would RTM, but I'm not sure exactly what to look for.  Basically, I 
> need to be able to call a variable dynamically.  Meaning something  like
> the following:
> 
> -  I don't want to say OBJECT.VAR  but rather 
> OBJECT. ("string")  and have it retrieve the variable (not the value
> of  it) if in fact it exists. . .

getattr(obj, 'name', defaultvalue)

You can also implement the special methods __getitem__ and __setitem__
to allow indexed access to attributes, ie:

class FalseDict(object):
  def __init__(self, toto, tata):
 self.toto = toto
 self.tata = tata
  def __getitem__(self, name):
 return getattr(self, name)
  def __setitem__(self, name, value):
 setattr(self, name, value)

f = FalseDict('toto', 'tata')
f['toto']
f['tata'] = 42

> 
> The purpose is to create an XML tree myself 

Don't reinvent the wheel. ElementTree (and it's C based brother) are
very good at 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: Mutability of function arguments?

2005-12-08 Thread bruno at modulix
ex_ottoyuhr wrote:
> I'm trying to create a function that can take arguments, say, foo and
> bar, and modify the original copies of foo and bar as well as its local
> versions -- the equivalent of C++ funct(&foo, &bar).

This is already what you have. In Python, all you have are references to
objects, there is no "local version".

> I've looked around on this newsgroup and elsewhere, and I gather that
> this is a very common concern in Python, but one which is ordinarily
> answered with "No, you can't. Neat, huh?" 

Pardon ???

>>> def appendToList(aList, aValue):
... aList.append(aValue)
...
>>> mylist = range(10)
>>> mylist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> appendToList(mylist, 42)
>>> mylist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 42]
>>>

Now the usual considerations apply :
- rebinding an arg has of course only local effect
- immutable objects are still immutables

Also note that since
1/ Python as a good support for exception handling
2/ a function can return multiple values [1],
there is less need for such constructs than in C or C++.

[1] the truth is that the function can return a unique tuple, that can
be unpacked as any other.

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


Virus in your Mail to empire.support

2005-03-18 Thread root at smtp

  The VirusCheck at the IMST generated the following Message:

 V I R U S  A L E R T

  Our VirusCheck found a Virus (W32/Netsky-Q) in your eMail to "empire.support".

  This eMail has been deleted !

  Now it is on you to check your System for Viruses   



  This System is running with Linux and Amavis (www.amavis.org).   :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Virus in your Mail to empire.support

2004-12-03 Thread root at smtp

  The VirusCheck at the IMST generated the following Message:

 V I R U S  A L E R T

  Our VirusCheck found a Virus (W32/Netsky-Q) in your eMail to "empire.support".

  This eMail has been deleted !

  Now it is on you to check your System for Viruses   



  This System is running with Linux and Amavis (www.amavis.org).   :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO in Python? ^^

2005-12-12 Thread bruno at modulix
Mike Meyer wrote:
> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> 
>>> ^^ There is no functionality to check if a subclass correctly
>>>implements an inherited interface
>>
>>I don't know of any language that provide such a thing. At least for
>>my definition of "correctly".
> 
> 
> Well, since your definition of "correclty" is uknown, I won't use
> it. 

!-)

My own definition of 'correctly' in this context would be about ensuring
that the implementation respects a given semantic.

But honestly, this was a somewhat trollish assertion, and I'm afraid
forgot to add a smiley here.


-- 
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: Proposal: Inline Import

2005-12-12 Thread bruno at modulix
Mike Meyer wrote:
> Shane Hathaway <[EMAIL PROTECTED]> writes:
> 
(snip)
> 
>>What's really got me down is the level of effort required to move code
>>between modules.  After I cut 100 lines from a 500 line module and
>>paste them to a different 500 line module, I have to examine every
>>import in both modules as well as examine the code I moved for missing
>>imports.
> 
> 
> Has it ever occured to you that if you're cutting and pasting 500 line
> blocks, you're doing something fundamentally wrong? One of the points
> of modules and OO is that you don't *have* to do things like
> that. Cut-n-paste means you wind up with two copies of the code to
> maintain, 

Mike, has it ever occured to you that this could be refactoring, not
copy_paste ?-)

(for the record, I too frequently *move* - not 'copy_paste' - big chunks
of code,  at least at the beginning of a project, or before a major
evolution)

-- 
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: Get rid of recursive call __getattr__

2005-12-14 Thread bruno at modulix
Pelmen wrote:
> How can I get rid of recursive call __getattr__ inside this method, if
> i need to use method or property of the class?
> 
Sorry, but I don't understand your question. Which recursive calls to
__getattr__ ? __getattr__ is only called if a/ it's defined and b/ the
attribute has not been found (see below).

Have you overriden __setattr__ or __getattribute__ ? If yes, please read
the corresponding sections of the Fine Manual.


>>> class Toto(object):
... def __init__(self, name):
... self.name = name
... def __getattr__(self, attname):
... print "__getattr__ called for %s" % attname
... return "%s doesn't exists" % attname
...
>>> t = Toto('toto')
>>> t.name = name
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'name' is not defined
>>> t.name
'toto'
>>> t.age
__getattr__ called for age
"age doesn't exists"

-- 
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: Get rid of recursive call __getattr__

2005-12-15 Thread bruno at modulix
Steve Holden wrote:
> Peter Otten wrote:
> 
>> Pelmen wrote:
>>
>>
>> class Test:
>>>
>>>
>>>  def __getattr__(self, attr):
>>>print attr
>>>
>>>  def foo(x):
>>>print x
>>>
>>>
>> t = Test()
>> print t
>>>
>>>
>>> __str__
>>>
>>> Traceback (most recent call last):
>>>  File "", line 1, in -toplevel-
>>>print t
>>> TypeError: 'NoneType' object is not callable
>>>
>>> what i have to do? define __str__ explicitly?
>>
>>
>>
>> By seemingly not returning anything your __getattr__() method actually
>> returns None. Instead you should raise an AttributeError when your
>> __getattr__() encounters the name of an attribute it doesn't handle.
>> Let's assume Test.__getattr__() should implement an attribute 'alpha' and
>> nothing else:
>>
>>
> class Test:
>>
>>
>> ... def __getattr__(self, name):
>> ... print "looking up", name
>> ... if name == "alpha":
>> ... return 42
>> ... print "lookup failed for", name
>> ... raise AttributeError
> 
> 
> or, rather better IMHO,
> 
>   raise AttributeError("lookup failed for %s" % name)

or still better in IMNSHO:
  raise AttributeError("%s object has no attribute %s" %
   \ (self.__class__.__name__,
  name))

(which is the 'standard' AttributeError message)



-- 
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: RoR like (was : SPE 0.8.1.b Python IDE...)

2005-12-15 Thread bruno at modulix
Yechezkal Gutfreund wrote:
> Are you familiar with any Python efforts that parrallel Ruby on Rails
> (integrated Ajax compliant IDE?).

"integrated" and "IDE" in the same sentence ? A bit redundant, isn't it ?-)

RoR is not an IDE, it's a web framework. The closest things in Python
are TurboGears (good Ajax/js support via Mochikit), Subway (never
tested), and Django (no Ajax support AFAIK).



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

2005-12-15 Thread bruno at modulix
Tuvas wrote:
> Let's say I make a program something like follows:
> 
> x=[]
> x.append([1,2,3])
> x.append([4,5,6])
> print x
> print x[0]
> print x[0][1]
> x[0][1]=5

Where are the tuples ?

> Okay, everything works here as expected except the last line. Why won't
> this work? 

Because you forgot to pay the salary ?-)

"don't work" is probably the worst description of a problem. Please take
time to explain what you expect and what you actually get.


-- 
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: definition of 'polymorphism' and python

2005-12-15 Thread bruno at modulix
Gabriel Zachmann wrote:
> I understand the Wikipedia article on Polymorphism
> ( http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 )
> that it doesn't make sense to talk about polymorphism in a fully
> dynamically typed language 

"a single polymorphic operator can act in expressions of various types"

>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list1 + list2
[1, 2, 3, 4, 5, 6]
>>> int1 = 1
>>> int2 = 2
>>> int1 + int2
3
>>> str1 = "aaa"
>>> strb = "bbb"
>>> str1 + strb
'aaabbb'
>>>

Ok, so we have polymorphic operators (if that wasn't obvious)

"A function that can evaluate to and be applied to values of different
types is known as a polymorphic function."

>>> id(1)
5279832
>>> id('aaa')
46912620984672
>>> id(list1)
46912620841680
>>> id(object())
46912496358832
>>> id(object.__class__)
46912499398624
>>> id(id)
46912496264616
>>>

Ok, so we have polymorphic functions too (if that wasn't obvious...)

"If all code is written without mention of any specific type and thus
can be used transparently with any number of new types, it is called
parametric polymorphism"

Well, seems that's what we (mostly) have

-- does the Python community agree?

I'm not the Python communauty, but I think you already guessed my answer !-)


-- 
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: RoR like (was : SPE 0.8.1.b Python IDE...)

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

Adrian, what you describe here is *exactly* what I call "no Ajax
support": you have to handle the whole thing manually, the framework
doesn't provide anything by itself. Would you say the CGI module offers
support for templating, data persistance and Ajax as well ?-)

And BTW, Ajax is not a client-side techno, it's a combination of client
*and* server-side technos. TurboGears support Ajax (well, a variant of,
since it's based on JSON, not XML) by having a pretty good, JSON aware
javascript lib (mochikit) for the client side *and* an OOTB JSON
serialization on the server side.

Hope that clears things up !-)

(PS : please, let's not start a Django-vs-TurboGears war, the
Ruby-Python pissing context is enough of a PITA)

-- 
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: Compressing folders in Windows using Python.

2006-01-01 Thread bren[at]gillatt.org
Heiko Wundram wrote:
> Steven D'Aprano wrote:
> 
>>>But when I run this script in Windows XP, I get an error while
>>>executing the above zip command.
>>
>>Would you like to tell us what error you get?
> 
> 
> I presume the error he's seeing is something along the line of:
> 
> "zip: Bad command or filename."
> 
> That's basically because there is no commandline builtin for zipping up
> files on Windows, and I don't know of WinZIP or any of the InfoZIP derived
> GUIs installing a command-line zipper.
> 
> What might help you though (and keep you platform-independent):
> 
> http://www.python.org/doc/2.4.2/lib/module-zipfile.html
> 
> --- Heiko.

Go and get something like 7-ZIP and put a path environment variable in.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Template language with XPath support for source code generation?

2006-01-12 Thread bruno at modulix
Stefan Behnel wrote:
> Hi!
> 
> I need to generate source code (mainly Java) from a domain specific XML
> language, preferably from within a Python environment (since that's where the
> XML is generated).
> 
> I tried using XSLT, but I found that I need a template system that supports
> Python interaction. I know, lxml's XSLT support is /somewhat/ getting there,
> but even with that, XSLT is so clumsy when it comes to code generation
> (looping constructs and if/else above all), that it would take me tons of XSLT
> code to write what I want.
> 
> I've been looking through Python templating systems all over the place, but I
> just can't find one that supports XPath - which is by far the best thing to
> have when you generate stuff from XML. TAL might be able to get me part of the
> way (at least, it supports some kind of Path expressions, though only for
> object access), but the only available implementation is part of Zope and I
> can't make my code depend on Zope only for a template system.

Zope's implementation can be used freestanding AFAIK. There's also
SimpleTal that is totally independant from Zope.


> My problem is that I want to write as little Python code as possible to make
> the templates (almost) stand alone and thus readable without the backend code.
> I can transform the XML language to a more usable XML format beforehand, no
> problem, but I then need to access the result from the template - and that's
> almost impossible without XPath.
> 
> Does anyone have an idea what I could use? Any hints are helpful.

Perhaps a TAL + elementTree combo could do ? (first parse the source XML
with elementTree, then pass the resulting tree as the context of the
ZPT/SimpleTal template)

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: Help me in this please--is Python the answer?

2006-01-12 Thread bruno at modulix
Ray wrote:

(snip)
> But then on the other hand, there is a manpower problem--it's damn easy
> to find a Java programmer (although the quality that you get is a
> different matter). Python programmers are more difficult.

Possibly - but if a programmer is not able to pick on Python in a matter
of days, then it's a bad programmer that won't be of any help whatever
the language. So in fact, choosing Python may help you get better
programmers !-)

> 
>>If I were you I'd concentrate on creating a website that actually
>>works.  Your chances of creating a website that needs to scale to be
>>'heavyweight' are very slim.  If you manage to get to that point then
>>you can start worrying about how to cope with all the money that's
>>rolling in ;)
> 
> 
> You know what, this is a very good point :))
> 
> 
>>AFAIAA Python scales better than Java as any performance critical
>>parts can be easily rewritten in C.  To spend too much time worrying
>>over it is premature optimisation though.
> 
> 
> Yes, but this is more of a web application though--something that I've
> never developed in Python before, so... I'll be evaluating Django
> shortly--let me see how it compares to Tomcat.

You may also want to have a look at turbogears (roughly similar to
Django, but probably much more flexible)

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: how do "real" python programmers work?

2006-01-13 Thread bruno at modulix
Barbier de Reuille Pierre wrote:
> On 12 Jan 2006 12:20:50 -0800
> "bblais" <[EMAIL PROTECTED]> wrote:
> 
> 
>>Hello,
>>
(snip)
> 
> 
> Well, I think it will depend on your project ...
> If you're developing GUI application, you will have trouble using the
> python shell. At least you will need a special, customized shell that
> will take care of launching the main loop of your GUI and let you enter
> commands. 

Well, most of your code should be runnable/testable without the GUI
part, so that may not be such a big problem.

(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


  1   2   3   4   5   6   7   >