Re: import reassignment different at module and function scope

2009-01-31 Thread Gabriel Genellina
En Sat, 31 Jan 2009 05:31:47 -0200, Brendan Miller   
escribió:



If I:

import sys

sys = sys.version

This executes find but:

import sys

def f():
sys = sys.version

This gives an error indicating that the sys on the right hand side of =
is undefined. What gives?


Python doesn't have local variable declarations. Inside a function, *any*  
name that is assigned to (e.g. any name appearing on the left side of an  
assignment operation, like "a" in a=8) becomes a local variable. In your  
example, "sys" is a local variable, and it "shadows" (or "hides") the  
global one of the same name.

When the interpreter tries to execute
sys = sys.version
it complains that it can't evaluate sys.version because the local name  
"sys" has not been assigned yet.


The same thing at the global level is OK, because sys.version refers to  
the global "sys" name.


(This should appear in the FAQ...)

--
Gabriel Genellina

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


Re: is python Object oriented??

2009-01-31 Thread Laszlo Nagy

M Kumar wrote:
Object oriented languages doesn't allow execution of  the code without 
class objects, what is actually happening when we execute  some piece 
of code, is it bound to any class?

Those who have time and consideration can help me
There are many kinds of definitions for "object oriented" languages. I 
have learned some things in the University, and one of them was making 
distinction between "pure object oriented" languages, and "mixed" languages.


Pure object oriented languages does not have programming tools that are 
non-objects. A good example was SmallTalk, if I remember correctly.


Python is not a pure object oriented language, because it has other 
programming tools, for example functions.


However, your question seems to be pedantry. As others would say, "you 
can do programming in FORTRAN in any language". In other words, it is 
possible to use Python in a non object-oriented way, but the "good" way 
of using it is defining classes and making objects... So Python *is* 
object oriented, if you use it the right way. There might be a 
definition of "object oriented language" that does not apply to Python, 
and theoretically, you could say that according to that definition, 
Python is not object oriented. But practically, it is!


Best,

  Laszlo

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


HTTPSConnection: client certificate auth

2009-01-31 Thread Mailing List SVR
Hi all,

I have a soap client using ZSI, the other end is oracle soa 10.1.3.1.0
all works fine since some months. The last week oracle soa was
configured to accept client certificate authentication over https. If I
try to use the standard python httplib.HTTPSConnection library it fails
with the infamous "bad record mac" error and so also ZSI that use
httplib. If I configure client certificate authentication on my own
apache all is fine


>>> from httplib import HTTPSConnection 
>>>
conn=HTTPSConnection('192.168.2.66',443,'/etc/cert/clients1.key','/etc/cert/clients1.crt')
>>> conn.request('GET','/ws?wsdl')
>>> r=conn.getresponse()
>>> r.read()

the connection to oracle soa works fine with other java tools such as
soapui,

there is some known workaround for using HTTPSConnection with oracle
soa?

I'm using python 2.4 on red hat 5,

thanks
Nicola

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


Re: Want to write a script to do the batch conversion from domain name to IP.

2009-01-31 Thread Hongyi Zhao
On Sat, 31 Jan 2009 04:10:39 -0200, "Gabriel Genellina"
 wrote:

>En Fri, 30 Jan 2009 12:53:33 -0200, Hongyi Zhao   
>escribi$)A(.:
>
>>> See the following errors I in my case:
>>>
>>> $ python
>>> 'import site' failed; use -v for traceback
>
>> import socket
>>> Traceback (most recent call last):
>>>  File "", line 1, in 
>>> ImportError: No module named socket
>
>Those errors indicate that Python is not working correctly in your system.  
>You should fix it before going on.

I use cygwin, I don't know whether the further discussion on fix this
issue is suitable for this group or not?  If not, could you please
give me some hints on the newsgroups or maillists I should resort to?

>
>> Another issue is: how can I perform all of these steps in a python
>> script?
>
>Start reading the tutorial and working the examples:  
>http://docs.python.org/tutorial/
>In a short time (maybe shorter than you expect) you'll manage enough of  
>Python to do this.
>Come back when you have specific questions, or try the tutor list:  
>http://mail.python.org/mailman/listinfo/tutor

Thanks, I've subscribe to this list.

-- 
.: Hongyi Zhao [ hongyi.zhao AT gmail.com ] Free as in Freedom :.
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-31 Thread anders
Tanks everyone that spent time helping my, the help was great.
Best regards Anders
--
http://mail.python.org/mailman/listinfo/python-list


How to manipulate a contents of file as record structures

2009-01-31 Thread CK Raju
I have a text file containing the following alphanumerals.
aa2255
hh11dpdpdpdp22
kkk21lokolkolko33
.

I need to read the contents as single line, one after the other
and append the sum of digits at the end.
aa225577
hh11dpdpdpdp2233
kkk21lokolkolko3354


What would be a simple way to achieve this ?
CK Raju
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to manipulate a contents of file as record structures

2009-01-31 Thread Gabriel Genellina
En Sat, 31 Jan 2009 08:35:44 -0200, CK Raju   
escribió:



I have a text file containing the following alphanumerals.
aa2255
hh11dpdpdpdp22
kkk21lokolkolko33
.

I need to read the contents as single line, one after the other
and append the sum of digits at the end.
aa225577
hh11dpdpdpdp2233
kkk21lokolkolko3354


What would be a simple way to achieve this ?



Suppose f is the open file. To read it a line at a time:
for line in f:
  do_something_with(line)

To search for a number, try the re module:  
http://docs.python.org/library/re.html


To do some calculation with those numbers, remember to convert them to  
integers first:

x="12"
y="34"
x+y gives "1234"
int(x)+int(y) gives 46

Good luck!

--
Gabriel Genellina

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


Re: How to manipulate a contents of file as record structures

2009-01-31 Thread CK Raju
On Sat, Jan 31, 2009 at 4:19 PM, Gabriel Genellina
 wrote:
> for line in f:
>  do_something_with(line)

Thanks a lot.
CK Raju
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-31 Thread MC

Re


‘builtin’ is not a class.


I think "object" ; not only "class"
And "builtin" is an object.




--
@-salutations

Michel Claveau


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


Re: Why doesn't eval of generator expression work with locals?

2009-01-31 Thread Aaron Brady
On Jan 31, 1:08 am, "Hendrik van Rooyen"  wrote:
> "Gabriel Genellina"  wrote:
snip
> >or even like this:
>
> >def foo(L, M, A):
> >   for x in L:
> >     for y in M:
> >       yield x+A
> >g = foo(iter(L), iter(M), A)
>
> >In particular, I like the 2nd (all late binding). Seems this topic was  
> >discussed many times [1] when PEP289 [2] was proposed, and "practicality  
> >beats purity".
>
> Ok thanks - I see where you are coming from now.
> It never ceases to amaze me how different we all are -
> Given a choice, I would have chosen the last alternative,
> as it feels more natural to me - the one you like feels to
> me as if it were too tightly coupled, somehow. - almost
> as if you were using named globals in a function instead
> of passing arguments in.
snip

Did anyone observe this yet?

>>> global_vars = {}
>>> local_vars = {'ar':["foo", "bar"], 'y':"bar"}
>>> print eval('all((x == y for x in ar))', local_vars, global_vars )
False
>>> print eval('all((x == y for x in ar))', global_vars, local_vars)
#error as original
--
http://mail.python.org/mailman/listinfo/python-list


Re: SimpleXMLRPCServer question

2009-01-31 Thread andrew cooke
On Jan 30, 11:59 pm, flagg  wrote:
> I am working on a very basic xmlrpc server, which will expose certain
> functions for administering BIND zone files.  The big problem I am
> having is parsing the incoming xmlrpc request.  Basically part of the
[...]

at the risk of repeating what the other guy said, it sounds like
you're going about this in the wrong way.  the xmlrpc server will
parse the incoming request for you if you supply it with a suitable
function to invoke.  so, for normal use, you do not override anything.

andrew

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


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-31 Thread Marc 'BlackJack' Rintsch
On Fri, 30 Jan 2009 21:59:34 +0100, Stef Mientki wrote:

> Marc 'BlackJack' Rintsch wrote:
>> On Fri, 30 Jan 2009 00:25:03 +0100, Stef Mientki wrote:
>>
>>
>>> try this:
>>>
>>> class MyRegClass ( int ) :
>>>   def __init__ ( self, value ) :
>>> self.Value = value
>>>   def __repr__ ( self ) :
>>> line = hex ( self.Value )
>>> line = line [:2] + line [2:].upper()
>>> return line
>>> 
>>> 
>> def __repr__(self):
>> return '0x%X' % self.value
>>
>>
>>>   __str__ = __repr__
>>> 
>>> 
>> This is unnecessary, the fallback of `__str__` is `__repr__` already.
>>
>>
> well this is what my Python is doing:
> 
> without  _str__ = __repr__
>  >>print shadow_register
> 170
> 
> with  _str__ = __repr__
>  >>print shadow_register
> 0xAA

Then don't inherit from `int`.  Why are you doing this anyway?  If you 
inherit from `int` you shouldn't store the value in an extra attribute 
but use the `int`\s value.  This way you have one value used by the `int` 
methods and one used by your own methods.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Where to host a (Python) project?

2009-01-31 Thread andrew cooke
Hi,

I have a new project, that I just released in beta (http://
www.acooke.org/lepl - a recursive decent parser with full
backtracking).  At the moment I am using pypi and setuptools for
distribution (it's a pure python package) and I am happy with hosting
static web pages (the manual and api doc linked to above) on my own
site (I did try the packages.python.org web pages, but it seemed
pointless duplicating my own).

However, i am thinking I could really do with:
- a mailing list
- simple bug tracking
- subversion
and am wondering which is the best (free) provider for these (the code
is LGPL open source).  I'd prefer a mailing list to something like
google groups (although I guess it may be possible to configure a
gateway) and I could open up my personal subversion server, but that
seems like a lot of work (not really that interested in moving to
something other than svn).

Any recommendations?

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


Why do operators and methods of built-in types differ

2009-01-31 Thread Csaba Hoch

Hi,

if I write the following:

   >>> 1+1
   2

it seems to be exactly equivalent to this:

   >>> (1).__add__(1)
   2

However, if I write invalid code and try to add a list to an int, the
errors will be different:

   >>> 1+[]
   Traceback (most recent call last):
 File "", line 1, in 
   TypeError: unsupported operand type(s) for +: 'int' and 'list'

   >>> (1).__add__([])
   NotImplemented

I found that operator.__add__(1, []) gives the same result as 1+[].

What is the reason behind this difference between the __add__ operator
and int.__add__?

Thank you,
Csaba
--
http://mail.python.org/mailman/listinfo/python-list


Empty string is False right?

2009-01-31 Thread AJ Ostergaard

Hello,

First post so bear with me if I'm being a numpty ...

Is it me or is there something slightly counter intuitive and thus not  
so pythonesque about this:


>>> s = ''
>>> if s: True
... else: False
...
False
>>> s and eval(s)
''
>>>

Regards,
AJ

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


Re: Empty string is False right?

2009-01-31 Thread Ralf Schoenian

AJ Ostergaard wrote:

Hello,

First post so bear with me if I'm being a numpty ...

Is it me or is there something slightly counter intuitive and thus not 
so pythonesque about this:


 >>> s = ''
 >>> if s: True
 else: False

False
 >>> s and eval(s)
''
 >>>

Regards,
AJ



Hi,

yes, the following evaluates to False:
empty String: ''
empty list: []
empty tuple: ()
empty dict: {}
0, None
and False of course

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


Re: Empty string is False right?

2009-01-31 Thread AJ Ostergaard

Hi Ralf,

Thanks for that but why:

>>> '' and True
''

Surely that should be False?!?

Regards,
AJ


On 31 Jan 2009, at 12:12, Ralf Schoenian wrote:


AJ Ostergaard wrote:

Hello,
First post so bear with me if I'm being a numpty ...
Is it me or is there something slightly counter intuitive and thus  
not so pythonesque about this:

>>> s = ''
>>> if s: True
 else: False

False
>>> s and eval(s)
''
>>>
Regards,
AJ


Hi,

yes, the following evaluates to False:
empty String: ''
empty list: []
empty tuple: ()
empty dict: {}
0, None
and False of course

Regards,
Ralf


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


Re: nth root

2009-01-31 Thread Mark Dickinson
On Jan 31, 5:43 am, "Tim Roberts"  wrote:
> Dan,
>
> Thanks - you're probably right - just my intuition said to me that rather 
> than calculating that the 13th root of 
> 4021503534212915433093809093996098953996019232
> is 3221.2904208350265
> there must be a quicker way of finding out its between 3221 and 3222
>
> but perhaps not.

I don't think you'll find anything much quicker than n**(1./13)
(though I hope
that if you're doing this millions of time then you're precomputing
the 1./13
rather than redoing the division every single time.

What happens behind the scenes here is that your integer is
immediately
converted to a float, then the system math library is used for the
power operation.  The integer -> float conversion is probably quite
significant, timewise.

I'd also be a bit worried about accuracy.   Is it important to you
that the
integer part of the result is *exactly* right, or is it okay if
(n**13)**(1./13) sometimes comes out as slightly less than n, or if
(n**13-1)**(1./13) sometimes comes out as n?

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


Re: Empty string is False right?

2009-01-31 Thread Gabriel Genellina
En Sat, 31 Jan 2009 10:16:19 -0200, AJ Ostergaard   
escribió:



Hi Ralf,

Thanks for that but why:

 >>> '' and True
''

Surely that should be False?!?


Python does "short-circuit evaluation" [1]
"and" and "or" return one of its operands as soon as the outcome is  
determined, not just True or False.

'' is a false value, as false as False itself :)
After seeing that, there is no point in evaluating the second operand  
(True) because the final result cannot be true; so Python just returns the  
first operand.


[1] http://en.wikipedia.org/wiki/Short_circuit_evaluation

--
Gabriel Genellina

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


Re: Empty string is False right?

2009-01-31 Thread Vlastimil Brom
2009/1/31 AJ Ostergaard :
> Hi Ralf,
>
> Thanks for that but why:
>
 '' and True
> ''
>
> Surely that should be False?!?
>
> Regards,
> AJ
>
>
see the docs:
http://docs.python.org/reference/expressions.html#boolean-operations

"The expression x and y first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is
returned."

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


Re: Empty string is False right?

2009-01-31 Thread Bernd Nawothnig
On 2009-01-31, AJ Ostergaard wrote:

> Thanks for that but why:

 '' and True
> ''

> Surely that should be False?!?

It is:

#v+
>>> bool('' and True)
False
#v-



Bernd

-- 
No time toulouse
--
http://mail.python.org/mailman/listinfo/python-list


Re: Empty string is False right?

2009-01-31 Thread John Machin
On Jan 31, 11:12 pm, Ralf Schoenian  wrote:

> yes, the following evaluates to False:

A much better way of describing the effect would be to say that the
following are treated as false (no capital letter!) in a conditional
context.

> empty String: ''
> empty list: []
> empty tuple: ()
> empty dict: {}

*any* empty container ...

> 0, None
> and False of course

and objects which adhere to the protocol
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why do operators and methods of built-in types differ

2009-01-31 Thread andrew cooke
On Jan 31, 8:51 am, Csaba Hoch  wrote:
> What is the reason behind this difference between the __add__ operator
> and int.__add__?

this is quite common in python.  the special methods like __add__ are
used to implement some functionality (like '+' in this case), but they
are not all of it.  for example, when
  a + b
is evaluated, a.__add__(b) is attempted, but if that fails (raises a
NotImplemented error) then b.__radd__(a) is tried instead.

so there's not a 1-to-1 correspondence between '+' and __add__() and
that is reflected in the exceptions, too.  when a method does not
exist a NotImplemented error is raised, but '+' contains extra logic
and raises a more useful error message.

does that make sense?  i should probably add that this is just how i
understand things - i assume it's correct, but i've not looked
anything up in the documentation.

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


Re: Empty string is False right?

2009-01-31 Thread AJ Ostergaard
I'm not suggesting it's not operating as advertised - I'm suggesting  
the 'advertising' is slightly sguiffy if you catch my drift. I guess  
it's just me that finds it slightly counter intuitive. Surely  
intuitively the expression is "and" and therefore should always return  
a boolean?


I'll shut up now. ;)

AJ


On 31 Jan 2009, at 12:27, Vlastimil Brom wrote:


2009/1/31 AJ Ostergaard :

Hi Ralf,

Thanks for that but why:


'' and True

''

Surely that should be False?!?

Regards,
AJ



see the docs:
http://docs.python.org/reference/expressions.html#boolean-operations

"The expression x and y first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is
returned."

hth,
 vbr


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


Re: Why do operators and methods of built-in types differ

2009-01-31 Thread Gabriel Genellina
En Sat, 31 Jan 2009 09:51:35 -0200, Csaba Hoch   
escribió:



if I write the following:

>>> 1+1
2

it seems to be exactly equivalent to this:

>>> (1).__add__(1)
2

However, if I write invalid code and try to add a list to an int, the
errors will be different:

>>> 1+[]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'list'

>>> (1).__add__([])
NotImplemented

I found that operator.__add__(1, []) gives the same result as 1+[].

What is the reason behind this difference between the __add__ operator
and int.__add__?


The operator "+" does more than blindy calling left.__add__(right). In  
this case, as int + list returns NotImplemented, it reverses the operands  
and tries right.__radd__(left), and only then it gives up and raises  
TypeError.


The actual rules are a bit more complex, involving type conversion too;  
see http://docs.python.org/reference/datamodel.html#emulating-numeric-types


--
Gabriel Genellina

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


Re: Empty string is False right?

2009-01-31 Thread John Machin
On Jan 31, 11:16 pm, AJ Ostergaard  wrote:
> Hi Ralf,
>
> Thanks for that but why:
>
>  >>> '' and True
> ''
>
> Surely that should be False?!?

No, deliberately not. Read this for Python 3.0
http://docs.python.org/3.0/reference/expressions.html#boolean-operations
and/or this for Python 2.X
http://docs.python.org/reference/expressions.html#boolean-operations
[essentially the only difference in 3.0 is a change to the protocol
that allows a non-builtin object to say whether it is true or false]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why do operators and methods of built-in types differ

2009-01-31 Thread Csaba Hoch

Gabriel Genellina wrote:
The operator "+" does more than blindy calling left.__add__(right). In 
this case, as int + list returns NotImplemented, it reverses the 
operands and tries right.__radd__(left), and only then it gives up and 
raises TypeError.


The actual rules are a bit more complex, involving type conversion too; 
see http://docs.python.org/reference/datamodel.html#emulating-numeric-types


Thanks for both of you, it's much clearer now.

Just a correction: according to the doc, NotImplemented is not an
error, but a returned value.

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


Re: Where to host a (Python) project?

2009-01-31 Thread Martin
Hi,

2009/1/31 andrew cooke :
> However, i am thinking I could really do with:
> - a mailing list
> - simple bug tracking
> - subversion
> and am wondering which is the best (free) provider for these (the code
> is LGPL open source).  I'd prefer a mailing list to something like
> google groups (although I guess it may be possible to configure a
> gateway) and I could open up my personal subversion server, but that
> seems like a lot of work (not really that interested in moving to
> something other than svn).

Google Groups can be perfectly used as Mailings Lists - while I'm not
a huge fan of them that isn't an argument from your feature list :)

There's tigris.org, savannah (savannah.gnu.org, nongnu.org),
launchpad. All of them are fine to some extent, you might want to read
up on PyMotW about how Doug Hellmann decided where to host his stuff.

hth
Martin
-- 
http://soup.alt.delete.co.at
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Empty string is False right?

2009-01-31 Thread Ben Finney
Ralf Schoenian  writes:

> yes, the following evaluates to False:
> empty String: ''
> empty list: []
> empty tuple: ()
> empty dict: {}
> 0, None
> and False of course

More precisely: All the above evaluate as Boolean false. But only one
of them evaluates to False: the object bound to the name ‘False’.

>>> bool(None) == bool(False)
True
>>> None == False
False
>>> None is False
False

>>> bool('') == bool(False)
True
>>> '' == False
False
>>> '' is False
False

>>> bool(0) == bool(False)
True
>>> 0 == False
False
>>> 0 is False
False

-- 
 \ “What is it that makes a complete stranger dive into an icy |
  `\   river to save a solid gold baby? Maybe we'll never know.” —Jack |
_o__)   Handey |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why do operators and methods of built-in types differ

2009-01-31 Thread andrew cooke

> Just a correction: according to the doc, NotImplemented is not an
> error, but a returned value.

curious, so it is.  i wonder why there is both a special return value
(NotIMplemented) and a related exception (NotImplementedError).  seems
very odd to have a value...

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


Re: is python Object oriented??

2009-01-31 Thread Steve Holden
MC wrote:
> Re
> 
>> ‘builtin’ is not a class.
> 
> I think "object" ; not only "class"
> And "builtin" is an object.
> 
You can think what you like, but there is a fundamental difference
between methods of a class and functions of a module. Until you
appreciate that you will likely make mistakes. Don't worry, though, we
all learn from our mistakes.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Where to host a (Python) project?

2009-01-31 Thread andrew cooke
On Jan 31, 9:59 am, Martin  wrote:
> There's tigris.org, savannah (savannah.gnu.org, nongnu.org),
> launchpad. All of them are fine to some extent, you might want to read
> up on PyMotW about how Doug Hellmann decided where to host his stuff.

all i can find is that he is writing his own!
http://blog.doughellmann.com/search/label/codehosting
(his reqs are quite different to mine - I am looking for an external
provider because I do not want to host dynamic pages myself).

anyway, if that was what you mean, fine - i just wonder if i am
missing something?

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


Re: nth root

2009-01-31 Thread Steve Holden
Mark Dickinson wrote:
> On Jan 31, 5:43 am, "Tim Roberts"  wrote:
>> Dan,
>>
>> Thanks - you're probably right - just my intuition said to me that rather 
>> than calculating that the 13th root of 
>> 4021503534212915433093809093996098953996019232
>> is 3221.2904208350265
>> there must be a quicker way of finding out its between 3221 and 3222
>>
>> but perhaps not.
> 
> I don't think you'll find anything much quicker than n**(1./13)
> (though I hope
> that if you're doing this millions of time then you're precomputing
> the 1./13
> rather than redoing the division every single time.
> 
Compared with the computation involved in the power computation I think
you'll find this makes a negligible difference in timing. But that's
just mu gut instinct, and we both know that a benchmark is the only way
to be certain, right? It just seems like a possibly premature
optimization to me. [sigh. I had to start this, didn't i?]

>>> t1 = timeit.Timer("x =
4021503534212915433093809093996098953996019232**(1.0/13)")
>>> t2 = timeit.Timer("x =
4021503534212915433093809093996098953996019232**power", "power=1.0/13")
>>> t1.timeit()
1.486610351562
>>> t2.timeit()
1.378485015869
>>>

Hmm, well, I suppose an 9% speed gain might be worth it.


> What happens behind the scenes here is that your integer is
> immediately
> converted to a float, then the system math library is used for the
> power operation.  The integer -> float conversion is probably quite
> significant, timewise.
> 
I bow to your superior intuition!

> I'd also be a bit worried about accuracy.   Is it important to you
> that the
> integer part of the result is *exactly* right, or is it okay if
> (n**13)**(1./13) sometimes comes out as slightly less than n, or if
> (n**13-1)**(1./13) sometimes comes out as n?
> 
Much more significant points, given the limited precision of the doubles
Python will be using. Could gmpy do this better, I wonder?

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Empty string is False right?

2009-01-31 Thread D'Arcy J.M. Cain
On Sat, 31 Jan 2009 12:16:19 +
AJ Ostergaard  wrote:
>  >>> '' and True
> ''
> 
> Surely that should be False?!?

Why?  The first value evaluates to False in a boolean context and
thus is returned in the above statement due to short circuit
evaluation but is not itself False.  You wouldn't expect the following
statement to be True.

>>> '' is False
False

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Empty string is False right?

2009-01-31 Thread Steve Holden
AJ Ostergaard wrote:
> I'm not suggesting it's not operating as advertised - I'm suggesting the
> 'advertising' is slightly sguiffy if you catch my drift. I guess it's
> just me that finds it slightly counter intuitive. Surely intuitively the
> expression is "and" and therefore should always return a boolean?
> 
> I'll shut up now. ;)
> 
You might think so, and it wouldn't be an entirely unreasonable thought,
but in practice it makes a lot of sense to retain the original value
where possible.

The fact is that any left-hand operand that evaluates to false in a
Boolean context can be used as it stands rather than being converted to
Boolean first. So the conversion is essentially useless processing.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: glob.fnmatch (was "search speed")

2009-01-31 Thread Tim Chase

rdmur...@bitdance.com wrote:

Quoth Tim Chase :
PS:  as an aside, how do I import just the fnmatch function?  I 
tried both of the following and neither worked:


   from glob.fnmatch import fnmatch
   from glob import fnmatch.fnmatch

I finally resorted to the contortion coded below in favor of
   import glob
   fnmatch = glob.fnmatch.fnmatch


What you want is:

from fnmatch import fnmatch


Oh, that's head-smackingly obvious now...thanks!

My thought process usually goes something like

"""
I want to do some file-name globbing

there's a glob module that looks like a good place to start

hmm, dir(glob) tells me there's a fnmatch thing that looks like 
what I want according to help(glob.fnmatch)


oh, the fnmatch() function is inside this glob.fnmatch thing

so, I want glob.fnmatch.fnmatch()
"""

It never occurred to me that fnmatch was its own importable 
module.  


-tkc



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


Re: Where to host a (Python) project?

2009-01-31 Thread Martin
2009/1/31 andrew cooke :
> On Jan 31, 9:59 am, Martin  wrote:
>> There's tigris.org, savannah (savannah.gnu.org, nongnu.org),
>> launchpad. All of them are fine to some extent, you might want to read
>> up on PyMotW about how Doug Hellmann decided where to host his stuff.
>
> all i can find is that he is writing his own!
> http://blog.doughellmann.com/search/label/codehosting
> (his reqs are quite different to mine - I am looking for an external
> provider because I do not want to host dynamic pages myself).

Darn, my bad. I just remembered that something happened in terms of
hosting on his site, I thought he had decided on this:

http://blog.doughellmann.com/2008/12/moving-pymotw-to-public-repository.html
(seems he didn't have any time...)

anyway, tigris, nongnu and savannah are hopefully at least useable
information :)

/Martin



-- 
http://soup.alt.delete.co.at
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe + SQLite problem

2009-01-31 Thread Armin

Gabriel Genellina wrote:

En Fri, 30 Jan 2009 09:50:08 -0200, Armin  escribió:




Right at the end: "To install data files directly in the target 
directory, an empty string should be given as the directory."


setup(...,
  data_files=[
   ('', ['list/of/file/names', 
'perhaps/including/source/directory']),

   ]
 )


Yes ... so far the theory :)

As posted before ... set's my script (python 2.3):

from distutils.core import setup
import py2exe

setup(windows=['dpconf.py'],
data_files=[ "", ["proj_db","gsd_db","dachs2.xbm"]]
)

When I create the distribution I got the following err msg:

*** copy data files ***
warning: install_data: setup script did not provide a directory for '' 
-- installing right in 'C:\pyDPCONF.2.3-dev\dist'

error: can't copy '': doesn't exist or not a regular file

Looks a little bit inconsistent ?

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


Re: nth root

2009-01-31 Thread Mark Dickinson
On Jan 31, 1:23 pm, Steve Holden  wrote:
> [Mark]
> > power operation.  The integer -> float conversion is probably quite
> > significant, timewise.
>
> I bow to your superior intuition!

Here's another timing that shows the significance of the int -> float
conversion: (non-debug build of the trunk)

>>> t1 = timeit.Timer("x = n**power", "n = 
>>> 4021503534212915433093809093996098953996019232; power = 1./13")
>>> t2 = timeit.Timer("x = n**power", "n = 
>>> 4021503534212915433093809093996098953996019232.; power = 1./13")
>>> t1.timeit()
0.34778499603271484
>>> t2.timeit()
0.26025009155273438

I've got a patch posted to the tracker somewhere that improves
the accuracy of long->float conversions, while also speeding them
up a tiny bit (but not a lot...).

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


Re: nth root

2009-01-31 Thread Mark Dickinson
On Jan 31, 1:23 pm, Steve Holden  wrote:
> Much more significant points, given the limited precision of the doubles
> Python will be using. Could gmpy do this better, I wonder?

Almost certainly, if exact results are wanted!  At least, GMP has
an mpz_root function; I don't know offhand whether gmpy makes it
accessible from Python.

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


Re: Where to host a (Python) project?

2009-01-31 Thread Michele Simionato
On Jan 31, 12:46 pm, andrew cooke  wrote:
> Any recommendations?

Google Code seems fine.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Empty string is False right?

2009-01-31 Thread Grant Edwards
On 2009-01-31, Vlastimil Brom  wrote:
> 2009/1/31 AJ Ostergaard :
>> Hi Ralf,
>>
>> Thanks for that but why:
>>
> '' and True
>> ''
>>
>> Surely that should be False?!?
>>
>> Regards,
>> AJ
>>
>>
> see the docs:
> http://docs.python.org/reference/expressions.html#boolean-operations
>
> "The expression x and y first evaluates x; if x is false,

But that doesn't mean "x is False" in the strict Python
expression sense of the phrase.  It means if bool(x) is False
(or something reasonably close to that).

> its value is returned; otherwise, y is evaluated and the
> resulting value is returned."

-- 
Grant

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


Re: Where to host a (Python) project?

2009-01-31 Thread eliben


andrew cooke wrote:
> Hi,
>
> I have a new project, that I just released in beta (http://
> www.acooke.org/lepl - a recursive decent parser with full
> backtracking).  At the moment I am using pypi and setuptools for
> distribution (it's a pure python package) and I am happy with hosting
> static web pages (the manual and api doc linked to above) on my own
> site (I did try the packages.python.org web pages, but it seemed
> pointless duplicating my own).
>
> However, i am thinking I could really do with:
> - a mailing list
> - simple bug tracking
> - subversion

code.google.com provides all of these in a free and convenient manner.
Recommended.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where to host a (Python) project?

2009-01-31 Thread andrew cooke
On Jan 31, 11:22 am, eliben  wrote:
> code.google.com provides all of these in a free and convenient manner.
> Recommended.

unfortunately google don't seem that reliable ;o)  (have you tried a
google search today?)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why do operators and methods of built-in types differ

2009-01-31 Thread Christian Heimes
andrew cooke schrieb:
>> Just a correction: according to the doc, NotImplemented is not an
>> error, but a returned value.
> 
> curious, so it is.  i wonder why there is both a special return value
> (NotIMplemented) and a related exception (NotImplementedError).  seems
> very odd to have a value...

They are different and unrelated things. The NotImplentedError is an
exception class while NotImplemented is a singleton like None. When a
method like __add__ can't handle the other object it returns
NotImplemented. It doesn't raise a NotImplementedError. The
NotImplemented singleton is an optimization. The interpreter just has to
compare the memory address of the returned value with the address of
NotImplemented. That's a super fast op in C.

Christian

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


Re: py2exe + SQLite problem

2009-01-31 Thread Thomas Heller
Armin schrieb:
> As posted before ... set's my script (python 2.3):
> 
> from distutils.core import setup
> import py2exe
> 
> setup(windows=['dpconf.py'],
>  data_files=[ "", ["proj_db","gsd_db","dachs2.xbm"]]
>  )
> 
> When I create the distribution I got the following err msg:
> 
> *** copy data files ***
> warning: install_data: setup script did not provide a directory for '' 
> -- installing right in 'C:\pyDPCONF.2.3-dev\dist'
> error: can't copy '': doesn't exist or not a regular file

>From the Python docs (chapter 'writing the setup script):

"""
data_files specifies a sequence of (directory, files) pairs in the following 
way:

setup(...,
  data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
  ('config', ['cfg/data.cfg']),
  ('/etc/init.d', ['init-script'])]
 )
"""

So, it looks like you should use

> setup(windows=['dpconf.py'],
>  data_files=[("", ["proj_db","gsd_db","dachs2.xbm"])]
   ^ ^
>  )

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


Re: py2exe + SQLite problem

2009-01-31 Thread Gabriel Genellina

En Sat, 31 Jan 2009 11:51:16 -0200, Armin  escribió:

Gabriel Genellina wrote:

En Fri, 30 Jan 2009 09:50:08 -0200, Armin  escribió:


 Right at the end: "To install data files directly in the target  
directory, an empty string should be given as the directory."

 setup(...,
  data_files=[
   ('', ['list/of/file/names',  
'perhaps/including/source/directory']),

   ]
 )


Yes ... so far the theory :)

As posted before ... set's my script (python 2.3):


You didn't tell us that you were using version 2.3 -- it's important, as  
the current stable releases are 2.6 and 3.0. Anyway, this should work in  
2.3 too.



from distutils.core import setup
import py2exe

setup(windows=['dpconf.py'],
 data_files=[ "", ["proj_db","gsd_db","dachs2.xbm"]]
 )



Comparing my example and yours, you lack a parenthesis level:

setup(windows=['dpconf.py'],
  data_files=[("", ["proj_db","gsd_db","dachs2.xbm"])]
  )


When I create the distribution I got the following err msg:

*** copy data files ***
warning: install_data: setup script did not provide a directory for ''  
-- installing right in 'C:\pyDPCONF.2.3-dev\dist'

error: can't copy '': doesn't exist or not a regular file

Looks a little bit inconsistent ?


O thou of little faith, try again...

--
Gabriel Genellina

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


Re: Why do operators and methods of built-in types differ

2009-01-31 Thread Gabriel Genellina
En Sat, 31 Jan 2009 11:03:13 -0200, andrew cooke   
escribió:





Just a correction: according to the doc, NotImplemented is not an
error, but a returned value.


curious, so it is.  i wonder why there is both a special return value
(NotIMplemented) and a related exception (NotImplementedError).  seems
very odd to have a value...


I consider it an optimization. Raising an exception is more costly than  
returning a value, and this failure is likely to happen often (not all  
types define all possible operators). AFAIK this is only recognized by the  
binary operators (__add__, __iadd__, etc) and rich comparisons (__eq__,  
__lt__, etc.)


--
Gabriel Genellina

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


Re: Why GIL? (was Re: what's the point of rpython?)

2009-01-31 Thread Aahz
In article <7xr62ufv1c@ruckus.brouhaha.com>,
Paul Rubin   wrote:
>a...@pythoncraft.com (Aahz) writes:
>>
>> CPython's "primitive" storage management has a lot to do with the
>> simplicity of interfacing CPython with external libraries.  Any solution
>> that proposes to get rid of the GIL needs to address that.
>
>This, I don't understand.  Other languages like Lisp and Java and
>Haskell have foreign function interfaces that easier to program than
>Python's, -and- they don't use reference counts.  There's usually some
>primitive to protect objects from garbage collection while the foreign
>function is using them, etc.  The Java Native Interface (JNI) and the
>Haskell FFI are pretty well documented.  The Emacs Lisp system is not
>too hard to figure out from examining the source code, etc.

This is the first time I've heard about Java being easier to interface
than Python.  I don't work at that level myself, so I rely on the
informed opinions of other people; can you provide a summary of what
makes those FFIs easier than Python?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter w.pack()?

2009-01-31 Thread W. eWatson

Steve Holden wrote:

W. eWatson wrote:

r wrote:

On Jan 28, 10:12 pm, "W. eWatson"  wrote:

Where in the world is a description of pack() for Tkinter widgets? Is it
some sort of general method for all widgets? I'm looking in a few
docs that
use it without ever saying where it is described. For one,
. In the NM Tech pdf on
Tkinter,
it's not found anywhere. I see Universal methods for widgets, but no
mention
of pack(). package, packed, but no pack.

did you try here :)
http://effbot.org/tkinterbook/pack.htm

Thanks. I have the site bookmarked, but it's hard to search. I posted a
comment to them that they should have it in pdf form.


http://letmegooglethatforyou.com/?q=site%3Aeffbot.org%2Ftkinterbook+pack

regards
 Steve
Well, that's an interesting "link". Another side of Google facilities? Maybe 
you're using Snagit or its brethern? However, I'm interested in searching a 
pdf, which, of course, doesn't yet exist.


--
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: 

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


Re: Tkinter w.pack()?

2009-01-31 Thread W. eWatson

Gabriel Genellina wrote:
En Thu, 29 Jan 2009 14:55:13 -0200, W. eWatson  
escribió:

Gabriel Genellina wrote:
En Thu, 29 Jan 2009 02:57:04 -0200, W. eWatson 
 escribió:



The word pack doesn't exist on the NMT pdf. Maybe there's a newer one?

 There is a PDF version of "An Introduction to Tkinter" here:
http://www.pythonware.com/library/

Thanks. I have it but it's an odd one to search on "pack(". There may 
be over 100 reference to pack(. It's probably explained there 
somewhere, but how many times do I want to press the search key? I 
have it printed out too. I guess I need to eyeball it. It's probably 
faster. Maybe find the section (geometry?) where it and others like it 
are found. There is an index, but it's a pitiful one page.


Uh? The very first occurence of "pack" is in the Table of Contents, "The 
pack geometry manager". (You may want to improve your search skills :) )


Yes, that's correct, but I was looking for "pack(". It all depends on one's 
perspective on how to search. I'll not labor the point.


--
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: 

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


Re: glob.fnmatch (was "search speed")

2009-01-31 Thread rdmurray
Quoth Tim Chase :
> rdmur...@bitdance.com wrote:
> > What you want is:
> > 
> > from fnmatch import fnmatch
> 
> Oh, that's head-smackingly obvious now...thanks!
> 
> My thought process usually goes something like
> 
> """
> I want to do some file-name globbing
> 
> there's a glob module that looks like a good place to start
> 
> hmm, dir(glob) tells me there's a fnmatch thing that looks like 
> what I want according to help(glob.fnmatch)
> 
> oh, the fnmatch() function is inside this glob.fnmatch thing
> 
> so, I want glob.fnmatch.fnmatch()
> """
> 
> It never occurred to me that fnmatch was its own importable 
> module.  

I did a help(glob), saw that fnmatch wasn't in there, did a dir(glob),
saw fnmatch and was puzzled, so I looked up the glob doc page on
docs.python.org for glob.  There was a cross reference at the bottom
of the page to fnmatch, and it was only at that point that I went:
"oh, duh" :)

--RDM

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


Re: Empty string is False right?

2009-01-31 Thread Diez B. Roggisch

AJ Ostergaard schrieb:

Hi Ralf,

Thanks for that but why:

 >>> '' and True
''

Surely that should be False?!?


No. Please read the section in the language reference about the and/or 
operators.


"and" will return the first false value, or the right side. Thus

'' and True -> ''

True and '' -> ''

'a' and True -> True

True and 'a' -> 'a'

"or" does the same, obviously with the or-semantics:


'' or False -> False
False or '' -> ''
'' or True -> True
True or '' -> True
'a' or False -> 'a'
False or 'a' -> 'a'

Diez

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


fastest way to detect a user type

2009-01-31 Thread Robin Becker
Whilst considering a port of old code to python 3 I see that in several 
places we are using type comparisons to control processing of user 
instances (as opposed to instances of built in types eg float, int, str)


I find that the obvious alternatives are not as fast as the current 
code; func0 below. On my machine isinstance seems slower than type for 
some reason. My 2.6 timings are


C:\Tmp>\Python\lib\timeit.py -s"import t;v=t.X()" t.func0(v)
100 loops, best of 3: 0.348 usec per loop

C:\Tmp>\Python\lib\timeit.py -s"import t;v=t.X()" t.func1(v)
100 loops, best of 3: 0.747 usec per loop

C:\Tmp>\Python\lib\timeit.py -s"import t;v=t.X()" t.func2(v)
100 loops, best of 3: 0.378 usec per loop

C:\Tmp>\Python\lib\timeit.py -s"import t;v=t.X()" t.func3(v)
100 loops, best of 3: 0.33 usec per loop

C:\Tmp>\Python\lib\timeit.py -s"import t;v=t.X()" t.func0(1)
100 loops, best of 3: 0.477 usec per loop

C:\Tmp>\Python\lib\timeit.py -s"import t;v=t.X()" t.func1(1)
100 loops, best of 3: 1.14 usec per loop

C:\Tmp>\Python\lib\timeit.py -s"import t;v=t.X()" t.func2(1)
100 loops, best of 3: 1.16 usec per loop

C:\Tmp>\Python\lib\timeit.py -s"import t;v=t.X()" t.func3(1)
100 loops, best of 3: 1.14 usec per loop

so func 3 seems to be the fastest option for the case when the first 
test matches, but is poor when it doesn't. Can anyone suggest a better 
way to determine if an object is a user instance?


##
from types import InstanceType
class X:
__X__=True

class V(X):
pass

def func0(ob):
t=type(ob)
if t is InstanceType:
pass
elif t in (float, int):
pass
else:
pass

def func1(ob):
if isinstance(ob,X):
pass
elif type(ob) in (float, int):
pass
else:
pass

def func2(ob):
if getattr(ob,'__X__',False):
pass
elif type(ob) in (float, int):
pass
else:
pass

def func3(ob):
if hasattr(ob,'__X__'):
pass
elif type(ob) in (float, int):
pass
else:
pass
##

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


Re: nth root

2009-01-31 Thread Dan Goodman

Mark Dickinson wrote:

I'd also be a bit worried about accuracy.   Is it important to you
that the
integer part of the result is *exactly* right, or is it okay if
(n**13)**(1./13) sometimes comes out as slightly less than n, or if
(n**13-1)**(1./13) sometimes comes out as n?


I don't think accuracy is too big a problem here actually (at least for 
13th roots). I just tested it with several hundred thousand random 100 
digit numbers and it never made a mistake. The precision of double ought 
to easily guarantee a correct result. If you let x=int(1e100**(1./13)) 
then ((x+1)**13-x**13)/x**13=2.6e-7 so you only need around the first 8 
or 9 digits of the 100 digit number to compute the 13th root exactly 
(well within the accuracy of a double).


OTOH, suppose you were doing cube roots instead then you would need the 
first 35 digits of the 100 digit number and this is more accurate than a 
double. So for example int(1e100**(1./3)) is a long way from being the 
integer part of the true cube root (it's between 10**18 and 10**19 away).


Dan

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


Re: nth root

2009-01-31 Thread Mensanator
On Jan 31, 8:05 am, Mark Dickinson  wrote:
> On Jan 31, 1:23 pm, Steve Holden  wrote:
>
> > Much more significant points, given the limited precision of the doubles
> > Python will be using. Could gmpy do this better, I wonder?
>
> Almost certainly, if exact results are wanted!  At least, GMP has
> an mpz_root function; I don't know offhand whether gmpy makes it
> accessible from Python.
>
> Mark

What am I doing wrong here?

IDLE 2.6b1
>>> import timeit
>>> from gmpy import root
>>> root(4021503534212915433093809093996098953996019232,13)
(mpz(3221), 0)
>>> t1 = timeit.Timer("x = root(a,r)", "a = 
>>> 4021503534212915433093809093996098953996019232; r = 13")
>>> t1.timeit()

Traceback (most recent call last):
  File "", line 1, in 
t1.timeit()
  File "C:\Python26\lib\timeit.py", line 193, in timeit
timing = self.inner(it, self.timer)
  File "", line 6, in inner
NameError: global name 'root' is not defined
--
http://mail.python.org/mailman/listinfo/python-list


Re: Empty string is False right?

2009-01-31 Thread Stephen Hansen
On Sat, Jan 31, 2009 at 4:36 AM, AJ Ostergaard  wrote:I'm not suggesting it's not operating as advertised - I'm suggesting the 'advertising' is slightly sguiffy if you catch my drift. I guess it's just me that finds it slightly counter intuitive. Surely intuitively the _expression_ is "and" and therefore should always return a boolean?Boolean operators just aren't guaranteed to return a boolean /type/ -- but instead a boolean /_expression_/, that if evaluated is true or false. The difference is important -- and although it might be partly for historical reasons (after all, there was no boolean /type/ until Python 2.3. That's not really all that long ago), it also has quite a few useful properties that aren't necessecarily immediately obvious but are used in a variety of places.A common one is the and/or "ternary" _expression_ that pre-dates the addition of conditional expressions to Python 2.5:>>> test = True>>> test and "Apples" or "Oranges"'Apples'>>> test = False>>> test and "Apples" or "Oranges"'Oranges'In Python 2.5., that can be rewritten to:>>> test = True>>> "Apples" if test else "Oranges"'Apples'>>> test = False>>> "Apples" if test else "Oranges"'Oranges'Its part of why you aren't supposed to compare boolean results/tests/expressions against True or False directly usually (besides /just/ style). You do:if _expression_:   print "Was true!"Not:if _expression_ is True:    print "Was true!"--Stephen



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


Re: Where to host a (Python) project?

2009-01-31 Thread ajaksu
On Jan 31, 1:03 pm, andrew cooke  wrote:
> On Jan 31, 11:22 am, eliben  wrote:
>
> > code.google.com provides all of these in a free and convenient manner.
> > Recommended.
>
> unfortunately google don't seem that reliable ;o)  (have you tried a
> google search today?)

You can mirror at LP, bitbucket, github, etc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-31 Thread thmpsn . m . k
On Jan 30, 12:15 am, Chris Rebert  wrote:
> - Python supports encapsulation. Prefixing an attribute/method with an
> underscore indicates that other programmers should treat it as
> 'private'. However, unlike B&D languages, Python itself does nothing
> to enforce this privacy, leaving it instead to the good judgement of
> the programmer, under the philosophy that "We're all consenting adults
> here".

How do you know? (I know I'm not.)

Seriously, though, the lack of private members does allow for ugly
hacks in user code, and you know there are always ugly hackers.

> This allows people to meddle with internals, at their own risk,
> if it ends up being absolutely necessary.

If it ends up being necessary, the class's design is flawed. (Though
in this case, the flaw is easily solved by simply providing a getter.)

> The enforcement point is
> largely academic anyway, as most languages' reflection APIs let you
> poke at ostensibly "private" things.

If you're talking about getters, then note that this doesn't let you
modify the member (unless there's a corresponding setter).

In the absence of private/protected, Python should at least provide
something similar to C++'s 'const' or Java's 'final'. (Similar, not
equivalent, because then the object itself wouldn't be able to
manipulate its own members!)

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


Python Doc 2.6 vs 2.5--A Matter of Format?

2009-01-31 Thread W. eWatson
I see  for 2.5 and  
for 2.6. I'm guessing these two pages differ somewhat in formats simply 
because someone decided to do so, and not that I'm in the wrong place for 
each of the two versions, correct? For example, somewhere down in the 2.5, I 
should find the 2.6 equivalent of ?

--
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: 

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


Re: nth root

2009-01-31 Thread Mensanator
On Jan 31, 10:53 am, Mensanator  wrote:
> On Jan 31, 8:05 am, Mark Dickinson  wrote:
>
> > On Jan 31, 1:23 pm, Steve Holden  wrote:
>
> > > Much more significant points, given the limited precision of the doubles
> > > Python will be using. Could gmpy do this better, I wonder?
>
> > Almost certainly, if exact results are wanted!  At least, GMP has
> > an mpz_root function; I don't know offhand whether gmpy makes it
> > accessible from Python.
>
> > Mark
>
> What am I doing wrong here?
>
> IDLE 2.6b1
>
> >>> import timeit
> >>> from gmpy import root
> >>> root(4021503534212915433093809093996098953996019232,13)
> (mpz(3221), 0)
> >>> t1 = timeit.Timer("x = root(a,r)", "a = 
> >>> 4021503534212915433093809093996098953996019232; r = 13")
> >>> t1.timeit()
>
> Traceback (most recent call last):
>   File "", line 1, in 
>     t1.timeit()
>   File "C:\Python26\lib\timeit.py", line 193, in timeit
>     timing = self.inner(it, self.timer)
>   File "", line 6, in inner
> NameError: global name 'root' is not defined

Never mind, I figured it out.

>>> import gmpy
>>> a=gmpy.mpz(4021503534212915433093809093996098953996019232)
>>> r=13
>>> t1 = timeit.Timer("x = root(a,r)", "from gmpy import root; from __main__ 
>>> import a,r")
>>> t1.timeit()
4.7018698921850728

For comparison:

>>> t2 = timeit.Timer("x = n**power", "n = 
>>> 4021503534212915433093809093996098953996019232.; power = 1./13")
>>> t2.timeit()
0.43993394115364026
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-31 Thread Stephen Hansen
On Sat, Jan 31, 2009 at 9:08 AM,   wrote:On Jan 30, 12:15 am, Chris Rebert  wrote:
> - Python supports encapsulation. Prefixing an attribute/method with an
> underscore indicates that other programmers should treat it as
> 'private'. However, unlike B&D languages, Python itself does nothing
> to enforce this privacy, leaving it instead to the good judgement of
> the programmer, under the philosophy that "We're all consenting adults
> here".

How do you know? (I know I'm not.)

Seriously, though, the lack of private members does allow for ugly
hacks in user code, and you know there are always ugly hackers.
So what, though?If you're a application developer, writing your own code: just don't do it.You've now achieved enforced encapsulation! Why does the languageneed to check that?If you're the user of a library and you need access to a private memberof that library: again, just don't do it! Write a patch and maintain aprivate fork to expose the member function, and submit it to the developerand hope it gets included so you don't have to maintain the private fork.For those people who need access to that internal Right Now and don'twant to wait for the developer to expose it, because its important to themwhy should the language forbid it? Sure, its an ugly hack. But so what? They're doing it, at the risk of future breakage if anything changes inthat undocumented internal detail, because they need to. There aresituations where maintaining a private fork to expose something in alibrary is a far greater burden and not worth it.If you're the writer of a library, why do you even care if the people whouse it access an undocumented internal? If anything breaks its notyour problem.If you're in some corporate environment which has a 'no fiddling withthe privates of another teams modules' -- why do you need the languageto enforce that restriction? If your employees aren't following the codingstandards of your own organization, that's a problem. Surely it'd come upvery quickly with even the most cursory of reviews, after all "obj._variable"is really obviously not "self._variable" and so pretty obviously accessingsomeone elses private state.If you're in an open source environment and are worried about qualityof code from lots of contributors who aren't being paid: again, reviewsshould be happening /anyways/.In the end, why bother? If you believe in absolute encapsulation itsextremely easy for you to get it in Python, today... don't touch someoneelses privates.  
> This allows people to meddle with internals, at their own risk,
> if it ends up being absolutely necessary.

If it ends up being necessary, the class's design is flawed. (Though
in this case, the flaw is easily solved by simply providing a getter.)Sure, the design is flawed. Doesn't change the fact that you need to accessthat internal state. "Providing a getter" is not necessarily simple: what ifits someone elses code? At the very least you have to maintain a privatefork then /or/ wait until they get around to fixing the design. Sometimes that's no big deal. Sometimes it is. 
In the absence of private/protected, Python should at least provide
something similar to C++'s 'const' or Java's 'final'. (Similar, not
equivalent, because then the object itself wouldn't be able to
manipulate its own members!)I find marking my constants as SOME_CONSTANT instead of some_constantto be more then sufficient usually. In the case where I do want to let someoneread a piece of data and not write it, I find a getter accessing a private membervariable without a corresponding setter perfectly fine.If the users of the code choose to dig inside my class and fiddle with thatprivate member -- woe on them! I wash my hands of any trouble theyhave.--Stephen 



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


Re: nth root

2009-01-31 Thread Mark Dickinson
On Jan 31, 4:48 pm, Dan Goodman  wrote:
> I don't think accuracy is too big a problem here actually (at least for
> 13th roots). I just tested it with several hundred thousand random 100
> digit numbers and it never made a mistake.

Well, random numbers is one thing.  But how about the following:

>>> n = 12345**13
>>> n
154662214940914131102165197707101295849230845947265625L
>>> int(n ** (1./13))  # should be 12345; okay
12345
>>> int((n-1) ** (1./13))  # should be 12344; oops!
12345

Mark

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


Re: persistent TCP connection in python using socketserver

2009-01-31 Thread markobrien85
On Jan 30, 5:54 am, Jean-Paul Calderone  wrote:
> On Thu, 29 Jan 2009 08:38:43 -0800 (PST), markobrie...@gmail.com wrote:
> >G'day
>
> >I'm currentlyusingsocketserverto build a simple XMLSocket (an XML
> >based protocol used for communication between flash and the outside
> >world) server. I've got flash establishing aconnection, sending a
> >request and mypythonserver responding. However at this point
> >socketserverterminates theconnection. Which is bad, since i need a
> >persistentconnectionso i can push data from the server to the client
> >without the overhead of polling.
>
> If you don't want theconnectionto close, then don't let the request
> complete.  SocketServerimplements logic for single request/response
> perconnection.  You can change this by making your requests take a
> really long time (until you're done with theconnection) or you can
> override the behavior which closes theconnectionafter a response.
>
> Or you could use the socket module, on which theSocketServermodule is
> based.  Or you could use Twisted, another higher-level package built on
> the socket module (mostly).  Actually, I recommend Twisted, since it will
> mostly isolate you from boring low-level details and let you implement
> whatever high-level behavior you're after (I know that a bunch of people
> have used it to communicate with Flash, for example).
>
> Jean-Paul

Cheers mate I had a look into twisted but was put off by the FAQ
stating 1.0+ modules may or may not be stable, and only the 'core' is.
I don't wanna be messing around with a potentially buggy server, so im
gonna roll my own using the sockets module.


Thanks for your help !
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Doc 2.6 vs 2.5--A Matter of Format?

2009-01-31 Thread Stephen Hansen
On Sat, Jan 31, 2009 at 9:14 AM, W. eWatson  wrote:I see  for 2.5 and  for 2.6. I'm guessing these two pages differ somewhat in formats simply because someone decided to do so, and not that I'm in the wrong place for each of the two versions, correct? For example, somewhere down in the 2.5, I should find the 2.6 equivalent of ?The entire documentation system for Python was changed in 2.6/3.0; it now uses ReST instead of LaTeX as its source and has a different toolchain(Sphinx) to build the HTML docs from the source material, do all the linking/indexing, and all of that jazz. Its mostly but not entirely the same: there's some structural changes that go beyond format, but all the content is there, I believe. I believe the "genindex" for 2.5 that you're looking for is at http://www.python.org/doc/2.5/lib/genindex.html ... you get it by hitting 'I' on the upper right hand corner of the page after you go into an actual documentaiton catalog. (E.g., "Library Reference" as opposed to that main index page)--S



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


Re: nth root

2009-01-31 Thread Dan Goodman

Mark Dickinson wrote:

Well, random numbers is one thing.  But how about the following:


n = 12345**13
n

154662214940914131102165197707101295849230845947265625L

int(n ** (1./13))  # should be 12345; okay

12345

int((n-1) ** (1./13))  # should be 12344; oops!

12345


Good point! Oops indeed. :-)

Dan

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


Re: is python Object oriented??

2009-01-31 Thread thmpsn . m . k
On Jan 30, 2:32 pm, Michael Torrie  wrote:
> Veerendra Ganiger wrote:
> > Python is not purely object oriented programming, because we can write
> > functions without any class.
> > You are right, predefined class attributes are available when we write or
> > execute a piece of python code without defining class, that means it's just
> > using objects for it's purpose. It does not mean its purely object oriented.
>
> To be clear, python does not force you to lay out your code according to
> some strict object-oriented paradigm.  But Python itself is still purely
> object-oriented, as is your script when parsed.
>
> This function without a class that you mentioned, is in fact an object
> with attributes.  You can pass a function around just like any other
> object.  Even calling a function is invoked like so:
>
> myfunc.__call__(params)
>
> So necessitating that code be inside a class has nothing to do with
> object-oriented programming.  Let's not forget that classes are
> themselves objects (metaobjects in smalltalk parlance if I recall
> correctly).
>
> Now python does not have any way besides lambda expressions of creating
> unbound function objects, but in practice this doesn't matter as I can
> rebind names freely.  I can still do:
>
> a=myfunc
> myfunc=some other expression or object
>
> > It all depends on implementation, I think even we can make "C" object
> > oriented with proper implementation.
>
> Indeed, any code based on gobject libraries can be object-oriented in
> design and function.

But it's only a faking, and things such as inheritance and
polymorphism are implemented clumsily (actually I'm not even sure
about polymorphism). And of course, there are still no private
members.

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


Re: Why do operators and methods of built-in types differ

2009-01-31 Thread Scott David Daniels

Csaba Hoch wrote:

if I write the following:
   >>> 1+1
   2
it seems to be exactly equivalent to this:
   >>> (1).__add__(1)
   2 
However, if I write invalid code and try to add a list to an int, the

errors will be different: 

As has been explained, binary operators are trickier than the above
seems to show.  Here is how to get the full behavior:
>>> import operator
>>> operator.add(1,[])
Traceback (most recent call last):
  File "", line 1, in 
operator.add(1,[])
TypeError: unsupported operand type(s) for +: 'int' and 'list'


--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Empty string is False right?

2009-01-31 Thread Scott David Daniels

Steve Holden wrote:

AJ Ostergaard wrote:

I'm not suggesting it's not operating as advertised - I'm suggesting the
'advertising' is slightly sguiffy if you catch my drift. I guess it's
just me that finds it slightly counter intuitive. Surely intuitively the
expression is "and" and therefore should always return a boolean?

...

You might think so, and it wouldn't be an entirely unreasonable thought,
but in practice it makes a lot of sense to retain the original value
where possible.


For example:
print name_from_form or default_name
or:
main(sys.arg[1:] or ['default', 'args'])

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Doc 2.6 vs 2.5--A Matter of Format?

2009-01-31 Thread Martin v. Löwis
> I see  for 2.5 and
>  for 2.6. I'm guessing these two pages differ
> somewhat in formats simply because someone decided to do so, and not
> that I'm in the wrong place for each of the two versions, correct?

Correct. The documentation format has significantly changed.

> For
> example, somewhere down in the 2.5, I should find the 2.6 equivalent of
> ?

Not necessarily. The change in format also means a change in indices;
the formats differ in what indices precisely are created, and what
precisely they contain. Try

http://www.python.org/doc/2.5/lib/genindex.html

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


Re: nth root

2009-01-31 Thread ajaksu
On Jan 31, 12:03 pm, Mark Dickinson  wrote:
[...]
> t1 = timeit.Timer("x = n**power", "n = 
> 4021503534212915433093809093996098953996019232; power = 1./13")
> t2 = timeit.Timer("x = n**power", "n = 
> 4021503534212915433093809093996098953996019232.; power = 1./13")

And by using a float literal instead of "float
(402150353421291543309...)", (BTW, here -^), it not only is faster but
also a great way make some innocent bystander waste his eyesight
trying to figure out the magic trick :D
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-31 Thread Tim Rowe
2009/1/30 Scott David Daniels :

> Be careful with your assertion that a regex is faster, it is certainly
> not always true.

I was careful *not* to assert that a regex would be faster, merely
that it was *likely* to be in this case.


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


Re: Python-list Digest, Vol 64, Issue 697

2009-01-31 Thread AJ Ostergaard

AJ Ostergaard wrote:
I'm not suggesting it's not operating as advertised - I'm  
suggesting the

'advertising' is slightly sguiffy if you catch my drift. I guess it's
just me that finds it slightly counter intuitive. Surely  
intuitively the

expression is "and" and therefore should always return a boolean?

You might think so, and it wouldn't be an entirely unreasonable  
thought,

but in practice it makes a lot of sense to retain the original value
where possible.

The fact is that any left-hand operand that evaluates to false in a
Boolean context can be used as it stands rather than being converted  
to

Boolean first. So the conversion is essentially useless processing.


That's what I've figured out during the course of the day.

Thanks for listening one and all! :)

Regards,
AJ

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


Searching a file for multiple strings

2009-01-31 Thread gotbyrd
Hello,

I'm fairly new with python and am trying to build a fairly simple
search script.  Ultimately, I'm wanting to search a directory of files
for multiple user inputted keywords.  I've already written a script
that can search for a single string through multiple files, now I just
need to adapt it to multiple strings.

I found a bit of code that's a good start:

import re
test = open('something.txt', 'r').read()

list = ['a', 'b', 'c']

foundit = re.compile('|'.join(re.escape(target) for target in list))
if foundit.findall(test):
print 'yes!'

The only trouble with this is it returns yes! if it finds any of the
search items, and I only want a return when it finds all of them.  Is
there a bit of code that's similar that I can use?

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


Re: len()

2009-01-31 Thread Andreas Waldenburger
On Sat, 31 Jan 2009 13:27:02 -0500 Pat  wrote:

> Tobiah wrote:
> > Just out of curiosity, why was len() made to
> > be it's own function?  I often find myself
> > typing things like my_list.len before I
> > catch myself.
> > 
> > Thanks,
> > 
> > Toby
> 
> I'm surprised that no one responded to that question.
> 
Huh? Gabriel Genellina replied about 46 minutes after it was posted.
Might it be that your newsserver is a bit laggy?

regards
/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Import Replacement

2009-01-31 Thread James Pruitt
Imagine there are two files horse.py and buffalo.py. horse.py is imported by
another file rider.py. Is it possible to make it so that under certain
circumstances possibly based on an environment variable or something similar
that when rider.py imports horse.py, it actually imports buffalo.py sort of
like a behind the scenes replacement so that rider.py needs little,
preferably absolutely no modification? Right now, I am investigating the use
of sys.modules and doing something using sys.modules['horse.py'] =
'buffalo.py'.
--
http://mail.python.org/mailman/listinfo/python-list


Import Replacement

2009-01-31 Thread James Pruitt
Imagine there are two files horse.py and buffalo.py. horse.py is imported by
another file rider.py. Is it possible to make it so that under certain
circumstances possibly based on an environment variable or something similar
that when rider.py imports horse.py, it actually imports buffalo.py sort of
like a behind the scenes replacement so that rider.py needs little,
preferably absolutely no modification? Right now, I am investigating the use
of sys.modules and doing something using sys.modules['horse.py'] =
'buffalo.py'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-31 Thread Andreas Waldenburger
On Sat, 31 Jan 2009 09:11:03 +0100 Laszlo Nagy 
wrote:

> Python is not a pure object oriented language, because it has other 
> programming tools, for example functions.

I'm not sure about the first part of the sentence, but Python's
functions are objects. Check it in the interpreter: attributes,
methods, the whole caboodle.

regards,
/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Searching a file for multiple strings

2009-01-31 Thread Tim Chase

I'm fairly new with python and am trying to build a fairly simple
search script.  Ultimately, I'm wanting to search a directory of files
for multiple user inputted keywords.  I've already written a script
that can search for a single string through multiple files, now I just
need to adapt it to multiple strings.

I found a bit of code that's a good start:

import re
test = open('something.txt', 'r').read()

list = ['a', 'b', 'c']

foundit = re.compile('|'.join(re.escape(target) for target in list))
if foundit.findall(test):
print 'yes!'

The only trouble with this is it returns yes! if it finds any of the
search items, and I only want a return when it finds all of them.  Is
there a bit of code that's similar that I can use?


[insert standard admonition about using "list" as a variable 
name, masking the built-in "list"]
Unless there's a reason to use regular expressions, you could 
simply use


  test = open("something.txt").read()
  items = ['a', 'b', 'c']
  if all(s in test for s in items):
print "Yes!"
  else:
print "Sorry, bub"

This presumes python2.5 in which the "all()" function was added. 
 Otherwise in pre-2.5, you could do


  for s in items:
if s not in test:
  print "Sorry, bub"
  break
  else:
print "Yeparoo"

(note that the "else" goes with the "for", not the "if")

-tkc





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


Re: Where to host a (Python) project?

2009-01-31 Thread Giampaolo Rodola'
On 31 Gen, 12:46, andrew cooke  wrote:
> Hi,
>
> I have a new project, that I just released in beta 
> (http://www.acooke.org/lepl- a recursive decent parser with full
> backtracking).  At the moment I am using pypi and setuptools for
> distribution (it's a pure python package) and I am happy with hosting
> static web pages (the manual and api doc linked to above) on my own
> site (I did try the packages.python.org web pages, but it seemed
> pointless duplicating my own).
>
> However, i am thinking I could really do with:
> - a mailing list
> - simple bug tracking
> - subversion
> and am wondering which is the best (free) provider for these (the code
> is LGPL open source).  I'd prefer a mailing list to something like
> google groups (although I guess it may be possible to configure a
> gateway) and I could open up my personal subversion server, but that
> seems like a lot of work (not really that interested in moving to
> something other than svn).
>
> Any recommendations?
>
> Thanks,
> Andrew

Google Code.


--- Giampaolo
http://code.google.com/p/pyftpdlib
--
http://mail.python.org/mailman/listinfo/python-list


Re: Searching a file for multiple strings (PS)

2009-01-31 Thread Tim Chase

I'm fairly new with python and am trying to build a fairly simple
search script.  Ultimately, I'm wanting to search a directory of files
for multiple user inputted keywords.  I've already written a script
that can search for a single string through multiple files, now I just
need to adapt it to multiple strings.


One more item:  if your files are large, it may be more efficient 
to scan through them incrementally rather than reading the whole 
file into memory, assuming your patterns aren't multi-line (and 
by your escaping example, I suspect they're just single-words):


  items = set(['a', 'b', 'c'])
  for fname in ['file1.txt', 'file2.txt']:
still_to_find = items.copy()
for line in file(fname):
  found = set()
  for item in still_to_find:
if item in line:
  found.add(item)
  still_to_find.difference_update(found)
  if not still_to_find: break
if still_to_find:
  print "%s: Nope" % fname
else:
  print "%s: Yep" % fname

just one more way to do it :)

-tkc



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


Re: nth root

2009-01-31 Thread Mark Dickinson
On Jan 31, 7:04 pm, ajaksu  wrote:
> also a great way make some innocent bystander waste his eyesight
> trying to figure out the magic trick :D

Oh, come on!  At least I put the two lines next to each other!  :-)

Mark

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


Re: SimpleXMLRPCServer question

2009-01-31 Thread flagg
On Jan 30, 8:12 pm, rdmur...@bitdance.com wrote:
> Quoth flagg :
>
> > I am working on a very basic xmlrpc server, which will expose certain
> > functions for administering BIND zone files.  The big problem I am
> > having is parsing the incoming xmlrpc request.  Basically part of the
> > xmlrpc request will help deterime which zone file is edited.    I have
> > been looking at the do_POST() method from SimpleXMLRPCDispatcher and
> > it seems like I could code something which overides that method,
> > however I am new to programming am at a loss, i might even be making
> > this tougher than it needs to be.   Is there a way to parse the
> > incoming xmlrpc request before the function it is calling is executed?
>
> Wouldn't you be overriding '_dispatch' on SimpleXMLRPCServer instead?
>
> It's been a while since I looked at XMLRPC, but why wouldn't you have
> a operation names, with the zone file to operate on as an argument?
> Then you'd just be defining your operations as methods on your
> SimpleXMLRPCServer, and they'd use the argument to determine which file
> to operate on.
>
> If that doesn't make sense, either I've forgotten how XMLRPC works,
> or you should explain your requirements a bit more.
>
> --RDM

Let me see if i can elaborate on the requirements.  I have 20+
different zone files.  I want the xmlrpc server to be able to
determine what zone file to open by looking at the incoming xml
request.  For example one of the functions I have now is to show a DNS
record (I am using dnspython for most of this work)

If i send an xmlrpc request that uses the 'showRecord' function with
params of 'oracle1.foo.bar.com'  I want to parse the "params" piece
and then instruct the xml-rpc server to open foo.bar.com.zone for
reading.  The reason why i was looking at do_Post() and _dispatch was
to attempt to read the incoming params and do exactly that.

Do you think there is an easier way of accomplishing this, than the
way I am going about it?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where to host a (Python) project?

2009-01-31 Thread Andrey Demidov

I use Google Code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Import Replacement

2009-01-31 Thread Gary Herron
James Pruitt wrote:
> Imagine there are two files horse.py and buffalo.py. horse.py is
> imported by another file rider.py. Is it possible to make it so that
> under certain circumstances possibly based on an environment variable
> or something similar that when rider.py imports horse.py, it actually
> imports buffalo.py sort of like a behind the scenes replacement so
> that rider.py needs little, preferably absolutely no modification?
> Right now, I am investigating the use of sys.modules and doing
> something using sys.modules['horse.py'] = 'buffalo.py'.
> 
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

If horse and buffalo have the same interface then try something like this:

if ...:
  import horse as ridable
else:
  import buffalo as ridable
# Now use ridable as any module...

If each defines a class of its own name, but the classes have identical
interfaces, then try

if ...:
  from horse import Horse as Ridable
else:
  from buffalo import Buffalo as Ridable
# Then instantiate
animal = Ridable(...)



Gary Herron

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


Re: is python Object oriented??

2009-01-31 Thread Christian Heimes
thmpsn@gmail.com schrieb:
> But it's only a faking, and things such as inheritance and
> polymorphism are implemented clumsily (actually I'm not even sure
> about polymorphism). And of course, there are still no private
> members.

Do you honestly believe that C++'s private members are really private?
Privateness is only enforced during parsing time. Nobody can stop you
from messing around with header files or memory. You can still access
and modify private members but it's all messy and ugly. Even C# and .NET
don't stop you from doing nasty things from unmananged assemblies.

Seriously, 'private' and 'protected' are merely tools to stop bad
programmers from doing bad stuff. And the serve as documentation, too.

Oh, by the way, the first C++ compilers just converted C++ code to C
code. Such much about "You can't do OOP in C."!

Christian

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


help me python

2009-01-31 Thread aolsuppo
C:\Python26>vnc.py
Traceback (most recent call last):
  File "C:\Python26\vnc.py", line 4, in 
import PyD3DES
ImportError: DLL load failed: The specified module could not be found.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where to host a (Python) project?

2009-01-31 Thread andrew cooke
On Jan 31, 4:50 pm, "Giampaolo Rodola'"  wrote:
> Google Code.
>
> --- Giampaolohttp://code.google.com/p/pyftpdlib

thanks - that's a nice example.  i'm a bit concerned about the whole
google corporation thing, but reading through the ideological check-
sheet at savannah convinced me i wasn't worthy and your project looks
good (i admit i haven't seen that many google projects, but they all
seemed abandoned/bare/hostile).  so i'll follow the majority here and
give google code a go.

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


Re: is python Object oriented??

2009-01-31 Thread Michael Torrie
thmpsn@gmail.com wrote
>> This allows people to meddle with internals, at their own risk,
>> if it ends up being absolutely necessary.
> 
> If it ends up being necessary, the class's design is flawed. (Though
> in this case, the flaw is easily solved by simply providing a getter.)

No the class design is not necessarily flawed.  Sometimes it is
desirable to modify a class's behavior at a lower level.  In Java this
isn't possible directly and so it has led to an entire class of
libraries that provide means of doing this.  For more information, look
up "Aspect-oriented Programming" on wikipedia.  Since most
aspect-oriented programming examples I've seen are in Java I never
understood much about it ("cross-cutting concerns" is a pretty
meaningless explanation) until I realized that metaprogramming in
python, monkey-patching classes, and dynamically adding attributes to an
existing class are all forms of aspect-oriented programming.  And it
turns out to be quite useful for some things.

One area where aspect-oriented programming is useful is in libraries
that add security layers to objects and methods.  Rather than having to
make code directly aware of the security layer (which could take
different forms), we can instead reach into the classes and, for
example, wrap certain methods in a function that enforces security.  If
we do it in the class directly, then even code that descends from this
class will transparently "inherit" all of the newly added security layer
code that was never there when the code was first written.  By security
layer I'm talking more about code that enforces certain user
authentication before use (as in web programming) rather than "secure" code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-31 Thread Michael Torrie
thmpsn@gmail.com wrote:
>> To be clear, python does not force you to lay out your code according to
>> some strict object-oriented paradigm.  But Python itself is still purely
>> object-oriented, as is your script when parsed.
>
> But it's only a faking, and things such as inheritance and
> polymorphism are implemented clumsily (actually I'm not even sure
> about polymorphism). And of course, there are still no private
> members.

How is it faking?  The class of a function object is "function," which
is of the metaclass "type."  What more do you want?  If Guido himself
declared that functions are objects would you believe that?  Or modules?

Since a function object is an instance of the class "function" I don't
see how you could inherit from it, and polymorphism has nothing to do
with this either.  Maybe what you are talking about is deriving a class
from the class "function."  Not sure if that's allowed, mainly because
the language has defined a standard way of declaring a function (methods
are functions too, of course), so creating a useful, derived function
object would be difficult given how the syntax of the language works.

Private members?  I could stick add any attribute I wanted to a function
object and ask that people treat it as private if I wanted to:

def myfunc():
pass

myfunc.__dict__['_private'] = 4

If you are insinuating that not forcing private attributes to be
unaccessible by others (black box theory) is in somehow a violation of
object-oriented semantics, think again.  It's not.  (There are no formal
definitions of OO anyay, but wikipedia lists quite a few characteristics
considered common to OO, and enforced private members is not one of them.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: is python Object oriented??

2009-01-31 Thread Michael Torrie
Steve Holden wrote:
> You can think what you like, but there is a fundamental difference
> between methods of a class and functions of a module. Until you
> appreciate that you will likely make mistakes. Don't worry, though, we
> all learn from our mistakes.

And this fundamental difference is?

>From what I can tell an instance method is an object that encapsulates
the function object in a closure that makes sure it has a reference to
"self."  I know that you dynamically add functions to objects creating
methods dynamically, by using new.instancemethod or something.

This seems to indicate to me that there are functions and there are
functions.  Methods are in fact functions, just with a callable wrapper
around them.  Is this not so?
--
http://mail.python.org/mailman/listinfo/python-list


Re: SimpleXMLRPCServer question

2009-01-31 Thread rdmurray
Quoth flagg :
> Let me see if i can elaborate on the requirements.  I have 20+
> different zone files.  I want the xmlrpc server to be able to
> determine what zone file to open by looking at the incoming xml
> request.  For example one of the functions I have now is to show a DNS
> record (I am using dnspython for most of this work)
> 
> If i send an xmlrpc request that uses the 'showRecord' function with
> params of 'oracle1.foo.bar.com'  I want to parse the "params" piece
> and then instruct the xml-rpc server to open foo.bar.com.zone for
> reading.  The reason why i was looking at do_Post() and _dispatch was
> to attempt to read the incoming params and do exactly that.
> 
> Do you think there is an easier way of accomplishing this, than the
> way I am going about it?

Yeah.  Take a look at the SimpleXLMRPC documentation:

http://docs.python.org/library/simplexmlrpcserver.html

In addition to setting up the server as instructed (let's assume you
assign it to the variable 'server'), you just need to do something like:

class MyFunctions:

def showRecord(self, dnsname):
domain = '.'.join(dnsname.split('.')[1:])
with open(domain+'.zone')) as myfile:
# do stuff with data from myfile

server.register_instance(MyFunctions())


You would modify the body of that function to meet your processing
requirements, of course.  That is, SimpleXMLRPCServer does the request
parsing for you, calls the correspondingly named method, and passes it
the params as method arguments.

(This example is taken from the SimpleXMLRPC documentation, I just
selected one particular way of exposing the methods: via a class
instance).

--RDM

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


Re: Tkinter w.pack()?

2009-01-31 Thread Steve Holden
W. eWatson wrote:
> Steve Holden wrote:
>> W. eWatson wrote:
>>> r wrote:
 On Jan 28, 10:12 pm, "W. eWatson"  wrote:
> Where in the world is a description of pack() for Tkinter widgets?
> Is it
> some sort of general method for all widgets? I'm looking in a few
> docs that
> use it without ever saying where it is described. For one,
> . In the NM Tech pdf on
> Tkinter,
> it's not found anywhere. I see Universal methods for widgets, but no
> mention
> of pack(). package, packed, but no pack.
 did you try here :)
 http://effbot.org/tkinterbook/pack.htm
>>> Thanks. I have the site bookmarked, but it's hard to search. I posted a
>>> comment to them that they should have it in pdf form.
>>>
>> http://letmegooglethatforyou.com/?q=site%3Aeffbot.org%2Ftkinterbook+pack
>>
>> regards
>>  Steve
> Well, that's an interesting "link". Another side of Google facilities?
> Maybe you're using Snagit or its brethern? However, I'm interested in
> searching a pdf, which, of course, doesn't yet exist.
> 
OK, someone asked if you'd seen the HTML pages. You replied that you had
them bookmarked but they were difficult to search. So I simply
demonstrated that a search of the site for "pack" gave the right page as
its first result.

Maybe you *do* want a PDF, but it will be less searchable than the
existing HTML, so I am somewhat confused about why.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: is python Object oriented??

2009-01-31 Thread thmpsn . m . k
On Jan 31, 2:27 pm, Christian Heimes  wrote:
> thmpsn@gmail.com schrieb:
>
> > But it's only a faking, and things such as inheritance and
> > polymorphism are implemented clumsily (actually I'm not even sure
> > about polymorphism). And of course, there are still no private
> > members.
>
> Do you honestly believe that C++'s private members are really private?
> Privateness is only enforced during parsing time. Nobody can stop you
> from messing around with header files or memory. You can still access
> and modify private members but it's all messy and ugly. Even C# and .NET
> don't stop you from doing nasty things from unmananged assemblies.

I don't know how you would do it in C# (or Java for that matter).

In C++ you can play with pointers to "get at" some memory location
somewhere in the object. The only portable way to know the exact
location between the beginning of the object and the desired member is
the offsetof() macro, but as I understand it this only works for POD
types, which means that it won't work for classes such as:

class NonPOD
{
private:
int a;
int b;
public:
NonPOD();
~NonPOD();
int C();
};

(I haven't ever actually tried it, so I'm not sure.)

Nevertheless, you can play and hope for the best. For example, if the
member you want to get at is 'b', then you can do:

NonPOD obj;
std::cout << "obj.b = " << *(int*) ((unsigned char*) &obj + sizeof
(int)) << std::endl;

and hope that the compiler didn't leave a hole between the 'a' member
and the 'b' member.

Getting at the 'a' member would be easier because the first member of
a struct/class always has the same memory location as the object
itself (although again I'm not sure if this is true for non-POD types
as well).

So: Sometimes it may work, usually it will be unsafe and/or non-
portable, and in most cases the procedure will look complicated. It
certainly isn't something I'd try in a real application. However, it
WOULD be tempting to access the member if the language allows me to
just write:

print "obj.b =", obj.b

and be done with it.

Personally, in Python, I use double underscores for "private" members,
so the above would look like:

print "obj.b =", obj._NonPOD__b

but it's still easier than the C++ example.

> Seriously, 'private' and 'protected' are merely tools to stop bad
> programmers from doing bad stuff. And the serve as documentation, too.

It's not just documentation. For example, suppose you're reading a
class definition and see the declaration of a veryInterestingMember
and forget that you're not supposed to access it. If you try to access
it, the compiler will give you a diagnostic message at compile time.

So you can think of it as an error-checking tool as well.

> Oh, by the way, the first C++ compilers just converted C++ code to C
> code. Such much about "You can't do OOP in C."!

More interestingly, though, most compilers translate C and C++ code to
assembler first. Does that mean that you can do object-oriented
programming, generic programming, and procedural programming in
assembler?

(Answer: No, but you can probably -- very clumsily -- fake them.)


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


Re: persistent TCP connection in python using socketserver

2009-01-31 Thread Stephen Hansen

Cheers mate I had a look into twisted but was put off by the FAQ
stating 1.0+ modules may or may not be stable, and only the 'core' is.
I don't wanna be messing around with a potentially buggy server, so im
gonna roll my own using the sockets module.
You didn't read that FAQ right: its addressing API stability. Meaning,"Are you going to keep this API next release or is it gonna change?"With your description of what you're doing, I'd be very surprised if youneeded to wander near an unstable/experimental module with a stillshifting API.Twisted is VERY stable.--S



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


Re: nth root

2009-01-31 Thread Robert Kern

On 2009-01-30 22:00, Tim Roberts wrote:

Unfortunately, unless I'm doing something wrong, this appears to take 20 times 
as long... :-)

What on earth are numpy and psyco?  Do I need to watch the Lord of the Rings?


No, but Google would help.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: nth root

2009-01-31 Thread Tim Roberts
"Tim Roberts"  wrote:
> 
>Thanks - you're probably right - just my intuition said to me that rather than 
>calculating that the 13th root of 
>4021503534212915433093809093996098953996019232
>is 3221.2904208350265
>there must be a quicker way of finding out its between 3221 and 3222
> 
>but perhaps not.

Also, remember that the number you computed there is not really the 13th
root of 4021503534212915433093809093996098953996019232.  When you convert
it to float to do the exponentiation, you're losing everything after the
15th significant digit.  Of course, if all you're looking for is the
nearest integer, that's not very relevant.

Do you really need the absolute number?  You could take log(x)/13 and work
with the log of the results.  I suspect (without trying it) that's faster
than the exponentiation.

>From one Tim Roberts to another.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: help me python

2009-01-31 Thread andrew cooke
On Jan 31, 5:36 pm, aolsu...@gmail.com wrote:
> C:\Python26>vnc.py
> Traceback (most recent call last):
>   File "C:\Python26\vnc.py", line 4, in 
>     import PyD3DES
> ImportError: DLL load failed: The specified module could not be found.

i'm surprised no-one has replied here.  what is happening is that the
vnc module is trying to load a library it needs, called PyD3DES (this
is a compiled library, a ".dll", not python source).  a little
googling shows that this is part of the vnc package.

so either the vnc package is not installed correctly, or you have a
problem with paths.

since you are using windows i can't help you in any more detail than
that - hope it helps.

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


Newbie Question: Can't multiply sequence by non-int of type 'str'

2009-01-31 Thread Paulo Repreza
Hi,

I'm just learning the very basics of python and I ran into this problem in
version 3.0/3000:

>>>x = input("x: ")
x: 36
>>> y = input("y: ")
y: 42
>>> print (x*y)
Traceback (most recent call last):
  File "", line 1, in 
print (x*y)
TypeError: can't multiply sequence by non-int of type 'str'

But when I run the same code with Python 2.6.1 it does prints the result.

Is there any special function that I should add in order to work properly
under Python 3.0?

Thanks,

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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-31 Thread r
On Jan 30, 4:36 pm, Steve Holden  wrote:
[snip]
> It's mostly a matter of teaching by example. I'd like to think I usually
> set a good example, but I've certainly been known to get crabby from time
> to time

Steve you are defiantly the better of two evils around here :D
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >