Re: Lambda going out of fashion

2004-12-23 Thread Fredrik Lundh
Craig Ringer wrote:

>  It's hard to consistently support Unicode in extension modules without
> doing a lot of jumping through hoops. Unicode in docstrings is
> particularly painful. This may not be a big deal for normal extension
> modules, but when embedding Python it's a source of considerable
> frustration. It's also not easy to make docstrings translatable.
> Supporting an optional encoding argument for docstrings in the
> PyMethodDef struct would help a lot, especially for docstrings returned
> by translation mechanisms.

docstrings should be moved out of the C modules, and into resource
files.  (possibly via macros and an extractor).  when I ship programs
to users, I should be able to decide whether or not to include docstrings
without having to recompile the darn thing.

and yes, docstrings should support any encoding supported by python's
unicode system.

>  Const. I know there's a whole giant can of worms here, but even so -
> some parts of the Python/C API take arguments that will almost always be
> string literals, such as format values for Py_BuildValue and
> PyArg_ParseTuple or the string arguments to Py*_(Get|Set)String calls.
> Many of these are not declared const, though they're not passed on to
> anywhere else. This means that especially in c++, one ends up doing a
> lot of swearing and including a lot of ugly and unnecessary string
> copies or const_cast()s to silence the compiler's whining. It
> would be nice if functions in the Python/C API would declare arguments
> (not return values) const if they do not pass them on and do not change
> them.

I think the only reason that this hasn't already been done is to reduce the
amount of swearing during the conversion process (both for the core developer
and C extension developers...).

 



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


Re: Why are tuples immutable?

2004-12-23 Thread Antoon Pardon
Op 2004-12-22, Jeff Shannon schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>>Op 2004-12-21, Jeff Shannon schreef <[EMAIL PROTECTED]>:
>>  
>>
>>How does the dict know which value is associated with which key? 
>>  
>>
>>
>>Because there is a link between the key and the value. The problem
>>with a mutated key in a dictionary is not that the link between the
>>key and the value is severed, but that the key hashes now to a different
>>bucket. But if you just go over the buckets and iterate over the keys
>>within and there associated values, you will encouter your mutated
>>key with its value.
>>  
>>
>
> Except that the hash value *IS* the link between the key and the value.  

No it is not because that would imply that keys with the same hash
would have the same value. The hash is the link between the key
and the dictionary bucket.

> You cannot change the hash value without severing the link.  You cannot 
> trace the link without the original hash value.  You do not have the 
> original hash value when accessing the dict with a mutated key.

You are wrong. Looking up a value in a dictionary is a two stage
process. First a hash is computeted in order to find the hash bucket.
Each bucket is somekind of container with key value pairs. After the
bucket is found a search is done for the pair with the right key.

If the hash of a key is changed this only upsets the first stage,
finding the right bucket. But within one bucket is still that
pair of (now mutated) key and value. And a method like items
will just go over the buckets to collect these pairs.

>>>I need to be able to access sequence-keyed dictionaries with literals, 
>>>which means that the keys need to compare by value, not ID.  Thus, I 
>>>need to have sequences that compare (and hash) by value.  These 
>>>conditions *cannot* be met by a mutable list.
>>>
>>>
>>
>>Which condition can't be met by a mutable list? The only ones I see
>>above is comparison and hashable by value. A list can be compared
>>and hashed by value.
>>  
>>
>
> A list cannot be hashed by value in such a way that the hash doesn't 
> change when the list mutates.

You didn't list that one and you don't need that condition.

>>>I can have the quality of 
>>>hash value not changing when mutated, or I can have the quality of 
>>>hashing by value, but I *cannot* have both.
>>>
>>>
>>
>>So? You don't need the first.
>>  
> That's an "interesting" assertion.  You have yet to provide any evidence 
> of it, however. 

All you need is that the lists that are used as a key remain stable.
In that case, there hash doesn't change and the directory will have
no problem finding it.

>>>Thus, even if you make 
>>>lists hash by ID, I *still* need to have an immutable tuple type so that 
>>>I can get hash-by-value. 
>>>
>>>
>>
>>No you don't. The same algorithm that works for hashing tuples will
>>work just as fine for hashing lists.
>>  
> Except that the hash value will change when the list mutates, and then I 
> can't access my dictionary values.

Then don't mutate your list. Noone advocated mutating keys in a
dictionary. It's not because I think it could be usefull to use
a mutable as a key, that I think it is usefull to mutate a key.

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


deriving from str

2004-12-23 Thread Paolo Veronelli
I want to add some methods to str class ,but when I change the __init__ 
methods I break into problems

class Uri(str):
def __init__(self,*inputs):
print inputs
if len(inputs)>1:
str.__init__(self,'<%s:%s>'%inputs[:2])
else:
str.__init__(self,inputs[0])
print inputs
a=Uri('ciao','gracco')
Traceback (most recent call last):
  File "prova.py", line 9, in ?
a=Uri('ciao','gracco')
TypeError: str() takes at most 1 argument (2 given)
where is the  str() wrong call.I suppose It's the __new__ method which 
is wrong or me .Thanks for help

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


Replacing lambda() examples... (Re: Lambda going out of fashion)

2004-12-23 Thread Petr Prikryl
Hi,

I suggest to post here simplified examples that
use the lambda to be replaced by non-lambda 
Pythonic solutions. The ideal result would be 
the set of rules, how lambdas can be replaced
by in future when they become deprecated.

Less ideal but valuable may be short examples
and counter-examples of using or not using
the lambdas.

While following the thread "Lambda going out of fashion"
I have read cries for not throwing lambdas away and also
the opposite opinions. I believe that the theme requires
more examples to convince. I personally incline towards
the experience of Craig Ringer (see other notices below):

"Craig Ringer" wrote in message news:<[EMAIL PROTECTED]>...
> [...]
> I also make signficant use of Lambda functions, but less than I used to.
> I've recently realised that they don't fit too well with Python's
> indentation-is-significant syntax, and that in many cases my code is
> much more readable through the use of a local def rather than a lambda.
> 
> In other words, I increasingly find that I prefer:
> 
> def myfunction(x):
> return x**4
> def mysecondfuntion(x):
> return (x * 4 + x**2) / x
> make_some_call(myfunction, mysecondfunction)
> 
> to:
> 
> make_some_call( lambda x: x**4, lambda x: (x * 4 + x**2) / x)
> 
> finding the former more readable. The function names are after all just
> temporary local bindings of the function object to the name - no big
> deal. Both the temporary function and the lambda can be used as
> closures, have no impact outside the local function's scope, etc. I'd be
> interested to know if there's anything more to it than this (with the
> side note that just don't care if my temporary functions are anonymous
> or not).
> [...]

I believe that GvR has a lot of experience and he proved
to be very pragmatic. If he thinks that lambdas bring more
problems than they solve, it may be some truth in it.

I also believe that lamda-trained programmers think 
a bit differently which does not automatically mean
that they think the best way in all cases.

Waiting for interesting discussion,
  Petr

-- 
Petr Prikryl (prikrylp at skil dot cz) 

---
Odchozí zpráva neobsahuje viry.
Zkontrolováno antivirovým systémem AVG (http://www.grisoft.cz).
Verze: 6.0.821 / Virová báze: 559 - datum vydání: 21.12. 2004
 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Alex Martelli
Keith Dart <[EMAIL PROTECTED]> wrote:

> My personal gripe is this. I think the core language, as of 2.3 or 2.4
> is very good, has more features than most people will ever use, and they

Indeed, it has _too many_ features.  Look at the PEP about 3.0, and
you'll see that removing redundant features and regularizing a few
oddities is what it's meant to be all about.

> (Guido, et al.) can stop tinkering with it now and concentrate more on
> the standard libraries. 

No doubt the standard library needs more work, particularly if you count
the built-ins as being part of the library (which, technically, they
are).  Indeed, much of the redundancy previously mentioned is there
rather than in the core language strictly speaking -- e.g., all of the
things returning lists (from keys, values, items methods in dicts, to
the range built-in) mostly-duplicated with things returning iterators
(iterkeys, etc) or nearly so (xrange).  These are things that can't
change in 2.5 to avoid breaking backwards compatibility.  Other things,
where bw compat is not threatened, are no doubt going to be targeted in
2.5.


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


Re: list IndexError

2004-12-23 Thread Peter Otten
Steven Bethard wrote:

> I thought it might be helpful to code some of the alternatives you've
> been given and look at the timings to put things into perspective.  The
> code:
> 
>  remove.py 
> def remove_lc(x, lst):
>  lst[:] = [item for item in lst if item != x]

[snip]

>  $ python -m timeit -s "import remove; lst = [x % 1000 for x in
> xrange(1)]" "remove.remove_(500, lst)"

I do not think it measures what you think it measures.

A statement in the -s option is only run once, so you have to be careful
with mutable data and pass a copy of your sample to the function about to
be timed. The following example illustrates the problem:

$ py24 -m timeit -n5 -r1 -s"r=[0]" -s"def f(r): print r; r[0] += 1" "f(r)"
[0]
[1]
[2]
[3]
[4]
5 loops, best of 1: 106 usec per loop

Peter

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


Re: Problem with os.listdir and delay with unreachable network drives on Windows

2004-12-23 Thread Andrey Ivanov
[Read Roberts]
> I wrote my own directory browser in order to get around a bug where 
> tkFileDialog.askdirectory()  can't handle non-ascii paths. However, I
> have a problem where I call os.listdir() on a  mapped network drive,
> e.g. os.listdir("Z:\\"), and if the network drive is unavailable, the
> UI hangs  until the OS returns with an exception because the network
> shared drive is unavailable.

>   I would like to work around this by simply not looking into  mapped
> drives that are not currently mounted.  Is there some way to check 
> the status of mapped drive to see if it is currently mounted, or a 
> better solution? ( I use the call win32api.GetLogicalDriveStrings() 
> to get the list of available drives).

> Also, is there any way to enumerate remote volumes that are mounted 
> by not mapped? I can't easily find this in the win32 stuff or via 
> googling. The win32net calls to enumerate servers and shares sound 
> likely, but don't show such volumes on my system, although I may not
> be using the right arguments.

> I have the current Windows binary install of Python 2.3.4 on my 
> Windows XP system.

Maybe  a  win32net.WNetGetUniversalName()  [expands drive to UNC name]
and   win32net.NetGetUseInfo()  [returns  various  info  on  UNC  name
including  status] will help you. I don't have a time to setup shares,
so I can't guarantee that this approach will work as you expect. First
function  might  raise an exception on disconnected devices, which you
will  need  to handle. You might also need win32file.GetDriveType() to
distinguish between remote and local drives.

-- 
Andrey

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


Re: list IndexError

2004-12-23 Thread Nick Coghlan
Steven Bethard wrote:
Ishwor wrote:
i am trying to remove an item 'e' from the list l

I thought it might be helpful to code some of the alternatives you've 
been given and look at the timings to put things into perspective.  The 
code:

 remove.py 
def remove_lc(x, lst):
lst[:] = [item for item in lst if item != x]
def remove_try(x, lst):
try:
while True:
lst.remove(x)
except ValueError:
pass
I'd suggest a slightly different definition for remove_try:
def remove_try(x, lst):
  idx = 0
  try:
while True:
  idx = lst.index(x, idx)
  del s[idx]
  except ValueError:
pass
This avoids the 'restart from the beginning' problem with the current approach.
Anyway, pitting that against Steve's remove_lc on a 2.6 GHz hyperthreaded P4 
gives the following results for different percentages of removed values:

.1%  lc: 2010 usec  try: 467 usec
10%  lc: 1810 usec  try: 427 usec
50%  lc: 1010 usec  try: 273 usec
90%  lc:  214 usec  try:  61 usec
I know why the filtration version gets faster as the percentage increases (the 
resulting list is smaller), but I'm not sure why the in-place version is getting 
faster (as it makes more method calls and performs more deletions). One 
possibility is that as the list gets shorter due to the deletions, the whole 
thing gets pulled into the processor's cache and the operations start going 
blazingly fast.

Cheers,
Nick.
P.S. These were the commands I timed:
.1%:
python -m timeit -s "import remove; lst = [bool(x % 1000) for x in 
xrange(1)]" "remove.remove_(False, lst)"

10%:
python -m timeit -s "import remove; lst = [bool(x % 10) for x in xrange(1)]" 
"remove.remove_(False, lst)"

50%:
python -m timeit -s "import remove; lst = [bool(x % 2) for x in xrange(1)]" 
"remove.remove_(False, lst)"

90%:
python -m timeit -s "import remove; lst = [not bool(x % 10) for x in 
xrange(1)]" "remove.remove_(False, lst)"

And just to prove they're both still doing the right thing in that last example:
Py> import remove
Py> lst = [not bool(x % 10) for x in xrange(1)]
Py> len(lst)
1
Py> remove.remove_lc(False, lst)
Py> len(lst)
1000
Py> lst = [not bool(x % 10) for x in xrange(1)]
Py> len(lst)
1
Py> remove.remove_try(False, lst)
Py> len(lst)
1000
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: list IndexError

2004-12-23 Thread Nick Coghlan
Peter Otten wrote:
I do not think it measures what you think it measures.
Ah, good point. . . so we were actually measuring how long it takes to make zero 
replacements on the modified list, which explains the downward trend of the 
timings (as the modified list gets shorter).

Adding the list copy (using lst[:] in the call to the remove() method) gives me 
these numbers:

.1%  lc: 2410 usec  try:   617 usec
10%  lc: 2020 usec  try:  7340 usec
50%  lc: 1780 usec  try: 34300 usec
90%  lc: 1450 usec  try: 61000 usec
Right, that's *far* more like the numbers I was expecting :)
And now they demonstrate what they were meant to demonstrate - that there's a 
reason filtration is the recommended approach!

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Alan Gauld
On Thu, 23 Dec 2004 14:13:28 +1000, Stephen Thorne
<[EMAIL PROTECTED]> wrote:
> I'm a little worried about the expected disappearance of lambda in
> python3000. I've had my brain badly broken by functional programming
> in the past, and I would hate to see things suddenly become harder
> than they need to be.

Me too.
But its not only about becoming harder, I actually like the fact
that lamda exists as a tie in to the actual concept of an
anonymous function. When you read a math book on lambda calculus
its nice to transform those concepts directly to the language.

The current Pythonic lambda has its limitations, but being able
to explicitly create lambdas is a nice feature IMHO. Its much
better than having to create lots of one-off single use functions
with meaningless names.

It can't be that hard to maintain the lambda code, why not just
leave it there for the minority of us who like the concept?

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression: perl ==> python

2004-12-23 Thread Nick Craig-Wood
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>  that's not a very efficient way to match multiple patterns, though.  a
>  much better way is to combine the patterns into a single one, and use
>  the "lastindex" attribute to figure out which one that matched.

lastindex is useful, yes.

> see
> 
>  http://effbot.org/zone/xml-scanner.htm
> 
>  for more on this topic.

I take your point. However I don't find the below very readable -
making 5 small regexps into 1 big one, plus a game of count the
brackets doesn't strike me as a huge win...

xml = re.compile(r"""
<([/?!]?\w+) # 1. tags
|&(\#?\w+);  # 2. entities
|([^<>&'\"=\s]+) # 3. text strings (no special characters)
|(\s+)   # 4. whitespace
|(.) # 5. special characters
""", re.VERBOSE)

Its probably faster though, so I give in gracelessly ;-)

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Alan Gauld
On 22 Dec 2004 23:21:37 -0800, [EMAIL PROTECTED] wrote:

> but if lambda keyword is removed, I swear I will not use the python
> anymore.

While I would be dissappointed to lose lambda, I think losing
Python would hurt me a lot more! After all we aren't losing
functionality here, just adding sonme extra work and losing some
readability. Pythonic lambdas are just syntactic sugar in
practice, they just make the code look more like true 
functional code.

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Paul Rubin
Alan Gauld <[EMAIL PROTECTED]> writes:
> readability. Pythonic lambdas are just syntactic sugar in
> practice, 

Actually it's the other way around: it's named functions that are the
syntactic sugar.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Optional Static Typing

2004-12-23 Thread bearophileHUGS
Adding Optional Static Typing to Python looks like a quite complex
thing, but useful too:
http://www.artima.com/weblogs/viewpost.jsp?thread=85551

I have just a couple of notes:

Boo (http://boo.codehaus.org/) is a different language, but I like its
"as" instead of ":" and "->", to have:
def min(a as iterable(T)) as T:
Instead of:
def min(a: iterable(T)) -> T:


Sometimes it can be useful to mix parts with static typing and parts
without it in the same module (because dynamic typing is very useful
sometimes), but some other times you want to be sure to have a full
typed and checked module. So maybe a kind of compiler directive (like
the # used to define encoding) can be used to define a module fully
typed and fully checked by a pychecker-like. (A module with static
typing can be very useful for a "true" python compiler too.)
Bear hugs,
bearophile

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


RE: Metaclasses

2004-12-23 Thread Bob . Cowdery
Title: RE: Metaclasses





Robert Brewer wrote:
>Okay. It depends on where you're getting that capability information from, but the simplest approach I can >
>think of would be to stick it in the class:
>
>class API(object):
>    __metaclass__ = MetaAPI
>    
>    capmap = global_map_getter(usercontext_or_keyring)
>
>...then "capmap" should be available within MetaAPI.__init__:
>
>class MetaAPI(type):
>    def __init__(cls, name, bases, dct):
>    for name, method in dct['capmap']:
>    setattr(cls, name, method)
>
>Of course, all of this could be done without using a metaclass--just call setattr as needed right after your >class is defined. Another option would be to immediately follow your API class definition with a call like:

>
>from myframework import captools
>
>class API(object):
>    def foo():
>    pass>
>
>captools.enable(API)
>
>
>...the choice comes down IMO to what you think will be the most usable/maintainable by those who follow you.



Thanks for your help Robert. I'm still not understanding what I am seeing. I've forgotten about the objective for the moment. I just want to understand metaclasses.

The code I have is below, in 3 separate files, the capability, the metaclass and the API class. Sorry it's a bit rubbish at the moment.

When I run this I get:


>>> import api
{'_API__cap': {'MyRig': ['mode', 'mute'], 'SDR1000': ['mode', 'blanker', 'mute'], 'YourRig': ['mode', 'blanker']}, 'radio': 'SDR1000', '__module__': 'api', '__metaclass__': }

Set property  SDR1000 mode
Set property  SDR1000 blanker
Set property  SDR1000 mute
>>> a = api.API()
>>> a.mode
Traceback (most recent call last):
  File "", line 1, in ?
    a.mode
AttributeError: 'API' object has no attribute 'mode'
>>> a.mode = 10
>>> a.mode
10
>>> 


Two things I don't understand. __init__ gets called when I import api, not when I create an instance of API so the capability is set in stone on the import and I can't change it. Second when I try to read attribute 'mode' (or any other valid attribute) I get an error. If I set it to some value and read it it's there. I know I am not actually using the capability out of the dict at the moment because I just haven't looked to see how to dig it out yet but it is passed in because it prints out ok.

Regards
Bob


Capability class ...
class Capability(object):
    
    global m_radio
    m_radio = '' 
    m_cap = {
    'SDR1000': ['mode','blanker','mute'],
    'MyRig': ['mode','mute'],
    'YourRig': ['mode', 'blanker']
    }  
    def setRadio(radio):
    global m_radio
    m_radio = radio
    
    def getRadio():
    global m_radio
    return m_radio
    
    setRadio = staticmethod(setRadio)
    getRadio = staticmethod(getRadio)


Metaclass class ...
import capability


class autoprop(type):
    def __init__(cls, name, bases, dict):
    super(autoprop, cls).__init__(name, bases, dict)


    print dict


    def _get_mode(self):
    return self.__mode
    def _set_mode(self, mode):
    self.__mode = mode
    def _get_blanker(self):
    return self.__blanker
    def _set_blanker(self, blanker):
    self.__blanker = blanker
    def _get_mute(self):
    return self.__mute
    def _set_mute(self, mute):
    self.__mute = mute
    
    # need to dig this out the dict
    radio = capability.Capability.getRadio()
    __cap = capability.Capability.m_cap
    # set capability as properties
    for i in range(len(__cap[radio])):
    if __cap[radio][i] == 'mode':
    print 'Set property ', radio, 'mode'    
    mode  = property (eval('_get_'+__cap[radio][i]), eval('_set_'+__cap[radio][i]))
    elif __cap[radio][i] == 'blanker':
    print 'Set property ', radio, 'blanker' 
    blanker  = property (eval('_get_'+__cap[radio][i]), eval('_set_'+__cap[radio][i]))
    elif __cap[radio][i] == 'mute':
    print 'Set property ', radio, 'mute'
    mute  = property (eval('_get_'+__cap[radio][i]), eval('_set_'+__cap[radio][i]))


Api class ...
import meta
import capability
capability.Capability.setRadio('SDR1000')


class API(object):
    __metaclass__ = meta.autoprop
    
    # Get the capability context
    radio = capability.Capability.getRadio()
    __cap = capability.Capability.m_cap




Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]



*** Confidentiality Notice *** 
Proprietary/ConfidentialInformation belonging to CGI Group Inc. and its 
affiliatesmay be contained in this message. If you are not a 
recipientindicated or intended in this message (or responsible 
fordelivery of this message to such person), or you think forany reason 
that this message may have been addressed to youin error, you may not use or 
copy or deliver this messageto anyone else.  In such case, you should 
destroy thismessage and are asked to no

Re: (Mac-specific) AppScript bug

2004-12-23 Thread has
George van den Driessche wrote:
> (This is really for Hamish Sanderson, I think, but I can't find an
> e-mail address for him.)

No worries. (Email addy is buried in appscript-0.7.1 > Manual.txt >
Authors, though some releases listed a duff address which certainly
didn't help. Better documentation is on my TO-DO list.)


> On OS X 10.3.7, with XCode 1.5 and all the latest AppScript packages
> installed, writing this:
>
>   a = appscript.app( 'XCode.app' )
>
> causes a crash in terminology.py:
[...]
> code is a FourCC identifying some part of XCode's script interface.
You
> would imagine that every such part would have either a plural name or
a
> singular name, but in this case somehow the FourCC '' has ended
up
> in self._elements and it has neither. Any idea how that might arise?

Sounds like a bug in XCode's terminology resource. I'd need to see the
raw terminology to say for sure. If you want to use the
osaterminology.tools.quickdoc module to dump it to text file and send
if over I'll take a look.


>  If you change the marked line (104) to read:
>
>   name = self._pluralClassNames.get(code,
> self._singularClassNames.get(code, ''+code))
>
> then the rest of the terminology seems to run fine, and you just end
up
> with one bogus entry called '' in the app's attributes.

Appscript-0.9.0 does this. Should be ready in another few days - I'll
post when it's out. Buggy terminology resources are unfortunately a
fairly common problem, and I'm still figuring out how best to deal with
them. Welcome to the wonderful and wonky world of Mac application
scripting. :p

HTH and thanks,

has

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


RE: Metaclasses

2004-12-23 Thread Bob . Cowdery
Title: RE: Metaclasses





Shalabh


Yes I am realising there are variaous ways to achieve the same end. I guess I am in research mode at the moment and understanding what metaclasses can do is important even if I end up not using them. There is another thread on this question where I am trying to fill in the gaps in my understanding.

Regards
Bob


-Original Message-
From: Shalabh Chaturvedi [mailto:[EMAIL PROTECTED]] 
Sent: 22 December 2004 23:44
To: python-list@python.org
Subject: Re: Metaclasses



[EMAIL PROTECTED] wrote:


> I am trying to build a capability based API. That is, an instance of 
> the api will reflect the capabilities of some underlying services.


The question I'd ask at this point is - does the term 'instance of the 
API' correspond to a Python class, or an instance of the class that you 
define? In case you want to have one class per API, you'd have multiple 
classes in which case metaclasses *may* be useful (but still not 
required). In case you want to have one instance per API such that each 
instance has a different set of methods,  you don't need metaclasses at all.


--
Shalabh


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



*** Confidentiality Notice *** 
Proprietary/ConfidentialInformation belonging to CGI Group Inc. and its 
affiliatesmay be contained in this message. If you are not a 
recipientindicated or intended in this message (or responsible 
fordelivery of this message to such person), or you think forany reason 
that this message may have been addressed to youin error, you may not use or 
copy or deliver this messageto anyone else.  In such case, you should 
destroy thismessage and are asked to notify the sender by reply 
email.

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

Re: Lambda going out of fashion

2004-12-23 Thread Alex Martelli
Craig Ringer <[EMAIL PROTECTED]> wrote:
   ...
> Couldn't agree more. One of the things I find most valuable about Python
> is the ability to use functional style where it's the most appropriate
> tool to solve a problem - WITHOUT being locked into a pure-functional
> purist language where I have to fight the language to get other things
> done.

By the way, if that's very important to you, you might enjoy Mozart
(http://www.mozart-oz.org/) -- I'm looking at it and it does appear to
go even further in this specific regard (rich support for multi -
paradigm programming).  It's also blessed with a great book,
 -- I've just started
browsing it, but it appears to be worthy of being called "SICP for the
21st century"...!-).  Just like SICP made it worthwhile to learn a
little Scheme even if you'd never use it in production, so does CTMCP
(acronym for this new book by Van Roy and Haridi) work for Oz, it
appears to me.


> def callfunc(function,args):
> return apply(function,args)
> 
> and
> 
> def callfunc(function,args):
> return function(*args)
> 
> its just an (IMO trivial) difference in syntax. I'd be interested in
> knowing if there is in fact more to it than this.

No, the semantics are indeed the same.


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


Re: Tabnanny really useful?

2004-12-23 Thread Stuart Bishop
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
Franz Steinhaeusler wrote:
| Not really soo useful, because most syntax and also indentation errors
| are actually detected by invoking python, i.e. the command compile.
| But as combination for this: yes why not.
| I looked for Stanis spe editor, which uses a combination of these two.
Just because Python compiles and runs something does not mean that there
are no indentation errors. tabnanny works great because it removes all
ambiguous cases so you never have to worry about it. We use it as part
of our test suite to guard against misconfigured editors.
(again using '.' instead of space) Why would you want to allow '.\tprint
foo' in Python source when you could clean it up to be the totally
unambigous 'print foo'. As a more rational example, would you
want to allow '\tprint foo', which will totally confuse someone with
their editor misconfigured with 4 char tabs?
- --
Stuart Bishop <[EMAIL PROTECTED]>
http://www.stuartbishop.net/
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.5 (GNU/Linux)
iD8DBQFByp4nAfqZj7rGN0oRAoq9AJ4scAe0A3aFnx7jRZuqtRXXaxAcRgCfYkVf
FbH2HBFA4/44KgZfpiPuvNU=
=nyQt
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why are tuples immutable?

2004-12-23 Thread Antoon Pardon
Op 2004-12-22, Jeff Shannon schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>>Op 2004-12-21, Jeff Shannon schreef <[EMAIL PROTECTED]>:
>>  
>>
>>>Antoon Pardon wrote:
>>>
>>>
>>>So show us a dictionary (i.e. hash table) implementation that can do 
>>>this.
>>>
>>>
>>
>>Why should I, Do you doubt that it is possible?
>>  
> Yes.

I'm not going to show you an implementation, but the rest of
this article should contain enough information.

>>>You'll need to be able to derive the old hash from the new hash, 
>>>of course, so that you can correctly associate the values already stored 
>>>under that key.  And you'll have to be able to do that without referring 
>>>to the pre-modified object again, because dicts can't track every Python 
>>>operation that might modify a key object.  And it needs to deal properly 
>>>with equivalent-but-different-ID list literals, because using literals 
>>>(and not references stored elsewhere) is an important and common dict 
>>>key usage.
>>>
>>>If you can show me how you plan to accomplish this, I'll accept that 
>>>you're right on this.  Until then...
>>>
>>>
>>
>>I don't have to accomplish all that in order to be able to clean up
>>a mutated dictionary key. All I need to do is go over the keys, see
>>if they hash to the same bucket as they are in now and otherwise
>>put them in the new bucket. Sure that would be costly, but so would
>>allowing arbitrary mutation in a sorted list and resorting everytime
>>or in a heapqueue and reheapifying.
>>  
>
> The problem is that once the object has mutated, you *don't know* what 
> bucket it used to sort into.  There is no point at which a dictionary 
> can see "before" and "after" -- it just sees two different lists.

I don't have to know, I just go over every bucket and in each bucket
check whether the keys in there still hash to the current bucket.
Or in other words I call the items method and use that list to
remake the dictionary. That can even be done with a thin wrapper
around dictionary in python.

And before you start asserting again that the link between the key and
the object is severed in the dictionary if you mutate the key, here an
example to show you wrong.

.>>> class Hlist:
.>>> 
.>>>   def __init__(self, lst):
.>>> self.lst = list(lst)
.>>> 
.>>>   def __hash__(self):
.>>> return sum(self.lst) % 0x7fff
.>>> 
.>>>   def __repr__(self):
.>>> return '{' + ', '.join([str(i) for i in self.lst]) + '}'
.>>> 
.>>>   def __len__(self):
.>>> return len(self.lst)
.>>> 
.>>>   def __getitem__(self, index):
.>>> return self.lst[index]
.>>> 
.>>>   def __setitem__(self, index, value):
.>>> self.lst[index] = value
.>>> 
.>>> l1 = Hlist(xrange(3))
.>>> l2 = Hlist([3, 7 , 13])
.>>> 
.>>> d = {}
.>>> 
.>>> d[l1] = 1
.>>> d[l2] = 2
.>>>
.>>> d[l1]
1
.>>> l1[0] = 99
.>>> d[l1]
Traceback (most recent call last):
  File "", line 1, in ?
KeyError: {99, 1, 2}
.>>> d.items()
[({99, 1, 2}, 1), ({3, 7, 13}, 2)]

As you can see, the mutated key with its value is among the items.
So the dictionary still maintains a link between the key and the
value even if the key is mutated.

And yes I know what to do if I want to use mutable keys as objects. I'm
just argueing against those who think that should be somehow forbidden.
 

  

>>>We're not arguing that it should be arbitrarily forbidden.  We're 
>>>arguing that doing anything else makes it impossible to behave 
>>>sensibly.
>>>
>>>
>>
>>How does having stable keys in a mutable objects makes it impossible
>>to behave sensible for dictionaries?
>>  
>>
>
> What you are calling "stable keys in a mutable object" simply cannot be 
> done while allowing comparison-by-value.

Yes it can.

>  Sensible behavior for 
> dictionary keys requires that it be possible to compare keys by value.  

No problem here.

> Overall sensible behavior for lists also provides a strong suggestion 
> (though not an absolute requirement) that lists should normally compare 
> by value.

Again no problem.

>  Your suggestion requires that lists *not* compare by value, 

No it doesn't. It only requires the dicipline of the programmer
not to mutate the objects while it is used as a key.

> and provides very little practical benefit in return for complicating 
> all other list-comparison code everywhere.
>
>>>So prove us wrong,
>>>
>>>
>>
>>I don't have to prove you wrong. If you want to argue something,
>>you have to provide reasoning that shows you right.
>>  
>>
>
> You're the one that's saying that the current behavior is flawed.  

No I'm not. I'm saying your understanding is flawed. I'm argueing
against what you thinks happens, not against what actually happens.

> You're the one making the extraordinary claim that things could be done 
> better.  I'm not even claiming that *I'm* right -- I'm claiming that GvR 
> and Tim Peters are smarter and far more likely to be right than either 
> of us. ;)

I have claimed things could be better, but that w

Re: Lambda going out of fashion

2004-12-23 Thread Stephen Thorne
On 23 Dec 2004 00:52:53 -0800, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> Alan Gauld <[EMAIL PROTECTED]> writes:
> > readability. Pythonic lambdas are just syntactic sugar in
> > practice,
> 
> Actually it's the other way around: it's named functions that are the
> syntactic sugar.

Not true, you can't re-write

def f():
raise ValueError, "Don't call f"

as a lambda. Lambdas contain only a single expression. Even the py3k
wiki page ignores this critical difference. A single expression means
no statements of any kind can be included. Assignment, if/elif/else,
while, for, try/except, etc are not catered for in lambdas.

There has been a case in the past for a lambda that contains
statements, but they have been stomped on due to problems with syntax.
I don't like lambdas that have more than a single expression myself
(if it's more complex than "lambda x:baz(x.foo(y))", I would prefer to
write a named function).

ultimate-ly yr's.
Stephen Thorne.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jython performance

2004-12-23 Thread Kent Johnson
Sean Blakey wrote:
On Wed, 22 Dec 2004 17:03:55 -0200, Gabriel Cosentino de Barros
<[EMAIL PROTECTED]> wrote:
On the "Best GUI for small-scale accounting app?" tread some people
mentioned jython. I went to read about it, but i was wondering if anyone has
any real project done with it and can give real world comments about
performance. 
I've been very happy with it's performance, after the one-time
interpreter startup.
That matches my experience as well. I have written a medium-sized GUI app using Jython and Swing and 
I am very happy with the performance. Most of the heavy lifting is done in Java libraries anyway - 
primarily Swing, dom4j and Velocity in my case.

The initial import of a module is relatively slow and I often defer importing a module until it is 
needed. Other than that I have been pleased with the performance.

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


Re: regular expression: perl ==> python

2004-12-23 Thread Fredrik Lundh
Nick Craig-Wood wrote:

> I take your point. However I don't find the below very readable -
> making 5 small regexps into 1 big one, plus a game of count the
> brackets doesn't strike me as a huge win...

if you're doing that a lot, you might wish to create a helper function.

the undocumented sre.Scanner provides a ready-made mechanism for this
kind of RE matching; see

http://aspn.activestate.com/ASPN/Mail/Message/python-dev/1614344

for some discussion.

here's (a slight variation of) the code example they're talking about:

def s_ident(scanner, token): return token
def s_operator(scanner, token): return "op%s" % token
def s_float(scanner, token): return float(token)
def s_int(scanner, token): return int(token)

scanner = sre.Scanner([
(r"[a-zA-Z_]\w*", s_ident),
(r"\d+\.\d*", s_float),
(r"\d+", s_int),
(r"=|\+|-|\*|/", s_operator),
(r"\s+", None),
])

>>> print scanner.scan("sum = 3*foo + 312.50 + bar")
(['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], '')

 



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


Re: PHP vs. Python

2004-12-23 Thread JZ
Dnia Wed, 22 Dec 2004 20:57:07 -0500, Robert Kern napisał(a):

> I think he means, "scale to larger programs," not "scale to more 
> processors."

Yes. I will try to be more specific. There is several reasons why Python
scales better than PHP. 

(1) Python uses namespaces, PHP - not. The bigger programm the bigger
probability of conflict among names in PHP.

(2) Not only PHP lacks namespaces. It has one big inconsistent mess with
its function naming! Inconsistent prefixes, order of parameters. Mess. It
is difficult to memorize it. Python programming need less interupting for
reading manual.

(3) Python uses modules, PHP - not. Python can download single or some
classes from many big modules (eg. from module1 import class1, var1, fun1).
PHP is primitive in its copy-paste *all* included files! So Python uses
less memory than PHP and do not need to parse so many lines.

(4) Python automatic compile every imported modules into bytecode, PHP has
to parse all those mess. Without accelerators PHP is much slower for bigger
applications. This is the reason why PEAR is so slow. This is the reason
why ezPublish is so slow. The bigger code (more included files), the slower
PHP works. 

(5) Python compile its modules automatic and do not need to parse them for
every browser request like PHP do.

(6) Pythonic application server (eg. Webware) do not need to load and parse
any files from filesystem at all! It loads them once, compile it and store
compiled scripts in memory. PHP has to load files from filesystem, parse
them and execute. From my own experience: when I moved from PHP to Webware
and I compared its performance with (similar scale) php appplications, my
webware was almost 6 times faster!

(7) Python has much better free IDE editors with graphic debugger inside.
PythonWin, Boa, SPE, Eric3 etc. It is much easier debug in Python than i
PHP for larger programmes.

(8) And last but not least. Python is truly object oriented, general
purpose language. PHP is not general purpose language. PHP4 has very poor
OO. (PHP5 has better, but has also some useless new features like private
variables. They have sense for static compiled languages like C++ or Java ,
not for dynamic ones.) Python also uses sofisticated exception handling,
uses namespaces, has module import, has better unicode support, has more
consistent api etc. 
One more example from my experience. I always have problem with converting
string among iso-8859-2, cp1250, mac-ce and utf-8. PHP utf8 functions are
poor, implements useless (for me) iso-8859-1 only. iconv library for PHP is
even worse, when it cannot convert some characters it deletes the following
characters! PHP has no such like: unicode(txt, 'cp1250').encode('cp1250',
'xmlcharrefreplace'). When some characters exists only in cp1250 but not in
iso-8859-2 that function convert them into xml entity &#number; Cute!

--
JZ ICQ:6712522
http://zabiello.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Fredrik Lundh
Stephen Thorne wrote:

> Not true, you can't re-write
>
> def f():
>raise ValueError, "Don't call f"

f = lambda: eval(compile("raise ValueError(\"Don't call f\")", "", "exec"))

note that lambdas have names too, btw:

print f.func_name


 



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


Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-23 Thread Antoon Pardon
Op 2004-12-22, Nick Coghlan schreef <[EMAIL PROTECTED]>:
>> I'm currently not under the impression I'm able to. Sure I could
>> implement the above mentioned classes, but my feeling is that
>> should I present them here, nobody would be waiting for them.
>> Not because they would be unusfull, but because they go against
>> the current paradigm.
>
> As I see it, you have a couple of courses available:
>
> If you're into pain, consider further developing the 'rehash' idea, and the 
> option of adding hash methods to the mutable builtins. You've persuaded me 
> that 
> the idea is not entirely unreasonable. However, I mention pain, because you'd 
> still have work to do persuading enough people (including me) that the 
> additional hard to detect bugs this adds to the language would be worth it.
>
> I don't really recommend that option.

How about this:

  from UserDict import UserDict

  class RehashableDict(UserDict):

def rehash(self):

  dic = {}
  for k,v in self.data.iteritems():
dic[k] = v
  self.data = dic


This works as far as I have tested things out.


I don't think I would recommend adding hash methods to mutable builtins.
Storing keys by identity or value both can make sense for these kind
of objects. And since python prefers not to guess I think it is a good thing
there is no default hash for mutable objects.

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


Re: Lambda going out of fashion

2004-12-23 Thread Nick Coghlan
Alan Gauld wrote:
It can't be that hard to maintain the lambda code, why not just
leave it there for the minority of us who like the concept?
Because one of the points of Py3K is to clean up the language concepts and 
syntax, and the current lambda just doesn't fit cleanly. If it was proposed in a 
PEP, the syntax would be rejected as not being sufficiently Pythonic and for 
being a castrated near-synonym for the def statement.

Now, Python 3K will retain the statement/expression distinction, so anonymous 
functions will indeed be impossible without lambda - the link from a statement 
to an expression will need to be made through the local namespace.

So, rather than pushing to retain lambda for Py3K, it might be more productive 
to find a better statement -> expression translation for function definitions. 
Guido seems to prefer named functions, so it would still be tough to gain his 
acceptance. However, a more Pythonic syntax is the only way I can see anonymous 
functions making into 3.0

The current best example of a statement->expression translation is generator 
expressions:

def squares(seq)
  for x in seq:
yield x * x
total = sum(squares(seq))
versus:
total = sum(x * x for x in seq)
If we consider a function definition (omitting decorators and docstrings) we 
get:
def foo(a, b, c):
  return f(a) + o(b) - o(c)
accepts_func(foo)
What would a Pythonic 'function as expression' look like?
Perhaps something like:
accepts_func( (def (a, b, c) to f(a) + o(b) - o(c)) )
Here we simply omit the function name and use 'to' instead of ':' (the colon is 
omitted to avoid making our expression look like it might be a statement). We 
also don't need a return statement, since our target is an expression. The 
surrounding parentheses would be required.

The "def (arg-tuple) to (result)" form is intended to show that we're talking 
about a function in the mathematical sense of a single expression, rather than 
the general Python sense of a suite of statements. That is, it has the same 
behaviour as the current lambda - if you want a real Python function, write a 
real Python function :)

Personally, I don't see the restriction of anonymous functions to single 
expressions any more of a wart than the restriction of the value portion of a 
generator expression to a single expression. If an algorithm is too complex for 
a single expression, it's probably worth giving a name.

Some more examples:
(def (x) to x * x)# Map values to their squares
(def () to x) # No arguments, always map to x
(def (*a, **k) to x.bar(*a, **k)) # Look up the method now, call it later
And in combination with a generator expression:
( (def () to x(*a, **k)) for x, a, k in funcs_and_args_list)
Replacing the 'to' with -> might actually read better:
(def (a, b, c) -> f(a) + o(b) - o(c))
(def (x) -> x * x)
(def () -> x)
(def (*a, **k) -> x.bar(*a, **k))
( (def () -> x(*a, **k)) for x, a, k in func_list)
Anyway, thats just some ideas if you're concerned about the plan to have lambda 
disappear in 3K.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: mathmatical expressions evaluation

2004-12-23 Thread Kent Johnson
Tonino wrote:
thanks all for the info - and yes - speed is not really an issue and no
- it is not an implementation of a complete financial system - but
rather a small subset of a investment portfolio management system
developed by "another company" ...
What I am trying to achieve is to parse a formula(s) and generate a
result ...
Why do you need to parse the formulas at runtime? It sounds like they are known in advance and you 
could just write functions to implement the calculations.

Kent
I will look into the pyparsing suggested and maybe even leave out
numarrays for now - as it seems a bit overkill ...
The formula are a bit complex and maybe even difficult to write out
Thanks all - I will post my progress ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Alex Martelli
Alan Gauld <[EMAIL PROTECTED]> wrote:
   ...
> It can't be that hard to maintain the lambda code, why not just
> leave it there for the minority of us who like the concept?

I guess the key motivator is the usual set of design principles:

3.   Keep the language small and simple.
4.   Provide only one way to do an operation.

Well, this phrasing is actually from the "Spirit of C" section of the
introduction to the ISO C standard, but the Zen of Python phrasing,
"""There should be one-- and preferably only one --obvious way to do
it.""" isn't all that different.

Having lambda in the language in addition to def provides two ways to do
an operation (make a function), and for that it makes the language a
little bit less simple and less small than if only def was there.  I
guess that's why Guido now regrets ever having accepted lambda into the
language, and hopes to take it away when backwards compatibility can be
broken (i.e., in 3.0).


Having just reviewed, edited and merged over 1000 recipes to select
about 1/3 of those for the 2nd edition of the Cookbook, I think I'm in a
good position to state that, at least as far as CB contributors are
representative of the Python community, uses of lambda that are dubious
to very dubious to absurd outnumber those which are decent to good by
around 4:1.  If I see another case of:

somename = lambda x: ...

instead of the obvious

def somename(x): ...

I think I'll scream, though not quite as loud as for my next seeing:

map(lambda x: f(x), ...

instead of

map(f, ...


I don't know what it IS about lambda that prompts so much dubious to
absurd use, but that's what I observed.  I don't know if that plays any
role in Guido's current thinking, though -- I have no idea how much
"dubious Python" he's had to struggle with.  One could argue that the
typical abuses of redundant lambda as shown above are closely related,
e.g., to typical abuses of booleans, such as:

if (x>y) == True:

Funny enough, though, I've seen the equivalent of this latter abuse very
often in C and C++, but not in Python (again judging e.g. from the
submissions to the cookbook site).  Maybe it's bool's relatively recent
introduction in the language; after all, one DOES often see:

if len(somecontainer) > 0:

instead of the obvious

if somecontainer:

so it's not as if pythonistas in general are blessed with some magical
"redundancy avoidance spell"...


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


Re: Lambda going out of fashion

2004-12-23 Thread Fredrik Lundh
Alex Martelli wrote:

> I think I'll scream, though not quite as loud as for my next seeing:
>
> map(lambda x: f(x), ...
>
> instead of
>
> map(f, ...

note that if you replace "map" with "some function that takes a callable", the 
difference
between these two constructs may be crucially important.

 



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


Re: Why are tuples immutable?

2004-12-23 Thread Alex Martelli
Jeff Shannon <[EMAIL PROTECTED]> wrote:
   ...
> But, you generally don't "retrieve" _keys_ from dicts.  You *use* keys
> to retrieve *values* from a dict.  The only way to get a dict to give
> you a key is by using the keys() method (or items() method) to give you
> *all* of the keys. 

There are a few more cases, such as iterating on the dict (directly or
via iterkeys or iteritems), and also the pop method.  This does not
invalidate your thesis that retrieving keys is a rarer use case than
using keys to retrieve values -- I think you're right about that (hard
to prove, but that's how it seems to me, too).


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


Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-23 Thread Antoon Pardon
Op 2004-12-23, Nick Coghlan schreef <[EMAIL PROTECTED]>:
> Steven Bethard wrote:
>> Of course, if rehash worked in place, you could probably do some 
>> optimizations to only rehash the necessary items.
>
> Yep, especially given this little critter from dictobject.h which contains 
> everything needed to spot mutated objects:
>
> typedef struct {
>   long me_hash;  /* cached hash code of me_key */
>   PyObject *me_key;
>   PyObject *me_value;
> } PyDictEntry;
>
> So the major downside to giving standard mutable objects hash methods is that 
> dictionaries then suffer from the 'mutation without resorting' problem that 
> sorted lists can currently suffer from.
>
> As I said to Antoon, I no longer have any theoretical objection to the idea 
> of 
> mutable objects with a variable hash. I do, however, have a practical 
> objection 
> - mutating a dict's keys without calling rehash() could lead to some 
> extremely 
> subtle bugs that the interpreter can't really help identify. It just seems 
> far 
> too easy to inadvertently burn yourself by altering an object that is being 
> used 
> as a dictionary key.

Well then we will have to agree to disagree on this point. Python allows
one variable to mutate by mutating another variable. That is IMO the
great burning stick in Python. That this also causes problems for
dictionaries is just a consequent of that and doesn't warrant special
protection that is not available elsewhere in the language.

I don't understand why the ease of mutating an object that should remain
stable should cause more unease in a person just because the subject
is dictionary keys, except maybe because of custom.

But I'm obviously in the minority here.

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


Re: Python on Linux Cluster

2004-12-23 Thread Irmen de Jong
Gurpreet Sachdeva wrote:
I have shifted my python script on a 4 node open ssi cluster. Please
guide me what changes do I have to do in my python scripts to fully
utilize the cluster. How do we introduce parralel processing in
python???
There was a very recent thread about this subject: http://tinyurl.com/5247f
--Irmen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Keyword arguments - strange behaviour?

2004-12-23 Thread brian . bird
> Channelling the effbot, I think he was asking what namespace context
you
> expected the expression "arg=otherfunction(x)" to be evaluated in
when
> it's used at the time of a function call to dynamically create a new
> default value for arg.

Thanks, I realise now that's what was meant. I think I was just
assuming otherfunction() would be globally available - but that's not
something I want to go into since I can see now there will be problems
trying to define what python should do if it evaluated defaults at the
function call :)

I think I can now explain to someone why there are good reasons that
the default params are evaluated at the definition. However, I still
can't give a nice looking solution on how to re-write a function to
have empty mutable values as default arguments: eg.

def method(a,b,opt1=[],opt2=None,opt3="",opt4={})

How could I re-write this (especially if there are perhaps 20 optional
parameters,any number of which may have mutable defaults) without
writing 20 "if opt1 is None: opt1=[]" statements?

Brian

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


Re: deriving from str

2004-12-23 Thread Nick Coghlan
Paolo Veronelli wrote:
I want to add some methods to str class ,but when I change the __init__ 
methods I break into problems

class Uri(str):
def __init__(self,*inputs):
print inputs
if len(inputs)>1:
str.__init__(self,'<%s:%s>'%inputs[:2])
else:
str.__init__(self,inputs[0])
print inputs
a=Uri('ciao','gracco')
Traceback (most recent call last):
  File "prova.py", line 9, in ?
a=Uri('ciao','gracco')
TypeError: str() takes at most 1 argument (2 given)
where is the  str() wrong call.I suppose It's the __new__ method which 
is wrong or me .Thanks for help
Strings are immutable, so you need to override __new__ rather than __init__.
Py> class Uri(str):
...   def __new__(cls, *inputs):
... print inputs
... if len(inputs) > 1:
...   self = str.__new__(cls, '<%s:%s>'% inputs[:2])
... else:
...   self = str.__new__(cls, inputs[0])
... return self
...
Py> Uri('ciao', 'gracco')
('ciao', 'gracco')
''
Note that the first argument is the class object rather than the new instance. 
The __new__ method *creates* the instance, and returns it.

See here for the gory details of overriding immutable types: 
http://www.python.org/doc/newstyle.html

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Keyword arguments - strange behaviour?

2004-12-23 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
> > Channelling the effbot, I think he was asking what namespace
context
> you
> > expected the expression "arg=otherfunction(x)" to be evaluated in
> when
> > it's used at the time of a function call to dynamically create a
new
> > default value for arg.
>
> Thanks, I realise now that's what was meant. I think I was just
> assuming otherfunction() would be globally available - but that's not
> something I want to go into since I can see now there will be
problems
> trying to define what python should do if it evaluated defaults at
the
> function call :)
>
> I think I can now explain to someone why there are good reasons that
> the default params are evaluated at the definition. However, I still
> can't give a nice looking solution on how to re-write a function to
> have empty mutable values as default arguments: eg.
>
> def method(a,b,opt1=[],opt2=None,opt3="",opt4={})
>
> How could I re-write this (especially if there are perhaps 20
optional
> parameters,any number of which may have mutable defaults) without
> writing 20 "if opt1 is None: opt1=[]" statements?
>
> Brian

One way that is *slightly neater* is to simply collect all keyword
arguments as a dictionary. Then compare with a dictionary of defaults
for any missing keywords.

def afunction(**keywargs):
defaults = {'param1' : [], 'param2' : {}, 'param3' : []}
for entry in defaults:
if not keywargs.has_key(entry):
keywargs[entry] = defaults[entry]

This keeps all your defaults in a single dictionary and avoids a really
long function definition.
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: Keyword arguments - strange behaviour?

2004-12-23 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
> > Channelling the effbot, I think he was asking what namespace
context
> you
> > expected the expression "arg=otherfunction(x)" to be evaluated in
> when
> > it's used at the time of a function call to dynamically create a
new
> > default value for arg.
>
> Thanks, I realise now that's what was meant. I think I was just
> assuming otherfunction() would be globally available - but that's not
> something I want to go into since I can see now there will be
problems
> trying to define what python should do if it evaluated defaults at
the
> function call :)
>
> I think I can now explain to someone why there are good reasons that
> the default params are evaluated at the definition. However, I still
> can't give a nice looking solution on how to re-write a function to
> have empty mutable values as default arguments: eg.
>
> def method(a,b,opt1=[],opt2=None,opt3="",opt4={})
>
> How could I re-write this (especially if there are perhaps 20
optional
> parameters,any number of which may have mutable defaults) without
> writing 20 "if opt1 is None: opt1=[]" statements?
>
> Brian

One way that is *slightly neater* is to simply collect all keyword
arguments as a dictionary. Then compare with a dictionary of defaults
for any missing keywords.

def afunction(**keywargs):
defaults = {'param1' : [], 'param2' : {}, 'param3' : []}
for entry in defaults:
if not keywargs.has_key(entry):
keywargs[entry] = defaults[entry]

This keeps all your defaults in a single dictionary and avoids a really
long function definition.
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: Keyword arguments - strange behaviour?

2004-12-23 Thread Fuzzyman

Steven Bethard wrote:
> [EMAIL PROTECTED] wrote:
> > However, is there a good reason why default parameters aren't
evaluated
> > as the function is called? (apart from efficiency and backwards
> > compatibility)?
>
> So, one of my really common use cases that takes advantage of the
fact
> that default parameters are evaluated at function definition time:
>
> def foo(bar, baz, matcher=re.compile(r'...')):
>  ...
>  text = matcher.sub(r'...', text)
>  ...
>

Surely "re.compile(r'...')" is effectively a constant ? So your above
code is equivalent to :

aConst = re.compile(r'...')
def foo(bar, baz, matcher=aConst):
...
text = matcher.sub(r'...', text)
...

I agree that dynamic evaluation of default arguments seems much more
pythonic, as well as getting rid of a common python gotcha.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shmtl

> If default parameters were evaluated when the function was called, my

> regular expression would get re-compiled every time foo() was called.

> This would be inefficient, especially if foo() got called a lot.  If
> Python 3000 changed the evaluation time of default parameters, I
could
> rewrite this code as:
>
> class foo(object):
>  matcher=re.compile(r'...')
>  def __new__(self, bar, baz, matcher=None):
>  if matcher is None:
>  matcher = self.matcher
>  ...
>  text = matcher.sub(r'...', text)
>  ...
>
> But that seems like a lot of work to do something that used to be
pretty 
> simple...
> 
> Steve

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


Reading and Writing

2004-12-23 Thread elias . goodman
I am new to Python and programming.  I am looking for some basic
instruction here.

How should I: Open a Text file, read from it, modify it, print to
another .txt?

For instance: Read a string, sort it, write the sorted string.

I understand the algorithms but I don't know the actual mechanics of
Python.

Any help or advice as to where to look would be great.

Thanks.

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


Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-23 Thread Nick Coghlan
Antoon Pardon wrote:
I don't think I would recommend adding hash methods to mutable builtins.
Storing keys by identity or value both can make sense for these kind
of objects. And since python prefers not to guess I think it is a good thing
there is no default hash for mutable objects.
In that case, I don't think we now disagree on anything more substantial than 
what the __hash__ documentation in the Language Reference should be saying :)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-23 Thread Nick Coghlan
Antoon Pardon wrote:
I don't understand why the ease of mutating an object that should remain
stable should cause more unease in a person just because the subject
is dictionary keys, except maybe because of custom.
But I'm obviously in the minority here.
Nah - just fighting against long-held assumptions. Those don't get changed 
overnight - it takes at least a couple of days :)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Peter Otten
Alex Martelli wrote:

> if len(somecontainer) > 0:
> 
> instead of the obvious
> 
> if somecontainer:
> 
> so it's not as if pythonistas in general are blessed with some magical
> "redundancy avoidance spell"...
 
That is not always equivalent:

>>> z = Numeric.zeros(5)
>>> z
array([0, 0, 0, 0, 0])
>>> bool(z)
False
>>> len(z) > 0
True

Peter


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


Re: Lambda going out of fashion

2004-12-23 Thread Alex Martelli
Fredrik Lundh <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> 
> > I think I'll scream, though not quite as loud as for my next seeing:
> >
> > map(lambda x: f(x), ...
> >
> > instead of
> >
> > map(f, ...
> 
> note that if you replace "map" with "some function that takes a callable",
> the difference between these two constructs may be crucially important.

Sure -- if global name f gets rebound during the execution of the ``some
function'' (or if that function stashes the callable away, and that name
gets rebound later, etc), the semantics of passing f are different -- to
get the same semantics with a lambda, you'd have to use the old trick:

somefunc(lambda x, f=f: f(x), ...


I don't recall ever having seen the late-binding semantics (of the
lambda I originally showed) ``used properly'' -- I _have_ sometimes seen
that semantics cause subtle bugs, though.  Do you have any real-life
examples where expecting and allowing for rebinding of global name `f'
is proper and desirable behavior?  Being able to show a "good" use of
this late-binding could be helpful, if I knew of any.


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


Re: Newbie namespace question

2004-12-23 Thread Brandon
I did the constructor thing and just didn't like it, it didn't feel
clean (I know, I know and monkeying with __builtin__ is?)

As for global, that will just make it modlue-level global (I think?)
and I have this reference in multiple modules.  I think I tried it
already, but I can't remember for sure...  Anyway, all of this got me
brainstorming and I think I've got a solution that I think is clean and
will be effective, I'll bust it out and post it here for comments.
Thanks for your input!

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


Re: Lambda going out of fashion

2004-12-23 Thread jfj
Stephen Thorne wrote:
Hi guys,
I'm a little worried about the expected disappearance of lambda in
python3000. I've had my brain badly broken by functional programming
in the past, and I would hate to see things suddenly become harder
than they need to be.
Don't worry, it's not gonna go away because too much software is
depending on it. If you don't follow the advice that lambda is 
deprecated and you keep using it, more software will depend on it and it 
will never disappear :)

Personally I'm not a fan of functional programming but lambda *is* 
useful when I want to say for example:

  f (callback=lambda x, y: foo (y,x))
I don't believe it will ever disappear.
G.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading and Writing

2004-12-23 Thread Sir Galahad the chaste
Hi,
[EMAIL PROTECTED] wrote:
How should I: Open a Text file, read from it, modify it, print to
another .txt?
For instance: Read a string, sort it, write the sorted string.
What do you mean by "sorting"? If you want to sort the lines contained 
in a file, you could do something like this.

$ cat in.txt
foo
bar
baz
ham
spam
$ cat process.py
#!/usr/bin/env python
lines = open("in.txt").readlines()
lines.sort()
out = open("out.txt", "w")
for line in lines:
out.write(line)
out.close()
$ python process.py
$ cat out.txt
bar
baz
foo
ham
spam
Regards
G.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Alex Martelli
Peter Otten <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> 
> > if len(somecontainer) > 0:
> > 
> > instead of the obvious
> > 
> > if somecontainer:
> > 
> > so it's not as if pythonistas in general are blessed with some magical
> > "redundancy avoidance spell"...
>  
> That is not always equivalent:
> 
> >>> z = Numeric.zeros(5)
> >>> z
> array([0, 0, 0, 0, 0])
> >>> bool(z)
> False
> >>> len(z) > 0
> True

Good point!  Numeric sure has semantics here that can be confusing;-).

numarray's arrays just can't be used as the argument to bool(...) -- you
get a runtime error "An array doesn't make sense as a truth value.  Use
sometrue(a) or alltrue(a)" ("in the face of ambiguity, refuse the
temptation to guess").  Still, this ALSO means that len(z)>0 is very
different from bool(z), for numarray as for Numeric.

Most containers don't choose to implement __nonzero__, so bool(z) just
calls __len__ instead; that's the scenario I had in mind, of course.
But sure, if somecontainer might define peculiar semantics in
__nonzero__, then in order to test if it's empty you can't use the
normal pythonic idiom of checking its truth value, but rather must check
its length.  (I still prefer "if len(z):", avoiding the redundant ">0",
but that's just a small difference, of course).


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


Re: Lambda going out of fashion

2004-12-23 Thread Nick Coghlan
jfj wrote:
Stephen Thorne wrote:
Hi guys,
I'm a little worried about the expected disappearance of lambda in
python3000. I've had my brain badly broken by functional programming
in the past, and I would hate to see things suddenly become harder
than they need to be.
Don't worry, it's not gonna go away because too much software is
depending on it. If you don't follow the advice that lambda is 
deprecated and you keep using it, more software will depend on it and it 
will never disappear :)
No, that doesn't apply for Python 3.0
Indeed, lambda as it currently stands will disappear for the Python 2.x series.
Python 3.0 will be a case of "OK, let's take the things we learned were good and 
keep them, and throw away the things we realised were bad"

Undoubtedly, the two languages will co-exist for quite some time.
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Alex Martelli
Nick Coghlan <[EMAIL PROTECTED]> wrote:
   ...
> Perhaps something like:
> 
> accepts_func( (def (a, b, c) to f(a) + o(b) - o(c)) )

Nice, except I think 'as' would be better than 'to'.  'as' should be a
full keyword in 3.0 anyway (rather than a surprisingly-NOT-keyword like
today), and "define something as somethingelse" seems marginally more
readable to me than "define something to somethingelse" anyway.


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


Re: Newbie namespace question

2004-12-23 Thread Nick Coghlan
Brandon wrote:
I did the constructor thing and just didn't like it, it didn't feel
clean (I know, I know and monkeying with __builtin__ is?)
As for global, that will just make it modlue-level global (I think?)
and I have this reference in multiple modules.  I think I tried it
already, but I can't remember for sure...  Anyway, all of this got me
brainstorming and I think I've got a solution that I think is clean and
will be effective, I'll bust it out and post it here for comments.
Thanks for your input!
Another option for you to consider:
#__main__ ( I forget the script's name)
import app_config
app_config.setConfiguration(AdminConfig)
from jdbc import DataStore
 . . .etc
#jdbc.py
from app_config import AdminConfig
. . .etc
#app_config.py
def setConfiguration(adm_cfg):
  global AdminConfig
  AdminConfig = adm_cfg
The reason the import solution was breaking for you earlier was that you were 
setting up circular imports by using your main script as the holder for the 
global configuration.

By creating a special 'configuration data' module, you can use that to store the 
data, and every module that needs it can import it without worrying about 
circular imports.

Any extra global configuration properties can be added by updating the 
'setConfiguration' function.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for Series 60 update

2004-12-23 Thread Jukka Laurila
On Thu, 23 Dec 2004 06:52:28 +0800, Tim Hoffman <[EMAIL PROTECTED]> wrote:

> I did find a problem with it on my 7610.

> It works, but I had to hard code my bluetooth mac address (I assume
> thats what it is called in bluetooth).  The bt_discover() call
> didn't seem to find my host.

How did it fail? Did it simply not show your computer in the list or
did it hang indefinitely when connecting to it? Bluetooth discovery
has always been problematic, but connecting to a host directly using
the mac address has worked perfectly for months now. (I am one of the
developers in this project.)

Try doing the discovery again. Sometimes the phone just magically
discovers hosts it did not see ten seconds earlier. The discovery will
also fail if there already is a Bluetooth connection open, for example
the PC Suite can leave connections open that mess up the
discovery. You can force all connections to be terminated by turning
bluetooth on and off from the phone menu.

> from the console I could immediatly do xml-rpc calls
> to my favourite Zope/CMF instance over GPRS and it just worked.
> 
> This is cool.

Yes, very :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Craig Ringer
Fredrik Lundh wrote:
Craig Ringer wrote:
 

It's hard to consistently support Unicode in extension modules without
doing a lot of jumping through hoops. Unicode in docstrings is
particularly painful. This may not be a big deal for normal extension
modules, but when embedding Python it's a source of considerable
frustration. It's also not easy to make docstrings translatable.
Supporting an optional encoding argument for docstrings in the
PyMethodDef struct would help a lot, especially for docstrings returned
by translation mechanisms.
   

docstrings should be moved out of the C modules, and into resource
files.  (possibly via macros and an extractor).  when I ship programs
to users, I should be able to decide whether or not to include docstrings
without having to recompile the darn thing.
 

Good point. Unfortunately, many translation mechanisms - like Qt's, for 
example - don't make it easy to translate strings in resource files 
using the same tools as the core app. Translators have a hard enough job 
already with one set of tools in my experience, lumping more on them 
probably isn't nice. On the other hand, this isn't really Python's 
problem - but neither is where they come from. Even if I load docstrings 
from resource files, I still have a fair bit of work ahead to make 
Python accept them if they're not plain ASCII. In my current project, I 
actually gave up and changed sysdefaultencoding to utf-8 .  (It's an 
embedded interpreter, so it's not too bad - and all modules should 
handle that correctly by now anyway).

Const. I know there's a whole giant can of worms here, but even so -
some parts of the Python/C API take arguments that will almost always be
string literals, such as format values for Py_BuildValue and
PyArg_ParseTuple or the string arguments to Py*_(Get|Set)String calls.
Many of these are not declared const, though they're not passed on to
anywhere else. This means that especially in c++, one ends up doing a
lot of swearing and including a lot of ugly and unnecessary string
copies or const_cast()s to silence the compiler's whining. It
would be nice if functions in the Python/C API would declare arguments
(not return values) const if they do not pass them on and do not change
them.
   

I think the only reason that this hasn't already been done is to reduce the
amount of swearing during the conversion process (both for the core developer
and C extension developers...).
 

Agreed. However, it's my understanding that one can convert:
PyObject* *Py_BuildValue*(  char *format, ...)
to
PyObject* *Py_BuildValue*(  const char *format, ...)
(for example) without affecting module developers or users of that 
function elsewhere in the core code. const _arguments_ are often very 
safe, its const return values that tend to suck.

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


Re: Lambda going out of fashion

2004-12-23 Thread Robin Becker
Alex Martelli wrote:
.
By the way, if that's very important to you, you might enjoy Mozart
(http://www.mozart-oz.org/) -- I'm looking at it and it does appear to
go even further in this specific regard (rich support for multi -
paradigm programming).  It's also blessed with a great book,
 -- I've just started
browsing it, but it appears to be worthy of being called "SICP for the
21st century"...!-).  Just like SICP made it worthwhile to learn a
little Scheme even if you'd never use it in production, so does CTMCP
(acronym for this new book by Van Roy and Haridi) work for Oz, it
appears to me.
.very interesting, but it wants to make me install emacs. :(
Alex

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


Re: Lambda going out of fashion

2004-12-23 Thread Nick Coghlan
Alex Martelli wrote:
Nick Coghlan <[EMAIL PROTECTED]> wrote:
   ...
Perhaps something like:
accepts_func( (def (a, b, c) to f(a) + o(b) - o(c)) )

Nice, except I think 'as' would be better than 'to'.  'as' should be a
full keyword in 3.0 anyway (rather than a surprisingly-NOT-keyword like
today), and "define something as somethingelse" seems marginally more
readable to me than "define something to somethingelse" anyway.
I actually flipped back and forth between preferring 'as' and 'to' while writing 
the message.

It was the mathematical phrasing of "f is a function from R to R" (replacing the 
capital R's with the symbol for the real numbers) that first made me think of 
'to', since I was trying to emphasise the parallels with mathematical functions. 
(To my mind, theoretical mathematics is one of the areas with significant 
legitimate uses for lambda functions).

The '->' suggestion had a similar source.
The way I'd read the 'to' version out loud when explaining to someone what the 
code did:

"DEFine an anonymous function from arguments a, b and c TO the value f of a plus 
o of b minus o of c"

or the short version:
"DEFine a function from a, b and c TO f a plus o b minus o c"
As an even simpler example, (def (x) to x * x) would be "define a function from 
x to x squared". (def () to ) would be "define a function from no 
arguments to "

'as' already implies renaming semantics due to from-style imports. In Py3k, it's 
likely to pick up the naming duties in except clauses as well (i.e. "except 
ValueError, TypeError as ex:").

'as' is also a candidate for optional static typing and adaptation (and 
hopefully someone will talk Guido out of his punctuation happy version of that!).

I eventually decided that using 'as' for anonymous functions as well would just 
be plain confusing.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Nick Coghlan
Nick Coghlan wrote:
Indeed, lambda as it currently stands will disappear for the Python 2.x 
series.
Will NOT disappear. I repeat, will NOT disappear.
Cheers,
Nick.
Damn those missing negators. . .
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Stephen Thorne
On Thu, 23 Dec 2004 13:47:49 +0100, Alex Martelli <[EMAIL PROTECTED]> wrote:
> Nick Coghlan <[EMAIL PROTECTED]> wrote:
>...
> > Perhaps something like:
> >
> > accepts_func( (def (a, b, c) to f(a) + o(b) - o(c)) )
> 
> Nice, except I think 'as' would be better than 'to'.  'as' should be a
> full keyword in 3.0 anyway (rather than a surprisingly-NOT-keyword like
> today), and "define something as somethingelse" seems marginally more
> readable to me than "define something to somethingelse" anyway.

I'm sorry, but I dislike this quite a bit, 'def arglist as expression'
just doesn't fit right for me.

After reading the discussion, and trying to glean answers to my
original questions, I realise that there's a pragmatic way of doing
the things that I mentally 'require' lambda for, without using lambda
at all. I might try and catalog lambda patterns and their alternatives
at some point.

Alex, thankyou for the feedback concerning the misuse of lambda. I
consider prevention of misuse to be much more important than the
denial of use. I recognise fully the frustration you must experience
when you see map(lambda x:f(x).

I think it is important to voice concern, and I recieved not a few
'me-too's in reply to this thread. But at the end of the day, I'm not
against removing lambda in py3k.

slightly-less-concerned-ly yr's
Stephen Thorne.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread rzed
Stephen Thorne <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Hi guys,
> 
> I'm a little worried about the expected disappearance of lambda
> in python3000. I've had my brain badly broken by functional
> programming in the past, and I would hate to see things suddenly
> become harder than they need to be.
> 
> An example of what I mean is a quick script I wrote for doing
> certain actions based on a regexp, which I will simlify in this
> instance to make the pertanant points more relevent.
> 
> {
>  'one': lambda x:x.blat(),
>  'two': lambda x:x.blah(),
> }.get(someValue, lambda x:0)(someOtherValue)
> 
> The alternatives to this, reletively simple pattern, which is a
> rough parallel to the 'switch' statement in C, involve creating
> named functions, and remove the code from the context it is to
> be called from (my major gripe).
>
> So, the questions I am asking are: 
> Is this okay with everyone? 
> Does anyone else feel that lambda is useful in this kind of
> context? Are there alternatives I have not considered?
> 

Not addressing lambdas per se, but something similar to your pseudo-
switch statement can be done without using them at all. One way might 
be to use a function dictionary wrapped in an accessor function, such 
as this:

def dofns(key):
fd2 = {
0:'print "Key 0"',
1:'print "one"',
4:"\n".join(['for ix in range(15):',
'  print "%s%d" % (" "*ix,ix)']),
}
try:
exec(fd2[key])
except KeyError:
print 'Key',key,'not found'

The keys can as easily be strings, of course. One virtue of this 
method is that it allows multi-line statements and looping (as in fd2
[4]).

Now the actual 'switch' statement becomes as simple as:
dofns(key)

If there are parameters involved, this solution becomes a little 
tackier. One way might be something like:

def dofns(key,**kws):
fd2 = {
0:'print "Key 0"',
1:'print "one"',
2:"\n".join(['n=kws["name"]','x=kws["x"]',
'y=kws["y"]','print "%s:"%n,x,y']),
3:"\n".join(['val=kws["x"]*7 + kws["y"]',
'print kws["x"],kws["y"],val']),
4:"\n".join(['for ix in range(kws["x"]):',
'  print "%s%d" % (" "*ix,ix)']),
5:'exec(fd2[3])',
6:"\n".join(['print kws["z"],',
'dofns(3,x=13,y=22)']),
}
try:
exec(fd2[key])
except KeyError:
print 'Key',key,'not found'


# switch (key kwdparms)
for key in [0, 1,2,3,4,5,6,7]:
dofns(key,name='Gladys',y=50,x=8,z=34)

You could remove the function dictionary from the wrapper and use it 
similarly to your example, but I find that less readable. 
exec({
multi-line dictionary definition
}[key] parms) # what were we doing again? Oh! exec!

Anyway, for those who use lambdas, this approach is likely to be 
unappealing. For those who find lambdas puzzling, it may be an 
alternative, at least for a way to handle the switch equivalent.

-- 
rzed

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


test

2004-12-23 Thread Per Erik Stendahl
sdfdsafasd
--
http://mail.python.org/mailman/listinfo/python-list


odbc for solid

2004-12-23 Thread flupke
Hi,
at work we use a solid database and i need to develop an application 
that accesses it. Problem is the drivers: i only have some dll's lying 
around and jar.
On winsdows i could get by by using ODBC and the dll's to access the 
solid database but i want to eventually run it on a linux server.
Solid doesn't seem to have a driver specifically for Linux so i'm stuck 
here. Is there any way i can still use Linux and have access to solid?
Maybe i need to revert to jython so i can use the jar?

Thanks for any info
Benedict
--
http://mail.python.org/mailman/listinfo/python-list


subclassing list

2004-12-23 Thread Uwe Mayer
Hi,

I want to subclass "list". The documentation states to prefer subclassing
list instead of UserList. How to you clear the contents of a list subclass
without creating a new object?

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


urllib and sites that require passwds

2004-12-23 Thread [EMAIL PROTECTED]
Hello,

I'm doing a small website survey as a consultant for a company that has
a large private lan. Basically, I'm trying to determine how many web
sites there are on their network and what content the sites contain
(scary how they don't know this, but I suspect many companies are this
way).

Everything is going fine so far except for sites that require passwds
to be accessed. I don't want to view content on these sites, I only
want to note that they are passwd protected, make a list of them and
move on. The problem is that urllib hangs waiting for a username/passwd
to be entered. Is there a graceful way to deal with this?
Many thanks,
Bob

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


list Integer indexing dies??

2004-12-23 Thread Ishwor
Hi all. Look at this snippet of code.

>>> l = ['a','b','c','d']
>>> l
['a', 'b', 'c', 'd']
>>> l[0][0][0]
'a'
It prints the value 'a'. Fine so far :-)
l[0] ---> 'a' . 
l[0][0]---> 'a'[0] --> 'a'.
l[0][0][0] ---> 'a'[0][0] --> 'a'[0] --> 'a'

Now why doesnt this list which holds integer seem to work??

>>> l = [1,2,3]
>>> l[0]
1
>>> l[0][0]

Traceback (most recent call last):
  File "", line 1, in -toplevel-
l[0][0]
TypeError: unsubscriptable object
>>> l[0] 
1
>>> 1[0] 

Traceback (most recent call last):
  File "", line 1, in -toplevel-
1[0]
TypeError: unsubscriptable object
>>>

The compiler reports unsubscriptable object ?? confused , dazzled i am ???!!??
The same list now holds integer instead of strings and l[0][0][0]
which worked fine  earlier on strings doesn't seem to work on
integers???
Any help is greatly appreciated.



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


RE: list Integer indexing dies??

2004-12-23 Thread Batista, Facundo
Title: RE: list Integer indexing dies??





[Ishwor]



#- Now why doesnt this list which holds integer seem to work??
#- 
#- >>> l = [1,2,3]
#- >>> l[0]
#- 1
#- >>> l[0][0]
#- 
#- Traceback (most recent call last):
#-   File "", line 1, in -toplevel-
#- l[0][0]
#- TypeError: unsubscriptable object
#- >>> l[0] 
#- 1
#- >>> 1[0] 
#- 
#- Traceback (most recent call last):
#-   File "", line 1, in -toplevel-
#- 1[0]
#- TypeError: unsubscriptable object
#- >>>


Well, because the integer is not a subscriptable object


IOW, the string is a sequence of characters, and the integer is not sequence at all.


>>> 'a'[0]
'a'
>>> 'ab'[0]
'a'
>>> 'ab'[1]
'b'


What behaviour did you expect when subscripting an integer?


.    Facundo


Bitácora De Vuelo: http://www.taniquetil.com.ar/plog
PyAr - Python Argentina: http://pyar.decode.com.ar/



  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA.


La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje.

Muchas Gracias.



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

RE: Python Users Nederland - python-nl mailing list

2004-12-23 Thread Klaus Muller
Ik zal aan deze bijeenkomst deelnemen.

Ik ben de developer van SimPy (Simulation in Python). Als er belangstelling
bestaat, kan ik op een van de toekomstige meetings een presentatie over
SimPy geven.

Klaus Müller
simpy.sourceforge.net

> -Original Message-
> From: Johannes Gijsbers [mailto:[EMAIL PROTECTED]
> Sent: Tuesday, December 21, 2004 9:32 PM
> To: [EMAIL PROTECTED]
> Subject: Python Users Nederland - python-nl mailing list
> 
> Python Users Nederland, PUN, houdt haar tweede meeting op dinsdag 11
> januari om
> 20.00.
> 
> "Agenda"
> 
> 
> We beginnen om 20.00 met een presentatie van 1-1,5 van Martijn Faassen.
> Hij zal
> spreken over de Zope 3 component architectuur, met misschien een aantal
> uitweidingen over Five (Zope 3 in Zope 2). Na de presentatie kunnen we
> uitwijken naar één van de kroegen rond het Leidseplein.
> 
> Locatie
> ---
> 
> De locatie is in principe het kantoor van Amaze (http://www.amaze.nl),
> maar als
> blijkt dat er veel belangstelling is (>15/20) dan kunnen we waarschijnlijk
> uitwijken naar een ruimte van XS4ALL. Meldt het dus als je van plan bent
> te
> komen.
> 
> Over PUN
> 
> 
> Python Users Nederland is een beginnende gebruikersgroep. We hebben een
> website
> (http://www.py.nl) en een mailinglist
> (http://mail.python.org/mailman/listinfo/python-nl). De mailinglist wordt
> ook
> gebruikt om Nederlandse Python-gebruikers voor andere projecten op te
> sporen.
> 
> Cheers,
> 
> Johannes


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


Re: list Integer indexing dies??

2004-12-23 Thread Antoon Pardon
Op 2004-12-23, Ishwor schreef <[EMAIL PROTECTED]>:
> Hi all. Look at this snippet of code.
>
 l = ['a','b','c','d']
 l
> ['a', 'b', 'c', 'd']
 l[0][0][0]
> 'a'
> It prints the value 'a'. Fine so far :-)
> l[0] ---> 'a' . 
> l[0][0]---> 'a'[0] --> 'a'.
> l[0][0][0] ---> 'a'[0][0] --> 'a'[0] --> 'a'
>
> Now why doesnt this list which holds integer seem to work??

Because this only works with strings.

String is the only object in python which has an implied
equivallence between an element and a squence of one.

So one character is a string and a string is a sequence
of characters.

So 'a'[0] is again 'a' which can again be indexed by
0 as many times as you want.


I think python would have been more consistent if
strings would have been tuples of chars and maybe
implied an equivalence between whatever object and
a singleton of that object.

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


Re: list Integer indexing dies??

2004-12-23 Thread Ishwor
On Thu, 23 Dec 2004 11:17:57 -0300, Batista, Facundo
<[EMAIL PROTECTED]> wrote:
> 
[snip]

> #- >>> 1[0] 
> #- 
> #- Traceback (most recent call last): 
> #-   File "", line 1, in -toplevel- 
> #- 1[0] 
> #- TypeError: unsubscriptable object 
> #- >>> 
> 
> Well, because the integer is not a subscriptable object 
> 
If i see this code 'a'[0] then what does it really say about semantics
?? Really its hard for me to digest that 'a'[0] is supported by Python
where as 1[0] isn't.
look at this
>>> 'invalid'[0]
'i'
>>> 123232[-1] 
# Python should automagically infer here that user
# means indexing and *not* the number per se. 
# (i mean list in context of the line :-) )

Traceback (most recent call last):
  File "", line 1, in -toplevel-
123232[-1]
TypeError: unsubscriptable object


> IOW, the string is a sequence of characters, and the integer is not sequence
> at all. 
> 

strings are immutable sequence of collections in Python. Integers are
numbers. ;-)

> >>> 'a'[0] 
> 'a' 
> >>> 'ab'[0] 
> 'a' 
> >>> 'ab'[1] 
> 'b' 
> 
> What behaviour did you expect when subscripting an integer? 
>

I got unscriptable object TypeError (extract below) which is *now*
with your enlightment clear to me ;-)

>>> 1[0]

Traceback (most recent call last):
 File "", line 1, in -toplevel-
   1[0]
TypeError: unsubscriptable object
>>>


 
> .Facundo 
> 
> Bitácora De Vuelo: http://www.taniquetil.com.ar/plog 
> PyAr - Python Argentina: http://pyar.decode.com.ar/ 
> 

[snip]

Thanks Batista.

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


Re: Lambda going out of fashion

2004-12-23 Thread Jp Calderone
On Thu, 23 Dec 2004 13:36:08 GMT, rzed <[EMAIL PROTECTED]> wrote:
>Stephen Thorne <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]: 
> > [snip]
> > 
> > {
> >  'one': lambda x:x.blat(),
> >  'two': lambda x:x.blah(),
> > }.get(someValue, lambda x:0)(someOtherValue)
> > 
> > The alternatives to this, reletively simple pattern, which is a
> > rough parallel to the 'switch' statement in C, involve creating
> > named functions, and remove the code from the context it is to
> > be called from (my major gripe).
> >
> > [snip]
> 
> Not addressing lambdas per se, but something similar to your pseudo-
> switch statement can be done without using them at all. One way might 
> be to use a function dictionary wrapped in an accessor function, such 
> as this:
> 
> def dofns(key):
> fd2 = {
> 0:'print "Key 0"',
> 1:'print "one"',
> 4:"\n".join(['for ix in range(15):',
>   '  print "%s%d" % (" "*ix,ix)']),
> }
> try:
> exec(fd2[key])
> except KeyError:
> print 'Key',key,'not found'
> 

  I hate to be nasty, but *ugh* what a horrible way to start the day.

  There are so many things wrong with this.

  By exec'ing code strings you lose compile-time _syntax_ 
checking.  I'm all for dynamicism, but it really is nice to let the 
compiler do _something_ things for you.

  By exec'ing code strings you slow down the entire function 
by forcing a slower name-lookup code path in the interpreter.

  By exec'ing code strings you lose the ability to pass values 
back to your caller (oh, you could "return" in one of those, but
*ugg* that'd be even more terrible, and probably not what you want
in most cases, since it doesn't let you get at the value except from
your caller.  you could also set names in the local namespace but
that's pretty messed up too, python already has a function return
convention, making up your own is no fun).

  There are probably more reasons this is bad too.

  Even using `def' to define a function for each of these would be 
preferable.

  Aside from that, exec() isn't a function.  You "exec foo", not 
"exec(foo)".  The latter works simply because parens act as to set 
precedent instead of as part of function call syntax when used this 
way.

  Also, you should do the dictionary lookup first, in a try/except, 
and then execute it later, _outside_ the try/except, otherwise you 
risk masking KeyErrors from exec'd code.

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


Re: urllib and sites that require passwds

2004-12-23 Thread Fuzzyman
USe urllib2 which will fail with an exception. You can trap this
exception and using the code attribute of the exception object,
determine why it failed. The error code for 'authentication required'
is 401.

Off the top of my head :

import urllib2
req = urllib2.Request(theurl)
try:
handle = urllib2.urlopen(req)
except IOError, e:
if not e.hasattr('code'):
print 'The url appears to be invalid.'
print e.reason
else:
if e.code == 401:
print theurl, 'is protected with a password.'
else:
print 'We failed with error code', e.code
HTH

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


RE: list Integer indexing dies??

2004-12-23 Thread Batista, Facundo
Title: RE: list Integer indexing dies??





[Ishwor]


#- >>> 'invalid'[0]
#- 'i'
#- >>> 123232[-1] 
#- # Python should automagically infer here that user
#- # means indexing and *not* the number per se. 
#- # (i mean list in context of the line :-) )


Python never should automagically infer nothing!


Type "import this" in the interactive interpreter and look at rule #2.



#- > IOW, the string is a sequence of characters, and the 
#- integer is not sequence
#- > at all. 
#- > 
#- 
#- strings are immutable sequence of collections in Python. Integers are
#- numbers. ;-)


Nop. Strings are not a sequence of collections, just a sequence of characters.


.   Facundo


  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA.


La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje.

Muchas Gracias.



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

Re: subclassing list

2004-12-23 Thread Fuzzyman
class newList(list):
def clear(self):
self[:] = []

is one way.
HTH

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


(no subject)

2004-12-23 Thread Ran Libeskind-Hadas
From: Ran Libeskind-Hadas (via the vacation program)
Subject: Your e-mail

This message was generated automatically in response to your e-mail.
I will be traveling and away from my e-mail until Tuesday, December 28.
I will respond to your e-mail when I return.

Thank you,

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


Re: list Integer indexing dies??

2004-12-23 Thread Ishwor
On 23 Dec 2004 14:28:37 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> Op 2004-12-23, Ishwor schreef <[EMAIL PROTECTED]>:
> > Hi all. Look at this snippet of code.
> >
>  l = ['a','b','c','d']
>  l
> > ['a', 'b', 'c', 'd']
>  l[0][0][0]
> > 'a'
> > It prints the value 'a'. Fine so far :-)
> > l[0] ---> 'a' .
> > l[0][0]---> 'a'[0] --> 'a'.
> > l[0][0][0] ---> 'a'[0][0] --> 'a'[0] --> 'a'
> >
> > Now why doesnt this list which holds integer seem to work??
> 
> Because this only works with strings.
> 
> String is the only object in python which has an implied
> equivallence between an element and a squence of one.
> 
> So one character is a string and a string is a sequence
> of characters.
> 
> So 'a'[0] is again 'a' which can again be indexed by
> 0 as many times as you want.

;-) gotcha. But shouldn't this be valid too?? 
>>> 123232[0] 
in which basically python can infer from the object type and print out
1 instead of coughing up those errors? My experience as a learner here
is that there should be some automagics  & say like "okay you want to
do indexing on integers ( context dependent); i'll give you the index
of 0th position in that integer" ???
 

[snip]

Thanks Antoon.
-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclassing list

2004-12-23 Thread Richie Hindle

[Uwe]
> How [do] you clear the contents of a list subclass
> without creating a new object?

Use the paranoia emoticon: "del x[:]".  For example:

>>> class L(list):
...   pass
...
>>> x = L()
>>> x.append("Spam")
>>> del x[:]
>>> x
[]
>>> type(x)

>>>

with-thanks-to-Gordon-McMillan-ly y'rs,

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: urllib and sites that require passwds

2004-12-23 Thread Fuzzyman
damn... I'm losing my leading spaces indentation should be obvious
anyway... (everything below except is indented at least one step).
Fuzzy

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


Re: list Integer indexing dies??

2004-12-23 Thread Ishwor
On Thu, 23 Dec 2004 11:40:12 -0300, Batista, Facundo
<[EMAIL PROTECTED]> wrote:
> 
> 
> [Ishwor] 
> 
> #- >>> 'invalid'[0] 
> #- 'i' 
> #- >>> 123232[-1] 
> #- # Python should automagically infer here that user 
> #- # means indexing and *not* the number per se. 
> #- # (i mean list in context of the line :-) ) 
> 
> Python never should automagically infer nothing! 
> 
> Type "import this" in the interactive interpreter and look at rule #2. 
> 
> 
It would be too much sometimes.. its like saying "do only as much as i
say and nothing much. If you are trying to give some gift to me, i
won't take it "
Anyway i'll go with import this's #2. 

> #- > IOW, the string is a sequence of characters, and the 
> #- integer is not sequence 
> #- > at all. 
> #- > 
> #- 
> #- strings are immutable sequence of collections in Python. Integers are 
> #- numbers. ;-) 
> 
> Nop. Strings are not a sequence of collections, just a sequence of
> characters. 

Sorry i'll rephrase it. strings are **immutable sequence** of
characters which fall under Collections type.  ;-)


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


Re: Best GUI for small-scale accounting app?

2004-12-23 Thread Steve Holden
huy wrote:
Dave Cook wrote:
On 2004-12-20, Paul Rubin  wrote:

I think I can put together a useable (but not visually stunning) web
interface faster than I can put together any pure client-side
interface.  

Web browser "widgets" seem pretty limited to me, though.  You don't even
have something as simple as a combo box (i.e. an editable entry with a 
drop
down), let alone the rich set of widgets something like wxwidgets offers.
Also web development doesn't seem as coherent to me as development with a
good GUI framework.

I think it depends on your target audience. Many people love simplicity. 
 Many people hate multiple tabs, tree structures, deep nested menus etc 
etc. If you wanted to make a web program as complex as a rich client 
program then it's probably a bad idea to do as a web program. But If you 
wanted to keep it simple, then I'd go with a web program any day.
Indeed the best advice to many programmers is to spend A LOT of time 
considering the user interface, since that's what will often have the 
major impact on user experience, and hence ultimately on acceptance.

I still moan about having to use EIGHT mouse clicks in Mozilla 1.7 to 
change my default SMTP host to the other one on a list of two. Which 
remionds me, time to check out the latest release ...

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


soappy bug with dictionary?!?

2004-12-23 Thread elsarfhem
I have a problem with soappy when i try to send a python dictionary...
i send something like this {'1':2,'3':4}
and it returns something like this {'1':[2,4], '3':4}
function on the server is simply an echo:

def echo(arg):
   return arg

i post the soap message, it may be useful...
*** Incoming HTTP headers **
POST / HTTP/1.0
Host: localhost:8081
User-agent: SOAPpy 0.11.6 (pywebsvcs.sf.net)
Content-type: text/xml; charset="UTF-8"
Content-length: 552
SOAPAction: "http://localhost:8081/a";

*** Incoming SOAP **

http://schemas.xmlsoap.org/soap/encod
ing/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/";
xmlns:xsi="http
://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.or
g/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema";>



<_x005F_x0031_ xsi:type="xsd:string">2
6
4





In build.
In dump. obj= {'Result': : {'c':
'6', 'b
': '4', '_x0031_': '2'}}
In dump_dictionary.
In dump. obj= : {'c': '6', 'b':
'4', '_x
0031_': '2'}
In dump_instance. obj= : {'c':
'6', 'b':
 '4', '_x0031_': '2'} tag= Result
In dump. obj= ['2', '6', '4']
In dump_list. obj= ['2', '6', '4']
In dump. obj= 2
In dump_string.
In dumper.
In dump. obj= 6
In dump_string.
In dumper.
In dump. obj= 4
In dump_string.
In dumper.
In dump. obj= 6
In dump_string.
In build.
In dump. obj= {'Result': : {'c':
'6', 'b
': '4', '_x0031_': '2'}}
In dump_dictionary.
In dump. obj= : {'c': '6', 'b':
'4', '_x
0031_': '2'}
In dump_instance. obj= : {'c':
'6', 'b':
 '4', '_x0031_': '2'} tag= Result
In dump. obj= : {'c': '6', 'b':
'4', '_x
0031_': '2'}
In dump_instance. obj= : {'c':
'6', 'b':
 '4', '_x0031_': '2'} tag= Result
In dump. obj= ['2', '6', '4']
In dump_list. obj= ['2', '6', '4']
In dump. obj= 6
In dump_string.
In dump. obj= 4
In dump_string.
In dump. obj= ['2', '6', '4']
In dump_list. obj= ['2', '6', '4']
In dump. obj= 2
In dump_string.
In dump. obj= 6
In dump_string.
In dump. obj= 4
In dump_string.
In dump. obj= 6
In dump_string.
In dumper.
In dump. obj= 4
In dump_string.
In dumper.
In dump. obj= 2
In dump_string.
In dumper.
*** Outgoing HTTP headers **
HTTP/1.0 200 OK
Server: http://pywebsvcs.sf.net";>SOAPpy 0.11.6 (Python
2.3.3)
Date: Thu, 23 Dec 2004 14:56:03 GMT
Content-type: text/xml; charset="UTF-8"
Content-length: 960

*** Outgoing SOAP **

http://schemas.xmlsoap.org/soap/encod
ing/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/";
xmlns:xsi="http
://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.or
g/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema";>





<_x005F_x0031_ href="#i3"/>



<_x005F_x005F_x005F_x0031_ SOAP-ENC:arrayType="xsd:string[3]"
xsi:type="SOAP-ENC
:Array" SOAP-ENC:root="0" id="i3">




6
4
2




thanks for your help

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


Re: extract news article from web

2004-12-23 Thread Steve Holden
Zhang Le wrote:
Thanks for the hint. The xml-rpc service is great, but I want some
general techniques to parse news information in the usual html pages.
Currently I'm looking at a script-based approach found at:
http://www.namo.com/products/handstory/manual/hsceditor/
User can write some simple template to extract certain fields from a
web page. Unfortunately, it is not open source, so I can not look
inside the blackbox.:-(
Zhang Le
That's a very large topic, and not one that I could claim to be expert 
on, so let's hope that others will pitch in with their favorite 
techniques. Otherwise it's down to providing individual parsers for each 
service you want to scan, and maintaining the parsers as each group of 
designers modifies their pages.

You might want to look at BeutifulSoup, which is a module for extracting 
 stuff from (possibly) irregularly-formed HTML.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: Killing a python thread with a signal

2004-12-23 Thread Philippe C. Martin
On Thu, 2004-12-23 at 04:51, James Lamanna wrote:
> So I've created a thread with the threading.Thread class, but I want to 
> be able to kill this thread because it does a select() with a timeout of 
> None.

I do not know what type of information your thread reads from the sockets, but 
I added a 'QUIT-STYLE' command in my script when I want the thread to exit so 
it wakes up.

Regards,

Philippe



-- 
*
Philippe C. Martin
SnakeCard LLC
www.snakecard.com
*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib and sites that require passwds

2004-12-23 Thread Ishwor
On 23 Dec 2004 06:46:50 -0800, Fuzzyman <[EMAIL PROTECTED]> wrote:
> damn... I'm losing my leading spaces indentation should be obvious
We'll forgive you for that. It was from "top-of-your-head" ~;-)

> anyway... (everything below except is indented at least one step).
> Fuzzy
Its nice that urllib2 returns errcode to process further. doesn't
urllib do that?
Anyway i wanted to know if any website which is similar to CPAN
library website? I mean i want to be able find modules n stuff for
Python.. It would be really great to know.

Thanks.

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


Re: list IndexError

2004-12-23 Thread Mike C. Fletcher
Fredrik Lundh wrote:
Mike C. Fletcher wrote:
 

yeah actually i saw what Fedrik had to say above. I created a sliced
copy of the l & did my homework within the for loop
 

You might want to check it again before you hand it in ;) ...
   

...
that's not the code he quoted in the mail you replied to, though...
 

Ah, my mistake, I missed the [:] after the source argument that was 
taking a copy... which brings up the question, how many other people 
would miss it?  Guess it's just a matter of how often you see the 
pattern, so you begin to expect the [:] and either look for it or take 
it for granted (hmm, another source of bugs?).

Apologies for any unnecessary alarm,
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
--
http://mail.python.org/mailman/listinfo/python-list


Switch statement (was: Lambda going out of fashion)

2004-12-23 Thread Skip Montanaro

Stephen> {
Stephen>  'one': lambda x:x.blat(),
Stephen>  'two': lambda x:x.blah(),
Stephen> }.get(someValue, lambda x:0)(someOtherValue)

One thing to remember is that function calls in Python are pretty damn
expensive.  If x.blat() or x.blah() are themselves only one or two lines of
code, you might find that your "switch" statement is better written as an
if/elif/else statement.  You're making potentially three function calls
(get(), lambda and x.blat() or x.blah()) to perform what might only be a
small handful of inline statements.  I'll ignore the readability cost of
your solution vs. an if statement.

Stephen> So, the questions I am asking are: Is this okay with everyone?

Sure.  I'll adjust.

Stephen> Does anyone else feel that lambda is useful in this kind of
Stephen> context?

It's useful in this sort of context.  It will probably always be limited to
single expressions, which will always leave it a second-class citizen in
Python.  Interestingly enough, lambda in the Lisp world has the same
limitation, however, since Lisp code is nothing but a series of
s-expressions, that's not a problem.

Stephen> Are there alternatives I have not considered?

I've never seen a situation where if/elif/else wasn't adequate or was less
clear than the many attempts at switch-like behavior.

Folks (in general), there is still an open PEP on a switch statement for
Python.  It's been idle since late 2001:

http://www.python.org/peps/pep-0275.html

It would help if interested people were to take a look at it and identify
open issues.  If you google for pep 275 you will probably find relevant
python-dev discussions from the 2001/2002 timeframe.  Thomas Wouters' patch
for the interpreter would also need to be resurrected and brought
up-to-date.  I not longer remember why the PEP stalled.

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


Improving Python (was: Lambda going out of fashion)

2004-12-23 Thread Skip Montanaro

Keith> My personal gripe is this. I think the core language, as of 2.3
Keith> or 2.4 is very good, has more features than most people will ever
Keith> use, and they (Guido, et al.) can stop tinkering with it now and
Keith> concentrate more on the standard libraries.

What keeps you from being part of the "et al"?  This is open source, after
all.  Note that there's more to be done than simply writing code.
Documentation always needs attention.  Bug reports and patches always need
to be verified and vetted.  Even mundane stuff like managing mailing lists
detracts from the time the most experienced people could spend writing code
you might not be able to do.  There's lots to do.  Start here:

http://www.python.org/dev/

Go anywhere. 

Skip

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


Re: list Integer indexing dies??

2004-12-23 Thread Antoon Pardon
Op 2004-12-23, Ishwor schreef <[EMAIL PROTECTED]>:
> On 23 Dec 2004 14:28:37 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>> Op 2004-12-23, Ishwor schreef <[EMAIL PROTECTED]>:
>> > Hi all. Look at this snippet of code.
>> >
>>  l = ['a','b','c','d']
>>  l
>> > ['a', 'b', 'c', 'd']
>>  l[0][0][0]
>> > 'a'
>> > It prints the value 'a'. Fine so far :-)
>> > l[0] ---> 'a' .
>> > l[0][0]---> 'a'[0] --> 'a'.
>> > l[0][0][0] ---> 'a'[0][0] --> 'a'[0] --> 'a'
>> >
>> > Now why doesnt this list which holds integer seem to work??
>> 
>> Because this only works with strings.
>> 
>> String is the only object in python which has an implied
>> equivallence between an element and a squence of one.
>> 
>> So one character is a string and a string is a sequence
>> of characters.
>> 
>> So 'a'[0] is again 'a' which can again be indexed by
>> 0 as many times as you want.
>
> ;-) gotcha. But shouldn't this be valid too?? 
 123232[0] 

Well if it should become valid, it should just return 123232 IMO.

> in which basically python can infer from the object type and print out
> 1 instead of coughing up those errors?

Why do you feel it should cough up 1?

Suppose I write a number in octal notation.

What should 035[0] cough up? Be carefull it should
cough up the same as 29[0].

> My experience as a learner here
> is that there should be some automagics  & say like "okay you want to
> do indexing on integers ( context dependent); i'll give you the index
> of 0th position in that integer" ???

Integers have no position. The position we think of in integers is an
artefact of our notational system. Even then if we would simply defer
to decimal notation there is still a problem. You see there are a
number of arguments that would make 123232[0] cough up 2. Because
by starting indexing from the back we get a nice correspondence between
the index of the number and the power of 10 it represents.

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


Re: Python, unix and mssql

2004-12-23 Thread Steve Holden
francisl wrote:
We have to build some script were I work to make a dynamic server 
inventory.

But, the project team, a windows crew, start it all in vbscript and on 
mssql. Note, due to political reason, we can not use mysql or anyother 
one that are not *authorize*, it's oracle or mssql. Now we have to make 
it work also with our sun and HP unix server(plus one Linux).

So I propose to use python, and after they see my litle python/wxwindow 
program, that list windows registry value relate to SUS automatic update 
and that let it remotely force a check. They were amaze on how short it 
took to make us save a lot of time. - Windows by default put a static 
value in its LastWaitTimeout key, in their doc they said 48 hrs. But 48 
hrs is to long for a good schedule on production server. Plus it give us 
headaches to validate all the update on our network. (~75 winnt/2k/2k3 
servers)

back to subject
Question.
Can we, directly from unix select and insert data in a remote mssql 
database?

if not, my second though was to put a litle python server on the server 
holding the mssql database, which will accept request and insert it in 
the database. But is that possible?

Thank you
If ODBC access is permissible then you could, for example, use mxODBC on 
top of one of the generic ODBC drivers for Unix.

Since Oracle is also an "approved" database you might also want to think 
about using the cxOracle module, which AFAIK is available on both 
Windows and Unix-like platforms.

There are several ways you could have remote Python processes talking to 
each other. Pyro is a package that would let you handle this situation 
relatively easily, and I'm sure others will chime in with their favored 
solutions.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: Keyword arguments - strange behaviour?

2004-12-23 Thread Steven Bethard
Fuzzyman wrote:
Steven Bethard wrote:
[EMAIL PROTECTED] wrote:
However, is there a good reason why default parameters aren't
evaluated as the function is called? (apart from efficiency
and backwards compatibility)?
So, one of my really common use cases that takes advantage of the
fact that default parameters are evaluated at function definition
time:
def foo(bar, baz, matcher=re.compile(r'...')):
...
text = matcher.sub(r'...', text)
...
Surely "re.compile(r'...')" is effectively a constant ? So your above
code is equivalent to :
aConst = re.compile(r'...')
def foo(bar, baz, matcher=aConst):
...
text = matcher.sub(r'...', text)
...
Basically, yes.  Though you add an extra name to the module or class 
namespace by defining 'aConst'.  I consider this a minor pollution of 
the namespace since 'matcher' is only used in the function, not the 
module or class.

But if we're arguing for equivalencies, the oft-asked for
def foo(lst=[]):
...
where [] is evaluated for each function call, is equivalent for most 
purposes to:

def foo(lst=None):
if lst is None:
lst = []
There's a minor pollution of the range of values 'lst' can take on -- if 
you need lst to be able to take on the value None, you'll want to 
rewrite this something like:

no_value = object()
def foo(lst=no_value):
if lst is no_value:
lst = []
My point here is that there's always going to be some equivalent 
expression (turing completeness etc.)  I was just pointing out a quite 
reasonable use of the current default parameter evaluation system.

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


Re: Python for Series 60 update

2004-12-23 Thread Tim Hoffman
HI
Jukka Laurila wrote:
On Thu, 23 Dec 2004 06:52:28 +0800, Tim Hoffman <[EMAIL PROTECTED]> wrote:

I did find a problem with it on my 7610.

It works, but I had to hard code my bluetooth mac address (I assume
thats what it is called in bluetooth).  The bt_discover() call
didn't seem to find my host.

How did it fail? Did it simply not show your computer in the list or
did it hang indefinitely when connecting to it? Bluetooth discovery
has always been problematic, but connecting to a host directly using
the mac address has worked perfectly for months now. (I am one of the
developers in this project.)

It always came back saying there where no bluetooth devices around.
Interestingly if I then ran ControlFreak (bluetooth remote control for 
Winamp) it would connect to the HyperTerm that was still running.

So I am at a bit of a loss as to why the bt_discover call never found
the host
Also normal sync type operations where working fine (as in install apps
etc)
I will try again on the discover but connecting to the host directly is
enough for me at the moment.
Tim
Try doing the discovery again. Sometimes the phone just magically
discovers hosts it did not see ten seconds earlier. The discovery will
also fail if there already is a Bluetooth connection open, for example
the PC Suite can leave connections open that mess up the
discovery. You can force all connections to be terminated by turning
bluetooth on and off from the phone menu.

from the console I could immediatly do xml-rpc calls
to my favourite Zope/CMF instance over GPRS and it just worked.
This is cool.

Yes, very :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: mathmatical expressions evaluation

2004-12-23 Thread Tonino
yes - this is what I have been doing - created a set of functions to
handle the formula and they all calculate a section of the formula.
Thanks for all the help ;)
Tonino

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


Re: odbc for solid

2004-12-23 Thread Steve Holden
flupke wrote:
Hi,
at work we use a solid database and i need to develop an application 
that accesses it. Problem is the drivers: i only have some dll's lying 
around and jar.
On winsdows i could get by by using ODBC and the dll's to access the 
solid database but i want to eventually run it on a linux server.
Solid doesn't seem to have a driver specifically for Linux so i'm stuck 
here. Is there any way i can still use Linux and have access to solid?
Maybe i need to revert to jython so i can use the jar?

This might be of interest (and also possibly of relevance to an earlier 
query about accessing MS SQL Server from Unix in the "Python, unix and 
mssql" thread):

  http://sourceforge.net/projects/pyodb
"""PyODB is an ODBC Python module to provide an quick an easy way to 
work with databases. It provides a small set of simplified bindings to 
the unixODBC API and has been developed using SWIG."

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: extract news article from web

2004-12-23 Thread Fuzzyman
If you have a reliably structured page, then you can write a custom
parser. As Steve points out - BeautifulSOup would be a very good place
to start.

This is the problem that RSS was designed to solve. Many newssites will
supply exactly the information you want as an RSS feed. You should then
use Universal Feed Parser to process the feed.

The module you need for fecthing the webpages (in case you didn't know)
is urllib2. There is a great article on fetching webpages in the
current issue of pyzine. See http://www.pyzine.com :-)
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: Why are tuples immutable?

2004-12-23 Thread Antoon Pardon
Op 2004-12-23, Scott David Daniels schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>> Op 2004-12-22, Jeff Shannon schreef <[EMAIL PROTECTED]>:
>>>The problem is that once the object has mutated, you *don't know* what 
>>>bucket it used to sort into.  There is no point at which a dictionary 
>>>can see "before" and "after" -- it just sees two different lists.
>
> This is half the problem.  In the period where an element is in the
> wrong hash bucket, a new entry for the same value can be created in
> the proper hash bucket.  Then the code will have to determine how to
> merge two entries at rehash time.

But similar problems can happen in a sorted list, where the sort
is done on a "key" of the data and where you don't want duplicate
"keys".

If you then mutate a "key", it may be possible to insert a duplicate
"key" in the sorted list because the list isn't sorted anymore. If
you then resort your list you also have to determine how to merge
the two items with the same "key"


This just to show that repairing sorted lists can be just as
troublesome as repairing dictionaries. People who think 
sorted lists of mutable objects is less bothersome as dictionaries
with mutable keys, haven't thought things through IMO.

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


Re: Lambda going out of fashion

2004-12-23 Thread Skip Montanaro

Craig> IMO the reference behaviour of functions in the C API could be
Craig> clearer. One often has to simply know, or refer to the docs, to
Craig> tell whether a particular call steals a reference or is reference
Craig> neutral.  Take, for example, PyDict_SetItemString vs
Craig> PyMapping_SetItemString . Is it obvious that one of those steals
Craig> a reference, and one is reference neutral? Is there any obvious
Craig> rationale behind this? 

Sure.  PyDict_SetItemString was first written very early on in Python's
development (actually, it was originally called something
namespace-ly-dangerous like dict_setstring).  PyMapping_SetItemString (part
of the abstract objects api) was written later with an emphasis on the
consistency of behavior you desire.  You're generally going to be better off
sticking with the abstract objects api.  For obvious reasons of backward
compatibility, the concrete apis (PyDict_*, PyList_*, etc) must be retained.

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


Re: list IndexError

2004-12-23 Thread Steven Bethard
Steven Bethard wrote:
Ishwor wrote:
i am trying to remove an item 'e' from the list l

I thought it might be helpful to code some of the alternatives you've 
been given and look at the timings to put things into perspective.
Corrected timings[1] using:
$ python -m timeit -s "import remove" "remove.remove_(500, [x % 
1000 for x in xrange(1)])"

remove_xrange: 5.46 msec per loop
remove_lc: 5.48 msec per loop
remove_try:6.31 msec per loop
remove_ishwor: 7.03 msec per loop
remove_list:   8.38 msec per loop
remove_filter: 9.08 msec per loop
remove_remove: 9.98 msec per loop
and using:
$ python -m timeit -s "import remove" "remove.remove_(50, [x % 100 
for x in xrange(1)])"

remove_lc:  5.12 msec per loop
remove_xrange:  5.8  msec per loop
remove_list:7.9  msec per loop
remove_filter:  8.29 msec per loop
remove_try:30.3  msec per loop
remove_ishwor: 30.7  msec per loop
remove_remove: 55.2  msec per loop
So, when timed correctly =) list comprehensions and xrange are faster 
even when the items to be removed are only 0.1% of the data.

Steve
[1] Thanks Peter!
P.S.  For fun, I played around with the data to see if I could find a 
dataset on which one of the "slower" techniques is faster than remove_lc 
or remove_xrange.  Here's one:

$ python -m timeit -s "import remove" "remove.remove_(25, [x % 50 
for x in xrange(100)])"

remove_remove: 53.3 usec per loop
remove_xrange: 57.7 usec per loop
remove_try:58.8 usec per loop
remove_ishwor: 58.9 usec per loop
remove_lc: 65.4 usec per loop
remove_list:   93.7 usec per loop
remove_filter: 95.8 usec per loop
--
http://mail.python.org/mailman/listinfo/python-list


Re: Keyword arguments - strange behaviour?

2004-12-23 Thread Fuzzyman

Steven Bethard wrote:
> Fuzzyman wrote:
> > Steven Bethard wrote:
> >
> >>[EMAIL PROTECTED] wrote:
> >>
> >>>However, is there a good reason why default parameters aren't
> >>>evaluated as the function is called? (apart from efficiency
> >>>and backwards compatibility)?
> >>
> >>So, one of my really common use cases that takes advantage of the
> >>fact that default parameters are evaluated at function definition
> >>time:
> >>
> >>def foo(bar, baz, matcher=re.compile(r'...')):
> >> ...
> >> text = matcher.sub(r'...', text)
> >> ...
> >
> > Surely "re.compile(r'...')" is effectively a constant ? So your
above
> > code is equivalent to :
> >
> > aConst = re.compile(r'...')
> > def foo(bar, baz, matcher=aConst):
> > ...
> > text = matcher.sub(r'...', text)
> > ...
>
> Basically, yes.  Though you add an extra name to the module or class
> namespace by defining 'aConst'.  I consider this a minor pollution of

> the namespace since 'matcher' is only used in the function, not the
> module or class.
>
> But if we're arguing for equivalencies, the oft-asked for
>
> def foo(lst=[]):
>  ...
>
> where [] is evaluated for each function call, is equivalent for most
> purposes to:
>
> def foo(lst=None):
>  if lst is None:
>  lst = []
>
> There's a minor pollution of the range of values 'lst' can take on --
if
> you need lst to be able to take on the value None, you'll want to
> rewrite this something like:
>
> no_value = object()
> def foo(lst=no_value):
>  if lst is no_value:
>  lst = []
>
> My point here is that there's always going to be some equivalent
> expression (turing completeness etc.)  I was just pointing out a
quite
> reasonable use of the current default parameter evaluation system.
>
> Steve

Sure.. but you also gave an example of an alternative that was complex,
and used it's complexity as an argument against having default
arguments dynamically evaluated. What I was saying is that there is an
alternative that is at least as readable (if not more) than your
example.

Having default arguments evaluated when the function is defined is
unintuitive and unpythonic.
Regards,


Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: odbc for solid

2004-12-23 Thread flupke
> Steve Holden wrote:
This might be of interest (and also possibly of relevance to an earlier 
query about accessing MS SQL Server from Unix in the "Python, unix and 
mssql" thread):

  http://sourceforge.net/projects/pyodb
"""PyODB is an ODBC Python module to provide an quick an easy way to 
work with databases. It provides a small set of simplified bindings to 
the unixODBC API and has been developed using SWIG."

regards
 Steve
Thanks Steve, i'll check the link
Benedict
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-23 Thread Skip Montanaro

>> readability. Pythonic lambdas are just syntactic sugar in practice,

Paul> Actually it's the other way around: it's named functions that are
Paul> the syntactic sugar.

While I'm sure it can be done, I'd hate to see a non-trivial Python program
written with lambda instead of def.  (Take a crack at pystone if you're
interested.)

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


Re: Python, unix and mssql

2004-12-23 Thread Scott David Daniels
francisl wrote:
Can we, directly from unix select and insert data in a remote mssql 
database?

In some sense you can.  I used python and mxODBC to talk ODBC protocol
to DB2 / MS SqlServer / Access.  It was quite a while ago, and I may
have had to use an odbc-on-linux piece I don't know about.  But the
upshot was that my (large, data and CPU-intensive) program ran portably
on both Win2K and Linux.  The mxODBC solution will cost money, but not
a lot (and MAL has done a great job letting you discover things about
the far end of the ODBC connection -- development is simple).  The
switch between databases was really minimal effort on my part -- the
sysadmin who had to create and backup the DBs was not as sanguine about 
the changes.  Check with Marc-Andre about the current state of the art
for linux ODBC drivers.

if not, my second though was to put a litle python server on the server 
holding the mssql database, which will accept request and insert it in 
the database. But is that possible?
This is also easy, and you can simply design a little socket watcher to
get commands, execute them, and return results.
Thank you
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question - default values of a function

2004-12-23 Thread Steve Holden
Bulba! wrote:
Thanks everyone (esp. Fredrik, http://www.effbot.org/zone/index.htm
contains lotsa goodies by him I intend to study), I'm going offline to
reboot my  brain. ;-) 

Bulba, with reference to your "don't laugh" comment, I'd just like to 
say that for a newbie your questions do have a habit of getting to the 
nub of what Python's about. I can see you're going to like this language.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: list IndexError

2004-12-23 Thread Steve Holden
M.E.Farmer wrote:
Hello Ishwor ,
The simpliest way I can explain slicing is that the slices point to the
spot *between* the items..
Take this list for example
slicer =  [0,1,2,3,4,5]
slicer [1]
1
slicer [1:2]
[1]
slicer [:-1]
 [0,1,2,3,4] 

slicer[2,4]
[2,3]
You can also use a "stride" rather than take every element and (in 
recent Pythons) go backwards:

Python 2.4 (#1, Dec  4 2004, 20:10:33)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> slicer = [0,1,2,3,4]
 >>> slicer[::2]
[0, 2, 4]
 >>> slicer[1::2]
[1, 3]
 >>> >>> slicer[::-1]
[4, 3, 2, 1, 0]
 >>> slicer[-1::-2]
[4, 2, 0]
 >>>
regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Unicode entries on sys.path

2004-12-23 Thread Thomas Heller
I was trying to track down a bug in py2exe where the executable did
not work when it is in a directory containing japanese characters.

Then, I discovered that part of the problem is in the zipimporter that
py2exe uses, and finally I found that it didn't even work in Python
itself.

If the entry in sys.path contains normal western characters, umlauts for
example, it works fine.  But when I copied some japanese characters from
a random web page, and named a directory after that, it didn't work any
longer.

The windows command prompt is not able to print these characters,
although windows explorer has no problems showing them.

Here's the script, the subdirectory contains the file 'somemodule.py',
but importing this fails:

  import sys
  sys.path = [u'\u5b66\u6821\u30c7xx']
  print sys.path

  import somemodule

It seems that Python itself converts unicode entries in sys.path to
normal strings using windows default conversion rules - is this a
problem that I can fix by changing some regional setting on my machine?

Hm, maybe more a windows question than a python question...

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


  1   2   3   >