soap request includes a hyphenated field, don't know how to set it

2009-03-27 Thread straycat000
I'm trying to use suds to create a SOAP request.  The request includes
a hyphenated field.  Python won't let me set to hyphenated variables.
Is there a way around this?  Don't tell me to use an underscore
because the SOAP server won't recognize it.

The request is supposed to look like this:

http://schemas.xmlsoap.org/soap/
envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema";
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";>
  

  164-251340-2009-03-12
  LIVE_EVENT_COVERAGE

  


Working my way through suds, I have something like this:

>>> event = client.factory.create('ns0:UserVerifiedEvent')
>>> print event
(UserVerifiedEvent){
   event-id = None
   user-verified-content[] = 
   domain-specific-attributes =
  (MediaAttributes){
 domain-attribute[] = 
  }
 }
>>> event.event-id = "164-251340-2009-03-12"
SyntaxError: can't assign to operator

And there's my problem.  I don't know how to set event-id within the
UserVerifiedEvent because of that hyphen.

For anyone who knows suds and SOAP, here's the wsdl to get you this
far:

>>> import suds
>>> from suds.client import Client
>>> url = 'http://www.mlb.com/flash/mediaplayer/v4/wsdl/MediaService.wsdl'
>>> client = Client(url)

Any ideas or python magic to get around this hyphen problem (and I
can't change that to event_id or the server won't recognize it.)

Thanks,
Matthew

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


Re: Style question - defining immutable class data members

2009-03-27 Thread Steve Holden
John Posner wrote:
> [snip]
>  >> > If the object is a class instance and the attribute reference
> occurs
>  >> > on both sides of the assignment operator; for example::
>  >> > 
>  >> > self.x = self.x + 1
>  >> >
>  >> > ... in the RHS expression, ``self.x`` is evaluated with 
>  >> > ``getattr()``, which can access either an instance attribute or
> (if 
>  >> > no instance attribute exists) a class attribute. The LHS target 
>  >> > ``self.x`` is assigned with ``setattr()``, which *always* accesses
> 
>  >> > an instance attribute, creating it if necessary. Thus, the two 
> 
> Steve Holden said: 
> 
>  >> Is this true in the case of read-write properties? This 
>  >> seems a little
>  >> simplistic for what's actually a pretty complex piece of logic.
> 
> It's not true for the read-write property example in the official property()
> function description:
> 
> class C(object):
> def __init__(self):
> self._x = None
> 
> def getx(self):
> return self._x
> def setx(self, value):
> self._x = value
> def delx(self):
> del self._x
> x = property(getx, setx, delx, "I'm the 'x' property.")
> 
> 
> But it *is* true if you revise this class definition to follow the pattern
> under discussion: a class attribute provides the "initial value" of an
> instance attribute:
> 
> class C(object):
> _x = 0
> 
> def __init__(self):
> pass
> def getx(self):
> return self._x
> def setx(self, value):
> self._x = value
> x = property(getx, setx)
> 
> 
> My intent was to fix an obvious omission: a special case was discussed in
> the "Augmented assignment statements" section, but an almost-identical
> special case was omitted from the "Assignment statements" section.
> 
> Neither section currently mentions property attributes. Do you think both
> sections should be changed to cover property attributes? Or maybe it would
> be simpler just to revise my first sentence:
> 
>   from: If the object is a class instance
> to: If the object is a (non-property) class instance
> 
That amendment would probably be least confusing to new readers, though
it would help when in hypermedia to link "property" to some discussion
of properties as they apply on the various Python versions.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/

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


Re: soap request includes a hyphenated field, don't know how to set it

2009-03-27 Thread Justin Ezequiel
On Mar 27, 3:33 pm, straycat...@yahoo.com wrote:
> Working my way through suds, I have something like this:
>
> >>> event = client.factory.create('ns0:UserVerifiedEvent')
> >>> print event
>
> (UserVerifiedEvent){
>    event-id = None
>    user-verified-content[] = 
>    domain-specific-attributes =
>       (MediaAttributes){
>          domain-attribute[] = 
>       }
>  }
> >>> event.event-id = "164-251340-2009-03-12"
>
> SyntaxError: can't assign to operator
>
> Any ideas or python magic to get around this hyphen problem (and I
> can't change that to event_id or the server won't recognize it.)
>
> Thanks,
> Matthew

haven't tried suds but perhaps you can try

setattr(event, "event-id", "164-251340-2009-03-12")


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


Re: soap request includes a hyphenated field, don't know how to set it

2009-03-27 Thread straycat000
On Mar 27, 1:15 am, Justin Ezequiel 
wrote:
> On Mar 27, 3:33 pm, straycat...@yahoo.com wrote:
>
>
>
> > Working my way through suds, I have something like this:
>
> > >>> event = client.factory.create('ns0:UserVerifiedEvent')
> > >>> print event
>
> > (UserVerifiedEvent){
> >    event-id = None
> >    user-verified-content[] = 
> >    domain-specific-attributes =
> >       (MediaAttributes){
> >          domain-attribute[] = 
> >       }
> >  }
> > >>> event.event-id = "164-251340-2009-03-12"
>
> > SyntaxError: can't assign to operator
>
> > Any ideas or python magic to get around this hyphen problem (and I
> > can't change that to event_id or the server won't recognize it.)
>
> > Thanks,
> > Matthew
>
> haven't tried suds but perhaps you can try
>
> setattr(event, "event-id", "164-251340-2009-03-12")

That did it!

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


modifying a list element from a function

2009-03-27 Thread TP
Hi everybody,

Be a the following list, containing list elements which second field is a
string.

>>> a = [ [4, "toto"], [5, "cou"] ]
>>> a[0][1]="tou"
>>> a
[[4, 'tou'], [5, 'cou']]

OK.

Now, I want:
* to do the same modification on the list "a" within a function
* not to hardcode in this function the position of the string in each
element of a.

At first sight, we think at defining a function like this:

def assign( text_accessor, list_elem, new_textvalue ):

text_accessor( list_elem ) = new_textvalue

and then doing:

assign( lambda elem: elem[1], a[0], "co" )

But it does not work, we obtain:

text_accessor( list_elem ) = new_textvalue
SyntaxError: can't assign to function call

In fact, we should work on the address of text_accessor( list_elem ). How to
do that?

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Debugging in Py

2009-03-27 Thread Lawson English

Jeremiah Dodds wrote:



On Wed, Mar 25, 2009 at 9:25 PM, *nixtechno > wrote:


Big thanks tkc, and I was wondering what your thoughts are on logging
module: http://docs.python.org/library/logging.html

"Instead of using many print statements for debugging, use
logger.debug: Unlike the print statements, which you will have to
delete or comment out later, the logger.debug statements can remain
intact in the source code and remain dormant until you need them
again. At that time, the only change that needs to happen is to modify
the severity level of the logger and/or handler to debug."

Where it makes sense as they state using this rather than printing,
due to the fact that you don't have to strip it all out when it's time
to release your work... I seen some writing on pdb, but I guess it's
time to study up on it. I appreciate the help.
--
http://mail.python.org/mailman/listinfo/python-list


I really like the logging module.  From the perspective of what you're 
writing while you're working on part of an application, it tends to 
not be that different that dropping print statements in, but there's a 
wealth of flexibility and customizability available to you on the high 
level.


For instance, I use it at work for one of our applications, and it 
emails me whenever certain types of events occur that I need to know 
about. It might be overkill for small projects, but it's definately 
worth getting to know.


  
You can also redirect the logger output to various places like wx text 
controls if you use the model
that wxPython itself uses to redirect print statements to its debug 
console window. There's no end to
how you can use logger output if you work things this way since logger 
refines its output based on a

hierarchical namespace that you can modify from any point in runtime.

E.G. direct errors and other text output  from .THIS namespace logger to 
.THIS text window or scrolling

list or  logger file (or all of the above).


Lawson

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


Re: Threading and tkinter

2009-03-27 Thread Eric Brunel
(Sorry: replying to the wrong message here, but my newsreader somehow managed
to miss the former post...)

> On Mar 7, 9:40 am, Jani Hakala  wrote:
>> > After reading the docs and seeing a few examples i think this should
>> > work ?
>> > Am I forgetting something here or am I doing something stupid ?
>> > Anyway I see my yellow screen, that has to count for something :)
>>
>> I have been using the following scheme:
>>   - Pass the root object to the thread object when creating the object
>>   - Define a event_handler: root.bind('<>', evt_handler) in
>>     the main thread.
>>
>>   - When the thread has done something that the GUI part should now
>>     about, signal an event in the thread:
>>         root.event_generate('<>')    (no other arguments)
>>
>>   - Call a method of the thread object in the event handler e.g. to get
>>     some data from a queue object.
>>
>> This ensures that only the main thread accesses Tkinter-related things.

Are you sure about that? Last time I check, doing:
root.event_generate('<>')
without any other argument called the binding directly, in the context where
it is done, so in the secondary thread. To actually switch to the thread where
the bind was done, you had to do:
root.event_generate('<>', when='tail')
to force the event to get into the event queue... Maybe it has changed in the
latest tcl/tk version (I checked this quite a long time ago on tcl/tk 8.3).


BTW, with the newer tcl/tk versions this time, be sure to compile them with
thread support ('configure ... --enebale-threads' on Unices and 'nmake ...
OPTS=threads' on Windows) if you plan to do such things. We had a lot of
problems with this trick on a tcl/tk 8.5 version not compiled with thread
support, especially when a lot of events happened in a very short time:
crashes, weird errors apparently caused by memory corruption, and so on...
--
http://mail.python.org/mailman/listinfo/python-list


Re: split string at commas respecting quotes when string not in csv format

2009-03-27 Thread Tim Chase

 >>> import re
 >>> s = """a=1,b="0234,)#($)@", k="7" """
 >>> rx = re.compile(r'[ ]*(\w+)=([^",]+|"[^"]*")[ ]*(?:,|$)')
 >>> rx.findall(s)
 [('a', '1'), ('b', '"0234,)#($)@"'), ('k', '"7"')]
 >>> rx.findall('a=1, *DODGY*SYNTAX* b=2')
 [('a', '1'), ('b', '2')]
 >>>


I'm going to save this one and study it, too.  I'd like to learn
to use regexes better, even if I do try to avoid them when possible :)


This regexp is fairly close to the one I used, but I employed the 
re.VERBOSE flag to split it out for readability.  The above 
breaks down as


 [ ]*   # optional whitespace, traditionally "\s*"
 (\w+)  # tag the variable name as one or more "word" chars
 =  # the literal equals sign
 (  # tag the value
 [^",]+ # one or more non-[quote/comma] chars
 |  # or
 "[^"]*"# quotes around a bunch of non-quote chars
 )  # end of the value being tagged
 [ ]*   # same as previously, optional whitespace  ("\s*")
 (?:# a non-capturing group (why?)
 ,  # a literal comma
 |  # or
 $  # the end-of-line/string
 )  # end of the non-capturing group

Hope this helps,

-tkc


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


control device via USB or Parallel

2009-03-27 Thread alejandro
Some guy will make switches that can be controlled via USB or parallel, he 
told me that I can chose which connection I want. So, are there any modules 
for Python that will allow me to control some switches via USB or parallel? 


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


Re: Async serial communication/threads sharing data

2009-03-27 Thread JanC
Jean-Paul Calderone wrote:

>  These days, serial ports are on the way out, I think.

I don't see generic USB and bluetooth serial devices disappear that fast...

E.g. AFAIK (almost?) all GPS receivers have to be accessed as serial
devices (mine even looks like a generic USB-to-serial device to the kernel).


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


please include python26_d.lib in the installer

2009-03-27 Thread Compie
I get this linker error
LINK : fatal error LNK1104: cannot open file 'python26_d.lib'
when I build the debug version of my Visual Studio project.

This is caused by the following lines in the file c:\Python26\include
\pyconfig.h
#   ifdef _DEBUG
#   pragma comment(lib,"python26_d.lib")
#   else
#   pragma comment(lib,"python26.lib")
#   endif /* _DEBUG */

The file python26_d.lib is not installed by the Python installer on
Windows.

So please:
1. Provide python26_d.lib in the installer.
or
2. Remove this automatic "pragma comment lib" from pyconfig.h, since I
can't disable it from the outside (as far as I know).

Please note: I want to build my own code in Debug mode for debugging.
I don't want to build or use the debug version of Python. I also can't
#undef _DEBUG, since the file that includes pyconfig.h (via Python.h)
is generated by SWIG. Also I prefer not to change pyconfig.h myself,
since my code needs to compile on a lot of different machines.
--
http://mail.python.org/mailman/listinfo/python-list


Re: modifying a list element from a function

2009-03-27 Thread Peter Otten
TP wrote:

> Hi everybody,
> 
> Be a the following list, containing list elements which second field is a
> string.
> 
 a = [ [4, "toto"], [5, "cou"] ]
 a[0][1]="tou"
 a
> [[4, 'tou'], [5, 'cou']]
> 
> OK.
> 
> Now, I want:
> * to do the same modification on the list "a" within a function
> * not to hardcode in this function the position of the string in each
> element of a.
> 
> At first sight, we think at defining a function like this:
> 
> def assign( text_accessor, list_elem, new_textvalue ):
> 
> text_accessor( list_elem ) = new_textvalue
> 
> and then doing:
> 
> assign( lambda elem: elem[1], a[0], "co" )
> 
> But it does not work, we obtain:
> 
> text_accessor( list_elem ) = new_textvalue
> SyntaxError: can't assign to function call
> 
> In fact, we should work on the address of text_accessor( list_elem ). How
> to do that?

You can understand Python to some extend if you liken its variables to
pointers, but here the analogy breaks: you cannot have pointers to
pointers. To parameterize list item access you can either pass the index or
a setter (and if needed a getter) function:

>>> a = [ [4, "toto"], [5, "cou"] ]
>>> def assign(setitem_n, items, value):
... setitem_n(items, value)
...
>>> def setitem1(items, value):
... items[1] = value
...
>>> assign(setitem1, a[0], "XX")
>>> a
[[4, 'XX'], [5, 'cou']]

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


Re: modifying a list element from a function

2009-03-27 Thread Kent

> * to do the same modification on the list "a" within a function
> * not to hardcode in this function the position of the string in each


>>> a = [ [4, "toto"], [5, "cou"] ]
>>> def assign(element,pos,newValue):
... element[pos]=newValue
...
>>> assign(a[0],1,'xxx')
>>> print a
[[4, 'xxx'], [5, 'cou']]
>>>

does it fit the requirement?
--
http://mail.python.org/mailman/listinfo/python-list


Re: C extension using GSL

2009-03-27 Thread sturlamolden
On Mar 27, 7:10 am, jesse  wrote:

> I give up. I cannot find my memory leak!

That's the penalty for using the Python C API.

http://www.cython.org

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


Re: dict view to list

2009-03-27 Thread alex23
On Mar 27, 3:44 pm, Aaron Brady  wrote:
> Is there a possibility of the dict_values, dict_items, and dict_keys
> objects growing a 'tolist' method?  It's one of those little things
> that contributes to one's user experience.

Probably not, because the Python approach is to use the builtins. I'm
not sure what you feel mydict.values().tolist() might offer over the
conventional list(mydict.values()).

So yeah, -1.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Characters aren't displayed correctly

2009-03-27 Thread J. Clifford Dyer
On Mon, 2009-03-02 at 06:16 -0800, Hussein B wrote:
> On Mar 2, 4:03 pm, "J. Clifford Dyer"  wrote:
> > On Mon, 2009-03-02 at 00:33 -0800, Hussein B wrote:
> > > On Mar 1, 11:27 pm, "J. Clifford Dyer"  wrote:
> > > > On Sun, 2009-03-01 at 09:51 -0500, Philip Semanchuk wrote:
> > > > > On Mar 1, 2009, at 8:31 AM, Hussein B wrote:
> >
> > > > > > Hey,
> > > > > > I'm retrieving records from MySQL database that contains non english
> > > > > > characters.
> > > > > > Then I create a String that contains HTML markup and column values
> > > > > > from the previous result set.
> > > > > > +
> > > > > > markup = u'''.'''
> > > > > > for row in rows:
> > > > > > markup = markup + '' + row['id']
> > > > > > markup = markup + '
> > > > > > +
> > > > > > Then I'm sending the email according to this tip:
> > > > > >http://code.activestate.com/recipes/473810/
> > > > > > Well, the email contains ? characters for each non english ones.
> > > > > > Any ideas?
> >
> > > > > There's so many places where this could go wrong and you haven't  
> > > > > narrowed down the problem.
> >
> > > > > Are the characters stored in the database correctly?
> >
> > > > > Are they stored consistently (i.e. all using the same encoding, not  
> > > > > some using utf-8 and others using iso-8859-1)?
> >
> > > > > What are you getting out of the database? Is it being converted to  
> > > > > Unicode correctly, or at all?
> >
> > > > > Are you sure that the program you're using to view the email  
> > > > > understands the encoding?
> >
> > > > > Isolate those questions one at a time. Add some debugging 
> > > > > breakpoints.  
> > > > > Ensure that you have what you think you have. You might not fix your  
> > > > > problem, but you will make it much smaller and more specific.
> >
> > > > > Good luck
> > > > > Philip
> >
> > > > Let me add to that checklist:
> >
> > > > Are you sure the email you are creating has the encoding declared
> > > > properly in the headers?
> >
> > > > Cheers,
> > > > Cliff
> >
> > > My HTML markup contains only table tags (you know, table, tr and td)
> >
> > Ah.  The issue is not with the HTML markup, but the email headers.  For
> > example, the email you sent me has a header that says:
> >
> > Content-type: text/plain; charset="iso-8859-1"
> >
> > Guessing from the recipe you linked to, you probably need something
> > like:
> >
> > msgRoot['Content-type'] = 'text/plain; charset="utf-16"'
> >
> > replacing utf-16 with whatever encoding you have encoded your email
> > with.
> >
> > Or it may be that the header has to be attached to the individual mime
> > parts.  I'm not as familiar with MIME.
> >
> > Cheers,
> > Cliff
> 
> Hey Cliff,
> I tried your tip and I still get the same thing (?)
> I added print statement to print each value of the result set into the
> console, which also prints  characters instead of the real
> characters values.
> Maybe a conversion is happened upon getting the data from the
> database?
> (the values are stored correctly in the database)

Sorry for responding so late.

Getting ? characters when you print to the console does not
*necessarily* mean python is doing anything wrong.  It may be outputting
the correct characters, but your console lacks the proper font for
displaying those characters.  Try doing for c in email_body: print
hex(ord(c)), and see if the results correspond to what you're trying to
get.

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

Cheers,
Cliff


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


Re: modifying a list element from a function

2009-03-27 Thread Adrian Dziubek
Could you explain your high level goal for this? It looks like a very
wicked way of doing things. Have You tried to read the list methods'
documentation? Maybe there you find something you need (like
list.index)?
-- 
Adrian
--
http://mail.python.org/mailman/listinfo/python-list


Re: imported module scitools not recognized

2009-03-27 Thread martine de vos

Thanks for your help and explanation.
I am now able to use modules from scitools.

Martine

On 26 mrt, 21:39, Terry Reedy  wrote:
> Robert Kern wrote:
> > On 2009-03-26 10:42, mgdevos wrote:
> >> Hi all,
>
> >> I have installed thescitoolsmodule but modules included inscitools,
> >> for example numpyutils, are not recognized.
> >> Python is able to importscitools, andscitoolsis recognized in my
> >> editor (Pydev for Eclipse 1.4.4) as autocompletion works well.
> >> However, when I try to run a test script:
>
> >> importscitools
>
> scitoolsis a package (on disk, a directory).  When you import it as a
> module, the module object is created by executingscitools.__init__.py.
>   If that file is empty, so will be the module created from it.  Try
> print(dir(scitools)) to see.
>
> >> print "Sequence is: ",scitools.numpyutils.seq(0,10,1)
>
> >> I get an error: "AttributeError: 'module' object has no attribute
> >> 'numpyutils'"
>
> In fact, I suspectscitoolshas no attributes other that the default
> module attributes.
>
> >> I assume that installation ofscitools( version 0.4 using the windows
> >> installer) was succesful asscitoolsis added to my python libs: D:
> >> \Programs\python_enthought2.5.2001\Lib\site-packages\scitools
>
> You can always check thescitoolsdirectory to see that it has the
> contents you expect.  In particular, you can look at its __init__.py
> file to see what it will have on import.
>
> >> I added the path toscitoolsto my pthonpath and even added all three
> >> modules to forced-builtins, but still I get the same error message.
>
> >> Could you please help me solving this problem?
>
> > fromscitoolsimport numpyutils
> > print 'Sequence is: ', numpyutils.seq(0,10,1)
>
> I believe you could also do
>
> importscitools.numpyutils
> print "Sequence is: ",scitools.numpyutils.seq(0,10,1)
>
> but it is usually more convenient to do the 'import from' so you do not
> have to repeat the full dotted name sequence.
>
> Terry Jan Reedy

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


Re: split string at commas respecting quotes when string not in csv format

2009-03-27 Thread John Machin
On Mar 27, 9:19 pm, Tim Chase  wrote:
> >>  >>> import re
> >>  >>> s = """a=1,b="0234,)#($)@", k="7" """
> >>  >>> rx = re.compile(r'[ ]*(\w+)=([^",]+|"[^"]*")[ ]*(?:,|$)')
> >>  >>> rx.findall(s)
> >>  [('a', '1'), ('b', '"0234,)#($)@"'), ('k', '"7"')]
> >>  >>> rx.findall('a=1, *DODGY*SYNTAX* b=2')
> >>  [('a', '1'), ('b', '2')]
>
> > I'm going to save this one and study it, too.  I'd like to learn
> > to use regexes better, even if I do try to avoid them when possible :)
>
> This regexp is fairly close to the one I used, but I employed the
> re.VERBOSE flag to split it out for readability.  The above
> breaks down as
>
>   [ ]*       # optional whitespace, traditionally "\s*"

No, it's optional space characters -- T'd regard any other type of
whitespace there as a stuff-up.

>   (\w+)      # tag the variable name as one or more "word" chars
>   =          # the literal equals sign
>   (          # tag the value
>   [^",]+     # one or more non-[quote/comma] chars
>   |          # or
>   "[^"]*"    # quotes around a bunch of non-quote chars
>   )          # end of the value being tagged
>   [ ]*       # same as previously, optional whitespace  ("\s*")

same correction as previously

>   (?:        # a non-capturing group (why?)

a group because I couldn't be bothered thinking too hard about the
precedence of the | operator, and non-capturing because the OP didn't
want it captured.

>   ,          # a literal comma
>   |          # or
>   $          # the end-of-line/string
>   )          # end of the non-capturing group
>
> Hope this helps,

Me too :-)

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


Re: split string at commas respecting quotes when string not in csv format

2009-03-27 Thread Paul McGuire
On Mar 27, 5:19 am, Tim Chase  wrote:
> >>  >>> import re
> >>  >>> s = """a=1,b="0234,)#($)@", k="7" """
> >>  >>> rx = re.compile(r'[ ]*(\w+)=([^",]+|"[^"]*")[ ]*(?:,|$)')
> >>  >>> rx.findall(s)
> >>  [('a', '1'), ('b', '"0234,)#($)@"'), ('k', '"7"')]
> >>  >>> rx.findall('a=1, *DODGY*SYNTAX* b=2')
> >>  [('a', '1'), ('b', '2')]
>
> > I'm going to save this one and study it, too.  I'd like to learn
> > to use regexes better, even if I do try to avoid them when possible :)
>
> This regexp is fairly close to the one I used, but I employed the
> re.VERBOSE flag to split it out for readability.  The above
> breaks down as
>
>   [ ]*       # optional whitespace, traditionally "\s*"
>   (\w+)      # tag the variable name as one or more "word" chars
>   =          # the literal equals sign
>   (          # tag the value
>   [^",]+     # one or more non-[quote/comma] chars
>   |          # or
>   "[^"]*"    # quotes around a bunch of non-quote chars
>   )          # end of the value being tagged
>   [ ]*       # same as previously, optional whitespace  ("\s*")
>   (?:        # a non-capturing group (why?)
>   ,          # a literal comma
>   |          # or
>   $          # the end-of-line/string
>   )          # end of the non-capturing group
>
> Hope this helps,
>
> -tkc

Mightent there be whitespace on either side of the '=' sign?  And if
you are using findall, why is the bit with the delimiting commas or
end of line/string necessary?  I should think findall would just skip
over this stuff, like it skips over *DODGY*SYNTAX* in your example.

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


Re: dict view to list

2009-03-27 Thread Aaron Brady
On Mar 27, 7:14 am, alex23  wrote:
> On Mar 27, 3:44 pm, Aaron Brady  wrote:
>
> > Is there a possibility of the dict_values, dict_items, and dict_keys
> > objects growing a 'tolist' method?  It's one of those little things
> > that contributes to one's user experience.
>
> Probably not, because the Python approach is to use the builtins. I'm
> not sure what you feel mydict.values().tolist() might offer over the
> conventional list(mydict.values()).
>
> So yeah, -1.

I'd like to address this, even though if I weren't an interested
party, I'd probably recognize a -1 too.  I'll try to be impartial.

The suggestion is entirely a "look and feel" observation.  In an
interactive session, to examine the contents of a dictionary I've just
created, I need to type list(_), and lose the previous return value.
It's a better for my  train of thought too.

I don't necessarily advocate that every collection and iterator should
grow one, though I don't really have the case for a special case for
dict views.  OTOH, I find three 'tolist' methods in the standard
library: array, memoryview, and parser.ST.  It could offer the same as
they do.

Mostly a convenience request I guess.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to arrange classes in .py files?

2009-03-27 Thread David L. Jones
On Mar 26, 8:51 pm, Kent  wrote:
> ... Is
> there any convention how to manage python classes into .py files?
>
> ...
> In above packages, each .py file contains one python class. And
> ClassName = Filename
>
> ...
> Can anyone give some hint on it? would be great with reason.
>

Overall, I don't think there is a single convention that anyone can
point to and everyone will at least acknowledge as convention.

If you have multiple single-class files, then you will have
unnecessary redundancy referencing the classes from outside:

  # Module structure:  mymodule/
  #  __init.py__
  #  someclass.py
  import mymodule
  c = mymodule.someclass.someclass()

You can get around this with a Java-like statement:

  # Same module structure
  from mymodule.someclass import someclass  # or from ... import *
  c = someclass()

but you lose namespacing which can make code more difficult to read. I
think that this Java-style approach of pulling everything into the
current namespace is quite silly, since Python's module structure was
specifically designed in large part not to work like this. (Commence
flaming.)

I tend to think in terms of coupling and cohesion. Within an
application, any classes, functions, data, etc. that are tightly
coupled are candidates to live in the same file. If you have a set of
classes that all inherit from a common set of base classes, then you
should probably consider putting the base and inherited classes
together in a file. That puts them in the same namespace, which makes
sense.

Cohesion is the flip side: if a class is large, even if it is somewhat
coupled to other classes, it should probably go in its own file. In
general, use coupling as a guide to put more things into a single
file, and cohesion as a guide to break out parts into multiple files.

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


Re: modifying a list element from a function

2009-03-27 Thread Aaron Brady
On Mar 27, 4:39 am, TP  wrote:
> Hi everybody,
>
> Be a the following list, containing list elements which second field is a
> string.
>
> >>> a = [ [4, "toto"], [5, "cou"] ]
> >>> a[0][1]="tou"
> >>> a
>
> [[4, 'tou'], [5, 'cou']]
>
> OK.
>
> Now, I want:
> * to do the same modification on the list "a" within a function
> * not to hardcode in this function the position of the string in each
> element of a.
>
> At first sight, we think at defining a function like this:
>
> def assign( text_accessor, list_elem, new_textvalue ):
>
>     text_accessor( list_elem ) = new_textvalue
>
> and then doing:
>
> assign( lambda elem: elem[1], a[0], "co" )
>
> But it does not work, we obtain:
>
>     text_accessor( list_elem ) = new_textvalue
> SyntaxError: can't assign to function call
>
> In fact, we should work on the address of text_accessor( list_elem ). How to
> do that?

There is always the __setitem__ method, either bound to the object in
question, or along with an instance and its class.

>>> def f( fun, ind, val ):
... fun( ind, val )
...
>>> a= [ None ]
>>> f( a.__setitem__, 0, 'abc' )
>>> a
['abc']

Or, you could require your instances to all have a method name to
accomplish it, or use operator.__setitem__.
--
http://mail.python.org/mailman/listinfo/python-list


Re: split string at commas respecting quotes when string not in csv format

2009-03-27 Thread Tim Chase

Paul McGuire wrote:

On Mar 27, 5:19 am, Tim Chase  wrote:

 >>> import re
 >>> s = """a=1,b="0234,)#($)@", k="7" """
 >>> rx = re.compile(r'[ ]*(\w+)=([^",]+|"[^"]*")[ ]*(?:,|$)')
 >>> rx.findall(s)
 [('a', '1'), ('b', '"0234,)#($)@"'), ('k', '"7"')]
 >>> rx.findall('a=1, *DODGY*SYNTAX* b=2')
 [('a', '1'), ('b', '2')]

I'm going to save this one and study it, too.  I'd like to learn
to use regexes better, even if I do try to avoid them when possible :)

This regexp is fairly close to the one I used, but I employed the
re.VERBOSE flag to split it out for readability.  The above
breaks down as

  [ ]*   # optional whitespace, traditionally "\s*"
  (\w+)  # tag the variable name as one or more "word" chars
  =  # the literal equals sign
  (  # tag the value
  [^",]+ # one or more non-[quote/comma] chars
  |  # or
  "[^"]*"# quotes around a bunch of non-quote chars
  )  # end of the value being tagged
  [ ]*   # same as previously, optional whitespace  ("\s*")
  (?:# a non-capturing group (why?)
  ,  # a literal comma
  |  # or
  $  # the end-of-line/string
  )  # end of the non-capturing group


Mightent there be whitespace on either side of the '=' sign?  And if
you are using findall, why is the bit with the delimiting commas or
end of line/string necessary?  I should think findall would just skip
over this stuff, like it skips over *DODGY*SYNTAX* in your example.


Which would leave you with the solution(s) fairly close to what I 
original posited ;-)


(my comment about the "non-capturing group (why?)" was in 
relation to not needing to find the EOL/comma because findall() 
doesn't need it, as Paul points out, not the precedence of the 
"|" operator.)


-tkc



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


Re: Python AppStore / Marketplace

2009-03-27 Thread Daniel Fetchinson
> I think Marcel has a point...
>
> Much can be done and should be done to improve packaging and applications
> for python.
>
> That's why I for one am working on the python package manager project. On
> sourceforge.
>
> It uses the pypi interface to search.
>
> Actually we haven't made a release yet. Still many.. many things to fix.
>
>>> Using my iPhone I suddenly realize how easy it is to find applications
>>> in Apple's AppStore. How easy and fast it is to install or de-install
>>> an app. My iPhone even checks in the background if there is an upgrade
>>> which could be installed painlessly.
>> [...]
>>> Unfortunately there's nothing like this in the Python world...
>
> It is being worked on...
>
>> I'd be content
>> to hear your projection for a mere 18 years out (the amount of time
>> for which Python apps have been in production), or even 10 years
>> (which takes us back to Python 1.5).
>
> Just a GUI for package management that lets you seperate what is available
> for the python platform that you are running on. Install, deinstall, and
> get package information.
>
> https://sourceforge.net/projects/pythonpkgmgr/
>
> We only have source at the moment. Only for windows... and only for
> python 2.5. Pretty limited... but we'll get there.

How will your solution be different from distutils, setuptools, pip,
zc.buildout and a couple other similar packages I don't recall now?
Have you considered joining one of these efforts in order to not
fragment the "packaging and distribution" arena? Have you evaluated
these solutions in detail and have found that they are not appropriate
for your needs? If yes, what is the most problematic features of these
already existing solutions that you don't like?

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: C extension using GSL

2009-03-27 Thread Nick Craig-Wood
jesse  wrote:
>  I give up. I cannot find my memory leak! I'm hoping that someone out
>  there has come across something similar. Let me lay out the basic
>  setup:
> 
>  I'm performing multiple simulations on a model. Each iteration
>  involves solving a system of differential equations. For this I use
>  the GNU Scientific Library (GSL) -- specifically the rk4imp ODE
>  solver. After the ODE is solved the array is returned to python and is
>  analyzed. As you may have guessed, my problem is that over the course
>  of the iterations the memory keeps climbing until python crashes.
> 
>  Note: *The extension does not keep running.* It returns object (a
>  list) and is done until the next iteration. AFAIK, any memory
>  allocated during execution of the extension should be released.
>  Question: Since the extension was run from within python is memory
>  allocated within an extension part of python's heap?

No, on the normal C heap

>  Would this have
>  an adverse or unpredictable affect on any memory allocated during the
>  running of the extension?

If the library passes you data and ownership of a heap block, you'll
need to free it.


> One hypothesis I have, since most other
>  possibilities have been eliminated, is that GSL's creation of it's own
>  data structures (eg., gsl_vector) is messing up Python's control of
>  the heap. Is this possible?

Only if GSL is buggy

> If so, how would one be able to fix this
>  issue?

Valgrind
 
>  It may help some nice folks out there who are good enough to look at
>  this post if I layout the flow, broken up by where stuff happens
>  (i.e., in the Python code or C code):
> 
>  1) Python: Set up the simulation and basic data structures (numpy
>  arrays with initial conditions, coupling matrices for the ODE's, dicts
>  with parameters, etc).
>  2) Python: Pass these to the C extension
>  3) C: Python objects passed in are converted to C arrays, floats,
>  etc.
>  4) C: A PyList object, L,  is created (new reference!). This will hold
>  the solution vector for the ODE
>  5) C: Initialize GSL ODE solver and stepper functions. Solve the ODE,
>  at each step use PyList_Append(L, current_state) to append the current
>  state to L.
>  6) C: After the ODE solver finishes, free GSL objects, free coupling
>  matrices, free last state vector.
>  7) C: Return L to Python with return Py_BuildValue("N", L).
>  8) Python: Convert returned list L to array A, delete L, work with A.
>  8.1) Python: Step 8) includes plotting. (I have a small suspicion that
>  matplotlib holds onto lots of data, but I've used clf() and close(fig)
>  on all plots, so I think I'm safe here. )
>  8.2) Python: save analysis results from A, save A. (At this point
>  there should be no more use of A. In fact, at point 8) in the next
>  iteration A is replaced by a new array.)
>  9) Python: Change any parameters or initial conditions and goto 1).

At every point a memory allocation is made check who owns the memory
and that it is freed through all possible error paths.

Valgrind will help you find the memory leaks.  It works well once
you've jumped the flaming hoops of fire that setting it up is!

Another thing you can try is run your process untill it leaks loads,
then make it dump core.  Examine the core dump with a hex editor and
see what it is full of!  This technique works suprisingly often.

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: C extension using GSL

2009-03-27 Thread jesse
On Mar 27, 9:30 am, Nick Craig-Wood  wrote:
> jesse  wrote:
> >  I give up. I cannot find my memory leak! I'm hoping that someone out
> >  there has come across something similar. Let me lay out the basic
> >  setup:
>
> >  I'm performing multiple simulations on a model. Each iteration
> >  involves solving a system of differential equations. For this I use
> >  the GNU Scientific Library (GSL) -- specifically the rk4imp ODE
> >  solver. After the ODE is solved the array is returned to python and is
> >  analyzed. As you may have guessed, my problem is that over the course
> >  of the iterations the memory keeps climbing until python crashes.
>
> >  Note: *The extension does not keep running.* It returns object (a
> >  list) and is done until the next iteration. AFAIK, any memory
> >  allocated during execution of the extension should be released.
> >  Question: Since the extension was run from within python is memory
> >  allocated within an extension part of python's heap?
>
> No, on the normal C heap
>
> >  Would this have
> >  an adverse or unpredictable affect on any memory allocated during the
> >  running of the extension?
>
> If the library passes you data and ownership of a heap block, you'll
> need to free it.
>
> > One hypothesis I have, since most other
> >  possibilities have been eliminated, is that GSL's creation of it's own
> >  data structures (eg., gsl_vector) is messing up Python's control of
> >  the heap. Is this possible?
>
> Only if GSL is buggy
>
> > If so, how would one be able to fix this
> >  issue?
>
> Valgrind
>
>
>
> >  It may help some nice folks out there who are good enough to look at
> >  this post if I layout the flow, broken up by where stuff happens
> >  (i.e., in the Python code or C code):
>
> >  1) Python: Set up the simulation and basic data structures (numpy
> >  arrays with initial conditions, coupling matrices for the ODE's, dicts
> >  with parameters, etc).
> >  2) Python: Pass these to the C extension
> >  3) C: Python objects passed in are converted to C arrays, floats,
> >  etc.
> >  4) C: A PyList object, L,  is created (new reference!). This will hold
> >  the solution vector for the ODE
> >  5) C: Initialize GSL ODE solver and stepper functions. Solve the ODE,
> >  at each step use PyList_Append(L, current_state) to append the current
> >  state to L.
> >  6) C: After the ODE solver finishes, free GSL objects, free coupling
> >  matrices, free last state vector.
> >  7) C: Return L to Python with return Py_BuildValue("N", L).
> >  8) Python: Convert returned list L to array A, delete L, work with A.
> >  8.1) Python: Step 8) includes plotting. (I have a small suspicion that
> >  matplotlib holds onto lots of data, but I've used clf() and close(fig)
> >  on all plots, so I think I'm safe here. )
> >  8.2) Python: save analysis results from A, save A. (At this point
> >  there should be no more use of A. In fact, at point 8) in the next
> >  iteration A is replaced by a new array.)
> >  9) Python: Change any parameters or initial conditions and goto 1).
>
> At every point a memory allocation is made check who owns the memory
> and that it is freed through all possible error paths.
>
> Valgrind will help you find the memory leaks.  It works well once
> you've jumped the flaming hoops of fire that setting it up is!
>
> Another thing you can try is run your process untill it leaks loads,
> then make it dump core.  Examine the core dump with a hex editor and
> see what it is full of!  This technique works suprisingly often.
>
> --
> Nick Craig-Wood  --http://www.craig-wood.com/nick

Thanks for the suggestions.
-J
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming Python 4th Edition?

2009-03-27 Thread pruebauno
On Mar 26, 10:08 pm, Esmail  wrote:
> Hi,
>
> Does anyone know if there is a 4th edition of this book planned
> and if so, when it might be coming out?
>
> It looks like a good and comprehensive book but is getting a bit
> outdated(?).
>
> And I guess since I'm asking this, I might as well be asking what
> your favorite, comparable Python book might be :-)
>
> Thanks,
> Esmail

Make sure that Programming Python is what you want. I was very
disappointment with it (First edition) because I was expecting
something like the Perl Camel book and it isn't.

It isn't a introduction to the Python language like "Learning Python",
it doesn't work as reference like "Python in a Nutshell", it doesn't
contain short idiomatic code like "Python Cookbook". What you are left
with is different application domains and how to apply Python to them.
The book is excellent if you want to do Network, GUI, Databases, etc.
but poor if you want to learn about Python the core language. The
title of the book should be changed from "Programming Python" to
"Applied Python" so newcomers to the language don't buy it by mistake.
Even the preface says that it is about "application-level programming
in Python". The book is pretty much 4 books in 1:
  System programming in Python
  Tkinter programming in Python
  Internet programming in Python
  Database and Persistence programming in Python

In my opinion an experienced programmer that wants to learn Python the
language should buy "Nutshell" and somebody new to programming in
general "Learning". You should buy "Programming" only if you need to
develop in one of the Domains covered in the book.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Any way to use a range as a key in a dictionary?

2009-03-27 Thread Carl Banks
On Mar 26, 11:02 pm, Paul Rubin  wrote:
> Dennis Lee Bieber  writes:
>
> > ...        v = theDict.get(x, NOT_RELEVANT)
> > ...        if v is not NOT_RELEVANT:
> > ...                print x, v
>
> I think you'd normally do this with
>
>      if x in theDict:
>           print x, v

Where does v come from?

> but the OP was asking about a different problem, involving looking up
> numeric ranges, which could conceivably be very large, thus the
> suggestions about interval trees and so forth.

The fact that the OP asked about what to do with the the other 65526
values suggests that he only wanted to use intervals to fill in the
gaps between meaningful values (thus having complete coverage over the
16-bit integer range).  An interval tree would not be a good approach
for that situation.


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


Re: please include python26_d.lib in the installer

2009-03-27 Thread Carl Banks
On Mar 27, 1:48 am, Compie  wrote:
> I get this linker error
> LINK : fatal error LNK1104: cannot open file 'python26_d.lib'
> when I build the debug version of my Visual Studio project.
>
> This is caused by the following lines in the file c:\Python26\include
> \pyconfig.h
> #                       ifdef _DEBUG
> #                               pragma comment(lib,"python26_d.lib")
> #                       else
> #                               pragma comment(lib,"python26.lib")
> #                       endif /* _DEBUG */
>
> The file python26_d.lib is not installed by the Python installer on
> Windows.
>
> So please:
> 1. Provide python26_d.lib in the installer.
> or
> 2. Remove this automatic "pragma comment lib" from pyconfig.h, since I
> can't disable it from the outside (as far as I know).
>
> Please note: I want to build my own code in Debug mode for debugging.
> I don't want to build or use the debug version of Python. I also can't
> #undef _DEBUG, since the file that includes pyconfig.h (via Python.h)
> is generated by SWIG. Also I prefer not to change pyconfig.h myself,
> since my code needs to compile on a lot of different machines.

python26_d.dll *is* the debugging version of Python.

As a workaround to the situation, try to copy the file python26.dll to
python26_d.dll.  (I'm not sure this will work; you say you are
building a SWIG library in debug mode, and it's possible that SWIG
will try to use features of the Python debugging version.  If that's
the case, you'll have no choice but to use the debugging version of
Python.)

OTOH, it's possible that SWIG and Python just happen to use the same
macro to indicate debugging mode.  So I think you raise a valid point
that this can be problematic.  Perhaps something like _Py_DEBUG should
be used instead.


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


Re: Programming Python 4th Edition?

2009-03-27 Thread Esmail

prueba...@latinmail.com wrote:


It isn't a introduction to the Python language like "Learning Python",
it doesn't work as reference like "Python in a Nutshell", it doesn't
contain short idiomatic code like "Python Cookbook". What you are left
with is different application domains and how to apply Python to them.
The book is excellent if you want to do Network, GUI, Databases, etc.
but poor if you want to learn about Python the core language. The
title of the book should be changed from "Programming Python" to
"Applied Python" 


Hi,

I appreciate you taking the time to post. I agree with what you say.
I guess what appeals to me is the nearly encyclopedic nature of the
book .. and I am curious about scripting with python, so it seems to
have some good material on it (though I think there are newer modules
now available for this).

It's good to hear what others think about this book, and others too.

Cheers,
Esmail

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


c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Aahz
In article ,
andrew cooke  wrote:
>
>you are trying to do very "deep" things that most people do not do with
>python.  that does not mean that there are no solutions, just that you
>have to find them yourself (especially with the decline of this
>newsgroup).

Excuse me?  What decline of this newsgroup?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict view to list

2009-03-27 Thread Miles
On Fri, Mar 27, 2009 at 9:58 AM, Aaron Brady wrote:
> The suggestion is entirely a "look and feel" observation.  In an
> interactive session, to examine the contents of a dictionary I've just
> created, I need to type list(_), and lose the previous return value.
> It's a better for my  train of thought too.

Versus _.tolist(), which would also overwrite the previous return value?

> I don't necessarily advocate that every collection and iterator should
> grow one, though I don't really have the case for a special case for
> dict views.  OTOH, I find three 'tolist' methods in the standard
> library: array, memoryview, and parser.ST.  It could offer the same as
> they do.

array has had that method since before Python v1.0. memoryview, for
whatever reason, is not iterable; parser.ST is also not, since it
doesn't convert to a flat sequence but rather a list tree.  I don't
see the special case for dict views, at all.

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


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread andrew cooke
Aahz wrote:
> Excuse me?  What decline of this newsgroup?

Hmmm.  It's hard to respond to this without implicitly criticising others
here, which wasn't my point at all.  But my personal impression is that
over the years various people who used to post here now stay pretty firmly
in the dev group, while others seem to have disappeared more or less
completely .

When I made this comment (which was some time ago) I went back and checked
whether there had been some splitting of newsgroups - I wondered if
perhaps I was remembering back to a time when dev did not exist and
everyone was here.  That didn't seem to be the case, though.

Anyway, as I said, my intention wasn't to criticise people here (who have
provided me with useful help), but simply based on my recollection of
c.l.python many years ago (I just googled and it seems I was here at least
10 years ago).

I hope that clarifies things.  I *really* don't want this to develop into
a criticism of current posters (which is completely unfair), so I am
unlikely to respond further to this thread.

Andrew


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


Interfacing python and C

2009-03-27 Thread steve William
Hi All,

I'm using SWIG for the first time and I am facing some problems with user
defined header files. I'm trying to use my own header file in a C program
which would be interfaced with python.

The header file is test.h:
*#include 

int fact(int n) {
 if (n <= 1) return 1;
 else return n*fact(n-1);
}*

The C program is test1.c:
*#include 
#include "test.h"

int calc_fact(int a)
{
return (fact(a));
}*

The interface file is test1.i:
*%module test1

%{
#include "stdio.h"
#include "test.h"
 %}

int calc_fact(int a);*

The commands that I used to generate the wrappers are:
*swig -python test1.i
gcc -c test1.c test1_wrap.c -I/usr/include/python2.5
-I/usr/lib/python2.5/config
g++ -shared test1_wrap.o -o _test1.so*

When I try to import test1, I get an error saying:
*>>> import test1
Traceback (most recent call last):
  File "", line 1, in 
  File "test1.py", line 22, in 
import _test1
ImportError: ./_test1.so: undefined symbol: calc_fact*

I'm not sure why this is happening because when I try without user defined
header file, it works. Also the error says that it does not recognize *
calc_fact* which is a function that I want to access from python and is
declared in the interface file.

Is there any specific way in which user defined headers need to be declared
in the interface file? Should the user defined header be placed in the
/usr/include  directory?

Any help on this is highly appreciated.

Thank you,
Steve James William.
--
http://mail.python.org/mailman/listinfo/python-list


Interfacing python and C

2009-03-27 Thread steve William
Hi All,

I'm using SWIG for the first time and I am facing some problems with user
defined header files. I'm trying to use my own header file in a C program
which would be interfaced with python.

The header file is test.h:
*#include 

int fact(int n) {
 if (n <= 1) return 1;
 else return n*fact(n-1);
}*

The C program is test1.c:
*#include 
#include "test.h"

int calc_fact(int a)
{
return (fact(a));
}*

The interface file is test1.i:
*%module test1

%{
#include "stdio.h"
#include "test.h"
 %}

int calc_fact(int a);*

The commands that I used to generate the wrappers are:
*swig -python test1.i
gcc -c test1.c test1_wrap.c -I/usr/include/python2.5
-I/usr/lib/python2.5/config
g++ -shared test1_wrap.o -o _test1.so*

When I try to import test1, I get an error saying:
*>>> import test1
Traceback (most recent call last):
  File "", line 1, in 
  File "test1.py", line 22, in 
import _test1
ImportError: ./_test1.so: undefined symbol: calc_fact*

I'm not sure why this is happening because when I try without user defined
header file, it works. Also the error says that it does not recognize *
calc_fact* which is a function that I want to access from python and is
declared in the interface file.

Is there any specific way in which user defined headers need to be declared
in the interface file? Should the user defined header be placed in the
/usr/include  directory?

Any help on this is highly appreciated.

Thank you,
Steve James William.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Interfacing python and C

2009-03-27 Thread MRAB

steve William wrote:

Hi All,

I'm using SWIG for the first time and I am facing some problems with 
user defined header files. I'm trying to use my own header file in a C 
program which would be interfaced with python.


The header file is test.h:
/#include 

int fact(int n) {
 if (n <= 1) return 1;
 else return n*fact(n-1);
}/
   
The C program is test1.c:

/#include 
#include "test.h"

int calc_fact(int a)
{
return (fact(a));
}/

The interface file is test1.i:
/%module test1

%{
#include "stdio.h"
#include "test.h"
 %}

int calc_fact(int a);/

The commands that I used to generate the wrappers are:
/swig -python test1.i
gcc -c test1.c test1_wrap.c -I/usr/include/python2.5 
-I/usr/lib/python2.5/config

g++ -shared test1_wrap.o -o _test1.so/

When I try to import test1, I get an error saying:
/>>> import test1
Traceback (most recent call last):
  File "", line 1, in 
  File "test1.py", line 22, in 
import _test1
ImportError: ./_test1.so: undefined symbol: calc_fact/

I'm not sure why this is happening because when I try without user 
defined header file, it works. Also the error says that it does not 
recognize /calc_fact/ which is a function that I want to access from 
python and is declared in the interface file.


Is there any specific way in which user defined headers need to be 
declared in the interface file? Should the user defined header be placed 
in the /usr/include  directory?


Any help on this is highly appreciated.


Should you be putting a function body in a header file?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 66, Issue 527

2009-03-27 Thread steve William
>
> steve William wrote:
>
>> Hi All,
>>
>> I'm using SWIG for the first time and I am facing some problems with user
>> defined header files. I'm trying to use my own header file in a C program
>> which would be interfaced with python.
>>
>> The header file is test.h:
>> /#include 
>>
>> int fact(int n) {
>> if (n <= 1) return 1;
>> else return n*fact(n-1);
>> }/
>>   The C program is test1.c:
>> /#include 
>> #include "test.h"
>>
>> int calc_fact(int a)
>> {
>>return (fact(a));
>> }/
>>
>> The interface file is test1.i:
>> /%module test1
>>
>> %{
>> #include "stdio.h"
>> #include "test.h"
>>  %}
>>
>> int calc_fact(int a);/
>>
>> The commands that I used to generate the wrappers are:
>> /swig -python test1.i
>> gcc -c test1.c test1_wrap.c -I/usr/include/python2.5
>> -I/usr/lib/python2.5/config
>> g++ -shared test1_wrap.o -o _test1.so/
>>
>> When I try to import test1, I get an error saying:
>> />>> import test1
>> Traceback (most recent call last):
>>  File "", line 1, in 
>>  File "test1.py", line 22, in 
>>import _test1
>> ImportError: ./_test1.so: undefined symbol: calc_fact/
>>
>> I'm not sure why this is happening because when I try without user defined
>> header file, it works. Also the error says that it does not recognize
>> /calc_fact/ which is a function that I want to access from python and is
>> declared in the interface file.
>>
>> Is there any specific way in which user defined headers need to be
>> declared in the interface file? Should the user defined header be placed in
>> the /usr/include  directory?
>>
>> Any help on this is highly appreciated.
>>
>>  Should you be putting a function body in a header file?
>

Since the header is pretty simple it does not do any harm putting the
function body in the header. It does compile and run correctly in gcc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Aahz
In article ,
andrew cooke  wrote:
>Aahz wrote:
>>
>> Excuse me?  What decline of this newsgroup?
>
>Hmmm.  It's hard to respond to this without implicitly criticising others
>here, which wasn't my point at all.  But my personal impression is that
>over the years various people who used to post here now stay pretty firmly
>in the dev group, while others seem to have disappeared more or less
>completely .

Well, yes, but that's simply the nature of online fora (I originally
wrote "nature of Usenet", but I think it's more general than that).  From
my POV, if you're going to call it a "decline", you need to provide more
evidence than some people leaving and others arriving.  I think that the
sheer volume and quality of posts to c.l.py is evidence that c.l.py is
not declining.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22
--
http://mail.python.org/mailman/listinfo/python-list


is there a way to collect twitts with python?

2009-03-27 Thread '2+
i found a guy twittin supercollider code
this means his followers can listen to a noiz by activating that 1 line
(well if he has sc installed)
if lots of sc users start twittin ... it would be no good to follow each

collecting a sc related twitt can be done with python?
if there's a lib already any good pointers to start learnin thangs at?

maybe someday
jython or pyjamas can be used to launch a
sctwitt strreaming radio?
(this should be the one listeners can mix his favorite sctwittists)

tia

-- 
SaRiGaMa's Oil Vending Orchestra
is podcasting:
http://sarigama.namaste.jp/podcast/rss.xml
and supplying oil.py for free:
http://oilpy.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a way to collect twitts with python?

2009-03-27 Thread Aahz
In article ,
'2+  wrote:
>
> [...]

This is for upperclass twit of the year, right?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22
--
http://mail.python.org/mailman/listinfo/python-list


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Tim Chase

Aahz wrote:

In article ,
andrew cooke  wrote:

you are trying to do very "deep" things that most people do not do with
python.  that does not mean that there are no solutions, just that you
have to find them yourself (especially with the decline of this
newsgroup).


Excuse me?  What decline of this newsgroup?


Must be a by-product of Schluehr's Law[1]...every thread degrades 
into an argument about the GIL. :)


-tkc


[1]
http://mail.python.org/pipermail/python-list/2009-January/697412.html



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


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread skip

Aahz> Excuse me?  What decline of this newsgroup?

Andrew>  But my personal impression is that over the years various
Andrew> people who used to post here now stay pretty firmly in the dev
Andrew> group, while others seem to have disappeared more or less
Andrew> completely .

People come and go, that's true.  That's to be expected though.  I certainly
find many of the "newer" folks more than capable replacements for people you
don't see around here (much) anymore.  Maybe you just aren't as familiar
with some of the new names.  I think if you intersect the set of frequent
posters here and with the frequent posters in python-dev (say, those who
post more than a few times a month) you'll find a fairly large intersection,
and that intersection will include some of the most active Python core
developers.

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


Re: Any way to use a range as a key in a dictionary?

2009-03-27 Thread Paul Rubin
Carl Banks  writes:
> >      if x in theDict:
> >           print x, v
> 
> Where does v come from?

Oops, pasted from original.  Meant of course "print x, theDict[x]".
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a way to collect twitts with python?

2009-03-27 Thread Grant Edwards
On 2009-03-27, '2+  wrote:

I've found that C# is much better at collecting twits... 

-- 
Grant Edwards   grante Yow!
  at   
BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-BI-
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: smtplib problem with newly rebuilt Debian/lenny system

2009-03-27 Thread Aahz
[posted & e-mailed, please respond to newsgroup]

In article ,
cassiope   wrote:
>
>In attempting to diagnose the cause, I tried directly executing the
>lines inside the python2.5 interpreter:
>
>import  smtplib
>s= smtplib.SMTP('localhost')
>
>but the second line causes  a traceback:
>
>File "", line 1, in 
>File "/usr/lib/python2.5/smtplib.py", line 244, in __init__
>(code, msg) = self.connect(host, port)
>File "/usr/lib/python2.5/smtplib.py", line 310, in connect
>raise socket.error, msg
>socket.error: (97, 'Address family not supported by protocol')
>
>This is with exim4 and python2.5 on a newly installed lenny system.
>No error messages appear in /var/log or /var/log/exim4 directories.

What happens if you 
telnet localhost 25

This looks like a network setup issue.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22
--
http://mail.python.org/mailman/listinfo/python-list


Find duplicates in a list/array and count them ...

2009-03-27 Thread Paul . Scipione
Hello,

I'm a newbie to Python.  I wrote a Python script which connect to my 
Geodatabase (ESRI ArcGIS File Geodatabase), retrieves the records, then 
proceeds to evaluate which ones are duplicated.  I do this using lists.  
Someone suggested I use arrays instead.  Below is the content of my script.  
Anyone have any ideas on how an array can improve performance?  Right now the 
script takes 2.5 minutes to run on a recordset of 79k+ records:

from __future__ import division
import sys, string, os, arcgisscripting, time
from time import localtime, strftime

def writeMessage(myMsg):
print myMsg
global log
log = open(logFile, 'a')
log.write(myMsg + "\n")

logFile = "c:\\temp\\" + str(strftime("%Y%m%d %H%M%S", localtime())) + ".log"

writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' begin unique values 
test')

# Create the Geoprocessor object
gp = arcgisscripting.create(9.3)
oid_list = []
dup_list = []
tmp_list = []
myWrkspc = "c:\\temp\\TVM Geodatabase GDIschema v6.0.2 PilotData.gdb"
myFtrCls = "\\Landbase\\T_GroundContour"

writeMessage(' ')
writeMessage('gdb: ' + myWrkspc)
writeMessage('ftr: ' + myFtrCls)
writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' retrieving 
recordset...')

rows = gp.SearchCursor(myWrkspc + myFtrCls,"","","GDI_OID")
row = rows.Next()
writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' processing 
recordset...')
while row:
if row.GDI_OID in oid_list:
tmp_list.append(row.GDI_OID)
oid_list.append(row.GDI_OID)
row = rows.Next()

writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' generating 
statistics...')

dup_count = len(tmp_list)
tmp_list = list(set(tmp_list))
tmp_list.sort()

for oid in tmp_list:
a = str(oid) + ' '
while len(a) < 20:
a = a + ' '
dup_list.append(a + '(' + str(oid_list.count(oid)) + ')')

for dup in dup_list:
writeMessage(dup)

writeMessage(' ')
writeMessage('records: ' + str(len(oid_list)))
writeMessage('duplicates : ' + str(dup_count))
writeMessage('% errors   : ' + str(round(dup_count / len(oid_list), 4)))
writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' unique values test 
complete')

log.close()
del dup, dup_count, dup_list, gp, log, logFile, myFtrCls, myWrkspc
del oid, oid_list, row, rows, tmp_list
exit()


Thanks!

Paul J. Scipione
GIS Database Administrator
work: 602-371-7091
cell: 480-980-4721



Email Firewall made the following annotations

-
--- NOTICE ---

This message is for the designated recipient only and may contain confidential, 
privileged or proprietary information.  If you have received it in error, 
please notify the sender immediately and delete the original and any copy or 
printout.  Unintended recipients are prohibited from making any other use of 
this e-mail.  Although we have taken reasonable precautions to ensure no 
viruses are present in this e-mail, we accept no liability for any loss or 
damage arising from the use of this e-mail or attachments, or for any delay or 
errors or omissions in the contents which result from e-mail transmission.

-

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


Re: Any way to use a range as a key in a dictionary?

2009-03-27 Thread Carl Banks
On Mar 27, 11:20 am, Paul Rubin  wrote:
> Carl Banks  writes:
> > >      if x in theDict:
> > >           print x, v
>
> > Where does v come from?
>
> Oops, pasted from original.  Meant of course "print x, theDict[x]".

You have look up x twice with that code, whereas you wouldn't have to
with this:

v = theDict.get(x)
if v is not None:
print x, v

or with this:

try:
v = theDict[x]
except KeyError:
pass
else:
print x,v

Also, these minimize the number of times you have to type x.  Thus I
recommend either of these two, or a defaultdict, for this.


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


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Albert Hopkins
On Fri, 2009-03-27 at 10:47 -0700, Aahz wrote: 
> In article ,
> andrew cooke  wrote:
> >Aahz wrote:
> >>
> >> Excuse me?  What decline of this newsgroup?
> >
> >Hmmm.  It's hard to respond to this without implicitly criticising others
> >here, which wasn't my point at all.  But my personal impression is that
> >over the years various people who used to post here now stay pretty firmly
> >in the dev group, while others seem to have disappeared more or less
> >completely .
> 
> Well, yes, but that's simply the nature of online fora (I originally
> wrote "nature of Usenet", but I think it's more general than that).  From
> my POV, if you're going to call it a "decline", you need to provide more
> evidence than some people leaving and others arriving.  I think that the
> sheer volume and quality of posts to c.l.py is evidence that c.l.py is
> not declining.

I agree. If the argument is simply that some devs no longer hang here
but do on -dev than that's not declining to me, especially as the amount
of traffic on -dev increases.  That's ordinary.  Same for people coming
and going.

For me declining means the rate of (non-spam) posts is steadily dropping
over time.

If you look at http://mail.python.org/pipermail/python-list/ it doesn't
make it clear that there is any sort of decline.

1999-04: 1708
1999-05: 2204
1999-06: 2390
1999-07: 2387
1999-08: 2149
1999-09: 2014
1999-10: 2060
1999-11: 1911
1999-12: 2304
2000-01: 2678
2000-02: 4000
2000-03: 3782
2000-04: 3236
2000-05: 4283
2000-06: 4628
2000-07: 4189
2000-08: 4275
2000-09: 3961
2000-10: 3834
2000-11: 2360
2000-12: 3116
2001-01: 4212
2001-02: 3892
2001-03: 4494
2001-04: 4731
2001-05: 5498
2001-06: 4936
2001-07: 6518
2001-08: 5247
2001-09: 3728
2001-10: 3687
2001-11: 4575
2001-12: 4472
2002-01: 5602
2002-02: 5272
2002-03: 5309
2002-04: 5984
2002-05: 5331
2002-06: 4229
2002-07: 4840
2002-08: 4948
2002-09: 4205
2002-10: 3327
2002-11: 4355
2002-12: 4108
2003-01: 6225
2003-02: 7758
2003-03: 5041
2003-04: 5025
2003-05: 5012
2003-06: 4976
2003-07: 4937
2003-08: 5703
2003-09: 4320
2003-10: 6396
2003-11: 5059
2003-12: 3930
2004-01: 4059
2004-02: 4316
2004-03: 5178
2004-04: 4358
2004-05: 3926
2004-06: 4255
2004-07: 4291
2004-08: 6275
2004-09: 5619
2004-10: 5251
2004-11: 4064
2004-12: 5295
2005-01: 5394
2005-02: 5278
2005-03: 5117
2005-04: 5098
2005-05: 4383
2005-06: 4635
2005-07: 4533
2005-08: 4546
2005-09: 4591
2005-10: 5580
2005-11: 5789
2005-12: 5119
2006-01: 15174
2006-02: 9838
2006-03: 11660
2006-04: 9776
2006-05: 10740
2006-06: 10156
2006-07: 9564
2006-08: 9806
2006-09: 10752
2006-10: 11348
2006-11: 9887
2006-12: 9186
2007-01: 7850
2007-02: 8184
2007-03: 8986
2007-04: 9965
2007-05: 10138
2007-06: 8444
2007-07: 7776
2007-08: 8544
2007-09: 8852
2007-10: 8548
2007-11: 6940
2007-12: 7454
2008-01: 8490
2008-02: 8572
2008-03: 8393
2008-04: 9508
2008-05: 10030
2008-06: 7500
2008-07: 8496
2008-08: 8198
2008-09: 7632
2008-10: 8332
2008-11: 7656
2008-12: 8694
2009-01: 9792
2009-02: 8033
2009-03: 3801


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


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread skip

Albert> For me declining means the rate of (non-spam) posts is steadily
Albert> dropping over time.

I know this wasn't the main point of your post, but if you subscribe to
python-list@python.org or read it via a mail-to-news gateway like Gmane I
think you will find the ratio of spam to ham much smaller than if you read
comp.lang.python via a vanilla Usenet newsfeed.

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
--
http://mail.python.org/mailman/listinfo/python-list


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Nick Craig-Wood
Aahz  wrote:
>  Well, yes, but that's simply the nature of online fora (I originally
>  wrote "nature of Usenet", but I think it's more general than that).  From
>  my POV, if you're going to call it a "decline", you need to provide more
>  evidence than some people leaving and others arriving.  I think that the
>  sheer volume and quality of posts to c.l.py is evidence that c.l.py is
>  not declining.

c.l.py is my favourite usenet group and has been for some time.  I've
been doing usenet for 16 years now!

I enjoy reading about problems and problems solved.  I enjoy helping
people where I can and especially learning new things when helping
people - I think it has contributed enormously to my development as a
python programmer.

When I ask a question of c.l.py I find the answers to be informative
and enlightening.  Even after quite a few years of python programing
I'm still learning new things from c.l.py

As a long time usenet user I find it easy to ignore the occasional
flame wars.  Posters with the wrong sort of attitude are brought
gently into line by the majority.

If usenet groups had ratings I'd give c.l.py 5 stars.

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Find duplicates in a list/array and count them ...

2009-03-27 Thread MRAB

paul.scipi...@aps.com wrote:

Hello,
 
I'm a newbie to Python.  I wrote a Python script which connect to my 
Geodatabase (ESRI ArcGIS File Geodatabase), retrieves the records, then 
proceeds to evaluate which ones are duplicated.  I do this using lists.  
Someone suggested I use arrays instead.  Below is the content of my 
script.  Anyone have any ideas on how an array can improve performance?  
Right now the script takes 2.5 minutes to run on a recordset of 79k+ 
records:
 
from __future__ import division

import sys, string, os, arcgisscripting, time
from time import localtime, strftime
 
def writeMessage(myMsg):

print myMsg

--- delete start ---

global log
log = open(logFile, 'a')

--- delete end ---

Open the log file once in the main part of the script.


log.write(myMsg + "\n")
 
logFile = "c:\\temp\\" + str(strftime("%Y%m%d %H%M%S", localtime())) + 
".log"
 


log = open(logFile, 'a')


writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' begin unique 
values test')
 
# Create the Geoprocessor object

gp = arcgisscripting.create(9.3)
oid_list = []
dup_list = []
tmp_list = []
myWrkspc = "c:\\temp\\TVM Geodatabase GDIschema v6.0.2 PilotData.gdb"
myFtrCls = "_\\Landbase\\T_GroundContour_"
 
writeMessage(' ')

writeMessage('gdb: ' + myWrkspc)
writeMessage('ftr: ' + myFtrCls)
writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' retrieving 
recordset...')
 
rows = gp.SearchCursor(myWrkspc + myFtrCls,"","","GDI_OID")

row = rows.Next()
writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' processing 
recordset...')


--- delete start ---

while row:
if row.GDI_OID in oid_list:
tmp_list.append(row.GDI_OID)
oid_list.append(row.GDI_OID)
row = rows.Next()

--- delete end ---

You're searching a list. The longer the list becomes, the longer it'll
take to search it. Build a dict of how many times you've seen each item.

oid_count = {}
while row:
oid_count[row.GDI_OID] = oid_count.get(row.GDI_OID, 0) + 1
oid_list.append(row.GDI_OID)
row = rows.Next()



writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' generating 
statistics...')
 

-- delete start ---

dup_count = len(tmp_list)

> tmp_list = list(set(tmp_list))
> tmp_list.sort()
--- delete end ---

You now want to know which ones occurred more than once.

tmp_list = [oid for oid, count in oid_count.iteritems() if count > 1]
tmp_list.sort()
dup_count = len(tmp_list)

--- delete start ---

for oid in tmp_list:
a = str(oid) + ' '
while len(a) < 20:
a = a + ' '
dup_list.append(a + '(' + str(oid_list.count(oid)) + ')')

--- delete end ---

And here you're scanning the entire list _for every item_; if there are 
'n' items then it's being scanned 'n' times!


The number of times each item occurred is now stored in oid_count.

for oid in tmp_list:
a = str(oid) + ' '
while len(a) < 20:
a = a + ' '
dup_list.append(a + '(' + str(oid_count[oid]) + ')')

 
for dup in dup_list:

writeMessage(dup)
 
writeMessage(' ')

writeMessage('records: ' + str(len(oid_list)))
writeMessage('duplicates : ' + str(dup_count))
writeMessage('% errors   : ' + str(round(dup_count / len(oid_list), 4)))
writeMessage(' ')
writeMessage(str(strftime("%H:%M:%S", localtime())) + ' unique values 
test complete')
 
log.close()


--- delete start ---

del dup, dup_count, dup_list, gp, log, logFile, myFtrCls, myWrkspc
del oid, oid_list, row, rows, tmp_list
exit()

--- delete end ---

Not necessary, and it'll exit at the end of the script anyway.

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


Re: Any way to use a range as a key in a dictionary?

2009-03-27 Thread Peter Otten
Mudcat wrote:

> I would like to use a dictionary to store byte table information to
> decode some binary data. The actual number of entries won't be that
> large, at most 10. That leaves the other 65525 entries as 'reserved'
> or 'other' but still need to be somehow accounted for when
> referenced.
> 
> So there are a couple of ways to do this that I've seen. I can loop
> that many times and create a huge dictionary. This isn't a good idea.
> I can just assume if a key isn't there that it's not relevant. That's
> a better idea.
> 
> However I wondered if there was a way to simply use a range as a key
> reference somehow. I played around with some options with no success.
> Or maybe there was another way to do this with another data type that
> I haven't thought about.

You can use a defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(lambda: "reserved", [(1,2), (2,3)])
>>> d[1]
2
>>> d[2]
3
>>> d[42]
'reserved'

If the keys are successive integers starting at 0 a list is also an option.
It makes setting ranges to a particular value easy:

>>> d = ["reserved"]*2**16
>>> d[10:20] = [42]*10
>>> d[5], d[10], d[15], d[20]
('reserved', 42, 42, 'reserved')

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


Re: Any way to use a range as a key in a dictionary?

2009-03-27 Thread Duncan Booth
Carl Banks  wrote:

> On Mar 27, 11:20 am, Paul Rubin  wrote:
>> Carl Banks  writes:
>> > >      if x in theDict:
>> > >           print x, v
>>
>> > Where does v come from?
>>
>> Oops, pasted from original.  Meant of course "print x, theDict[x]".
> 
> You have look up x twice with that code, whereas you wouldn't have to
> with this:
> 
> v = theDict.get(x)
> if v is not None:
> print x, v
> 

Note that while you only lookup x in the dict once your code does still 
involve two dict lookups: once to lookup the get method and once to lookup 
x. It also involves creating a new bound method object so if performance is 
a concern you'll find that either the 'if x in theDict: ...' or the 
try...except are likely to be faster.
--
http://mail.python.org/mailman/listinfo/python-list


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Aahz
In article ,
Nick Craig-Wood   wrote:
>
>c.l.py is my favourite usenet group and has been for some time.  I've
>been doing usenet for 16 years now!

Newbie.  ;-)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to arrange classes in .py files?

2009-03-27 Thread Kent
On Mar 27, 3:01 pm, "David L. Jones"  wrote:
> On Mar 26, 8:51 pm, Kent  wrote:
>
> > ... Is
> > there any convention how to manage python classes into .py files?
>
> > ...
> > In above packages, each .py file contains one python class. And
> > ClassName = Filename
>
> > ...
> > Can anyone give some hint on it? would be great with reason.
>
> Overall, I don't think there is a single convention that anyone can
> point to and everyone will at least acknowledge as convention.
>
> If you have multiple single-class files, then you will have
> unnecessary redundancy referencing the classes from outside:
>
>   # Module structure:  mymodule/
>   #                      __init.py__
>   #                      someclass.py
>   import mymodule
>   c = mymodule.someclass.someclass()
>
> You can get around this with a Java-like statement:
>
>   # Same module structure
>   from mymodule.someclass import someclass  # or from ... import *
>   c = someclass()
>
> but you lose namespacing which can make code more difficult to read. I
> think that this Java-style approach of pulling everything into the
> current namespace is quite silly, since Python's module structure was
> specifically designed in large part not to work like this. (Commence
> flaming.)
>
> I tend to think in terms of coupling and cohesion. Within an
> application, any classes, functions, data, etc. that are tightly
> coupled are candidates to live in the same file. If you have a set of
> classes that all inherit from a common set of base classes, then you
> should probably consider putting the base and inherited classes
> together in a file. That puts them in the same namespace, which makes
> sense.
>
> Cohesion is the flip side: if a class is large, even if it is somewhat
> coupled to other classes, it should probably go in its own file. In
> general, use coupling as a guide to put more things into a single
> file, and cohesion as a guide to break out parts into multiple files.
>
> D

thanks you guys' explaination. I did some refactory on my codes. Now
it look's like:

myapp/ # this is a package, it is the root package
   - gui/ # this is package, contains all gui related modules
- mainFrame.py


   - dao.py # all daos are in this module
   - service.py # all service classes, responsible for handling DB
connections, Txn mgmt, and Business logic Task (calling daos)
   - entity.py  # like 'pojo's, in java,
   - util.py # utils
   - myapp.py # start main script


with this structure, import statements were *significantly*
reduced. :)



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


Re: Calendar module: HTMLCalendar overrides style sheet settings

2009-03-27 Thread Sibylle Koczian
Terry Reedy schrieb:

> Calendar is an ancient and not-well-maintained module which may even
> predate html.  (There have even been suggestions that it be dropped.) I
> would not be surprised if the 'css' parameter of formatyearpage were an
> incomplete addition to the first version of HTMLCalendar.  Feel free to
> submit a patch to make the html work better with css, as long as css is
> not made mandatory rather than optional.  (Or should there be two html
> classes? I do not know html well enough to know.)
> 

But the Calendar class and its subclasses, including HTMLCalendar, are
new in Python 2.5?! I'll try to change the formatting a bit, shouldn't
be a big thing, but who knows...

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


Re: how to arrange classes in .py files?

2009-03-27 Thread Michael Torrie
Kent wrote:
> In java, usually a .java file contains One Class. I read some python
> codes, I found one py file can have many classes and functions. Is
> there any convention how to manage python classes into .py files?

In python we have a real name space, the primary unit being the
"module."  Think of a module as a singleton really, with any code in
module being executed upon import (a sort of constructor).  Python
classes are really just objects, so you can put as many related objects
in a module as you want, or is appropriate (more on this later), and
refer to them with the "module.object" notation.  If you need to spread
your code that's in one namespace out over several files for clarity and
ease of debugging, you can create a python "package[1]" which consists
of an __init__.py that can pull in various names from other files in the
package into the namespace it is defining.  A python package is imported
as if it was a normal module.

How you are organizing your python code is probably fine, but wouldn't
be considered very pythonic and familiar to many python programmers.
Most of us don't want to have to deal with something like:

import mymodule

myobject=mymodule.class.Class()

as that is redundant.  Rather, myobject=mymodule.Class() is expected.
Sounds to me like your style of programming may lend itself to using a
python package as an organizational unit for your code.

Typically my modules have the following structure:
- set up any module variables and constants
- exception classes
- internal functions or classes (private to the module)
- public functions or classes
- module-level code to perform any on-load stuff
- an if __name__=="__main__" section for doing unit testing

My modules are typically defined according to function.  Common module
names would include config, utilities, etc.

Since the singleton is the pattern that I use the most, I actually
rarely need classes at all in most modules, except to define exceptions
my module will raise.  I consider functions in modules to be the
equivalent of methods on a static class.  Quite a refreshing break from
the way Java forces me to work.  And much cleaner too.

Often as I develop a module, I'll factor out code that's generic out of
the module into its own module.  There should be very loose coupling
between modules, and very tight coupling within the module, though not
necessarily... a collection of utility functions are often just
collected in a module for convenience.  Coupling is a good indicator of
whether you should factor the code out into its own module.  Finally, if
I want to take a group of modules and export a simple, clean, public
interface, I'll wrap the modules in a package.

[1] http://docs.python.org/tutorial/modules.html#packages
--
http://mail.python.org/mailman/listinfo/python-list


Re: C extension using GSL

2009-03-27 Thread Gabriel Genellina

En Fri, 27 Mar 2009 03:10:06 -0300, jesse  escribió:


I give up. I cannot find my memory leak! I'm hoping that someone out
there has come across something similar. Let me lay out the basic
setup:
[...]
4) C: A PyList object, L,  is created (new reference!). This will hold
the solution vector for the ODE
[...]
7) C: Return L to Python with return Py_BuildValue("N", L).


I don't know the "N" format, but if Py_BuildValue returns a new reference,  
you're leaking a reference to the L list.

Why don't you return L directly?

You can use sys.getrefcount in Python to see the reference count for an  
object:


py> from sys import getrefcount as rc
py> x = object()
py> rc(x)
2   # the name x, and a temporary reference as parameter
py> rc([])
1   # only the temporary reference
py> x = y = []
py> rc(x)
3
py> x = ()
py> rc(x)
954   # the empty tuple is shared

--
Gabriel Genellina

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


Re: dict view to list

2009-03-27 Thread Luis Gonzalez
Yes, I know the python approach is to use built-ins.
But wouldn't it be cool if we could do mydict.values().tolist()
instead?
It would be more regular and intuitive and readable from an OO point
of view.
In my oppinion, this would be cleaner.
Built-ins used like this look like an early decission made when
designing an imperative language.

Luis

On 27 mar, 09:14, alex23  wrote:
> On Mar 27, 3:44 pm, Aaron Brady  wrote:
>
> > Is there a possibility of the dict_values, dict_items, and dict_keys
> > objects growing a 'tolist' method?  It's one of those little things
> > that contributes to one's user experience.
>
> Probably not, because the Python approach is to use the builtins. I'm
> not sure what you feel mydict.values().tolist() might offer over the
> conventional list(mydict.values()).
>
> So yeah, -1.

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


Python Tk Tix GUI documentation & builder overview and tips

2009-03-27 Thread baloand
I have recently started development for a small video conversion
project using a GUI. After some research I decided to use Tkinter/Tix
(Tk/Tix). The reasons are mainly:

1. the GUI is rather simple, and

2. the end-user is not necessarily technically inclined so I want to
keep
  a) required libraries as few as possible, and
  b) installation as painless as possible.

3. Tk/Tix is included with Python. Thus only a Python installation is
needed. Nothing else.

4. Tk itsself misses some rudimentary widgets like meters, multi/colum
lists, grid and scrolled widgets. Tix provides those. Good enough for
my little application (more advanced and more modern widgets are
available in frameworks like Qt, Gtk, or wxWindows).


Before starting I spent some effort to find
a) relevant documentation,
b) GUI Builders which might help me,
c) answers to non-obvious questions.

The process took some time and effort so I want to share my findings:

a) Documentation resources

Python Docs
http://docs.python.org/library/tkinter.html
Tk Commands
http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm
Tix Reference
http://tix.sourceforge.net/man/html/contents.htm
Tix demo application
You want to extract the Tix demo application coming with the Tix
8.4.3 source distribution. It contains  examples for many widgets -
unfortunately none for multi-column HList or the Grid (see below).

https://sourceforge.net/project/showfiles.php?group_id=5649&package_id=5704
Tix8.4.3-src.tar.gz, then look in /Tix8.4.3/Python/Demo/tix
Thinking in Tkinter
I recommend the "Individual programs online"
http://www.ferg.org/thinking_in_tkinter/index.html


b) GUI development tools

ActiveState GUI Builder (using grid layout)
SpecTcl is the predecessor of GUI Builder (by ActivaState).
http://spectcl.sourceforge.net/
FAQ (where to get source)
http://aspn.activestate.com/ASPN/Mail/Message/komodo-announce/3355346

PAGE v3.0 by Stewart Allen (using placer layout)
http://page.sourceforge.net/

There are many more for other GUI toolkits mentioned in this post:
http://mail.python.org/pipermail/python-list/2004-February/250727.html

Finally I decided to use the packer layout and create the widgets
manually. Just the simplest and quickest way for me.


c) How do I ...?

How do I use all methods available in the Tix Grid?

Tix Grid with full implementation of all methods
http://klappnase.bubble.org/TixGrid/index.html


How do I create a multi-column Tix.HList?

import Tkinter as Tk
import Tix

root = Tix.Tk()
# setup HList
hl = Tix.HList(root, columns = 5, header = True)
hl.header_create(0, text = "File")
hl.header_create(1, text = "Date")
hl.header_create(1, text = "Size")
# create a multi-column row
hl.add("row1", text = "filename.txt")
hl.item_create(entry_path, 1, text = "2009-03-26 21:07:03")
hl.item_create(entry_path, 2, text = "200MiB")

I haven't found out how to right-justify individual columns? Anyone?


How to implement Tk GUI with multiple threads?

Usually there are two options to make threads wait for an event:

  * gui thread polling (lame)
see here how to use Tk.after() (actually a Tcl command) to poll
http://uucode.com/texts/pylongopgui/pyguiapp.html

see here how to imitate the Tk event loop to poll for non-Tk
events (a socket, for example)

https://sourceforge.net/project/showfiles.php?group_id=5649&package_id=5704
Tix8.4.3-src.tar.gz, then look in /Tix8.4.3/Python/Demo/tix/
tixwidgets.py, find loop()


  * multithreaded with events (the option to choose)
Basically this uses bind and event_generate to send "Notify"
messages to the Tk instance.
I suspect the following example failed due to not synchronising
the event_generate call

http://coding.derkeiler.com/Archive/Python/comp.lang.python/2006-07/msg01479.html

For multithreading Python Tk GUI applications the following rules
apply:
1. same thread calling Tk must do all subsequent GUI calls,
2. other threads may send events with send_event to the root Tk
instance,
3. with threading problems you might try to synchonise access to
event_generate(). Using event_generate() with one non-GUI thread seems
to be safe.
--
http://mail.python.org/mailman/listinfo/python-list


~/.local not in sys.path?

2009-03-27 Thread skip
I don't see ~/.local in sys.path.  Is this some feature which needs to be
enabled?  I was kind of unclear after reading the section on it in the 2.6
What's New document.

Thx,

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
--
http://mail.python.org/mailman/listinfo/python-list


UnicodeEncodeError - opening encoded URLs

2009-03-27 Thread D4rko
Hi!

I have a problem with urllib2 open() function. My application is
receiving the following request - as I can see in the developement
server console it is properly encoded:

[27/Mar/2009 22:22:29] "GET /[blahblah]/Europa_%C5%9Arodkowa/5 HTTP/
1.1" 500 54572

Then it uses this request parameter as name variable to build
wikipedia link, and tries to acces it with following code:

url = u'http://pl.wikipedia.org/w/index.php?title=' + name +
'&printable=yes'
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
wikipage = opener.open(url)

Unfortunately, the last line fails with the exception:
UnicodeEncodeError 'ascii' codec can't encode character u'\u015a' in
position 30: ordinal not in range(128).  Using urlencode(url) results
in TypeError "not a valid non-string sequence or mapping object", and
quote(url)  fails because of KeyError u'\u015a' . How can I properly
parse this request to make it work (ie. acces
http://pl.wikipedia.org/wiki/Europa_%C5%9Arodkowa)?
--
http://mail.python.org/mailman/listinfo/python-list


Python print and types selection

2009-03-27 Thread mark . seagoe
Python 2.5, PC.

I have a question about getting Python print to be able to recognize a
long type.


class bignumber(object):

def __init__(self, initval=0):
self.val = initval
#
def __int__(self):
print 'bignumber.__int__ returning a %s' % type(self.val)
return self.val
#
def __long__(self):
print 'bignumber.__long__ returning a %s' % type(self.val)
return long(self.val)

def str(self):
return '0x%016X' % self.val
#
print 'TEST 1'
dog = 0x123456789ABCDEF0
print 'type(dog) = %s' % type(dog)
print 'dog val = 0x%016X' % dog

print 'TEST 2'
cat = bignumber(0x55)
print 'cat val = 0x%016X' % cat
print 'type(cat) = %s' % type(cat)

print 'TEST 3'
bird = bignumber(dog)
print 'type(bird) = %s' % type(bird)
print 'bird val = 0x%016X' % long(bird)
print 'bird val = 0x%016X' % bird

When I run this, I get:

TEST 1
type(dog) = 
dog val = 0x123456789ABCDEF0
TEST 2
bignumber.__int__ returning a 
cat val = 0x0055
type(cat) = 
TEST 3
type(bird) = 
bignumber.__long__ returning a 
bird val = 0x123456789ABCDEF0
bignumber.__int__ returning a 
Traceback (most recent call last):
  File "C:\PythonTesting\bignmber.py, line 32, in 
print 'bird val = 0x%016X' % bird
TypeError: int argument required

Python print recognizes the local constant "dog", but it goes and
fetches the __int__ type from my object-based class, even though it's
value is a long.  Then Python print doesn't expect a long to come back
and bombs out.  I don't want to force the main program to cast the
long value getting returned.  I know Python print can print a long,
but how can I make it select the __long__ instead of the __int__ ?

Thanks.



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


Accessing wx.TextCtrl after refactoring

2009-03-27 Thread alex
Hi all
I am working on a Dialog window for a gui in wxPython and started
refactoring it, below code is a simplified version of it.
"def createInput1" should create a static text, a button and a
textcontrol using the information in "def box1Labels".
"def makeStaticBox1" then arranges all widgets in staticbox1.

My problem is that it works fine for the static text and the button
label but I cant "rename" self.txtctrl that it
becomes self.txtctrl_inpath or self.txtctrl_outpath for getting the
path from either "def BrowseInDlg" or "def BrowseOutDlg".

I must admit that I am still a beginner but searching through my books
does not get me further. I like the idea of refactoring for
"automatising" widgets creation instead of hardcoding each widgetID.
But I am completely stuck here. Maybe can somebody help?

Coming from the Fortran world my programming style may be quite
"fortranic" instead of being "pythonic" but I am trying to improve and
enjoy what I learned so far...

Thanks Alex



#
#
#!/usr/bin/env python
#
#
"""Add Python docs string"""
import wx
import os
#
#
class Dialog1(wx.Dialog):
def __init__(self):
wx.Dialog.__init__(self, None, -1, "Test", size=(500, 600))
self.makeStaticBox1()
self.makeSizer()


def box1Labels(self):
return (("Label1:", "Browse", self.BrowseInDlg,
txtctrl_inpath),
("Label2:", "Browse", self.BrowseOutDlg,
txtctrl_outpath))


def makeStaticBox1(self):
box1 = wx.StaticBox(self, -1, "Box1")
pathFlexGridSizer = wx.FlexGridSizer(4, 0, 0, 0)
pathFlexGridSizer.AddGrowableCol(1)

for label, pth_btn_label, btn_funct, txtctrl_path in
self.box1Labels():
self.createInput1(label, pth_btn_label, txtctrl_path)

pathFlexGridSizer.Add(self.stattxt, 0,
wx.ALIGN_CENTER_VERTICAL|wx.TOP|wx.BOTTOM, 2)
pathFlexGridSizer.Add((10, 10))
pathFlexGridSizer.Add(self.pth_Btn, 0, wx.ALIGN_LEFT)
pathFlexGridSizer.Add(self.txtctrl, 0, wx.ALIGN_RIGHT|
wx.TOP|wx.BOTTOM, 2)
self.Bind(wx.EVT_BUTTON, btn_funct, self.pth_Btn)


self.path_sizer = wx.StaticBoxSizer(box1, wx.VERTICAL)
self.path_sizer.Add(pathFlexGridSizer, 2, wx.ALL|wx.EXPAND, 0)


def createInput1(self, label, pth_btn_label, txtctrl_path):
self.stattxt=wx.StaticText(self, -1, label)
self.pth_Btn = wx.Button(self, -1, pth_btn_label)
self.txtctrl=wx.TextCtrl(self, -1, "", size=(300, -1))




def makeSizer(self):
GridSizer = wx.BoxSizer(wx.VERTICAL)
GridSizer.Add(self.path_sizer, 1, wx.ALL|wx.EXPAND, 2)


self.SetSizer(GridSizer)
self.Fit()
self.Centre()
self.Show(True)


def BrowseInDlg(self, event):
#
dialog = wx.DirDialog(None, "Choose directory:",
style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
inpath=dialog.GetPath()
self.txtctrl_inpath.SetValue(inpath)
print inpath
dialog.Destroy()


def BrowseOutDlg(self, event):
#
dialog = wx.DirDialog(None, "Choose directory:",
style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
outpath=dialog.GetPath()
self.txtctrl_outpath.SetValue(outpath)
print outpath
dialog.Destroy()




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


Re: Python print and types selection

2009-03-27 Thread mark . seagoe
What I mean is, is there a way to change the class so that print will
see it as a long, without having to cast it as one in the main
program.
--
http://mail.python.org/mailman/listinfo/python-list


Problems with background processes on Windows

2009-03-27 Thread geoff . bache
Hi all,

The following code behaves differently on Windows and Linux using
Python 2.5.2. The Linux behaviour is what I expect in both places :)
Perhaps somebody could help explain this. Or maybe it is a Python bug.
Or a Windows feature...

 communicate.py ---

import subprocess
p = subprocess.Popen([ "python", "sleep.py" ], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
p.communicate()
---
 sleep.py 

import subprocess, os
subprocess.Popen([ 'python', '-c', 'import time; time.sleep(10)' ],
stdin=open(os.devnull), stdout=open(os.devnull, "w"),
stderr=subprocess.STDOUT)


In short, we start a subprocess which in turn starts a different
subprocess and then returns without waiting for it. We then try to
"communicate" with the first subprocess.

On Windows if I run "communicate.py" it does not return for 10
seconds, i.e. until the "grandchild" background process terminates. On
Linux it returns immediately as I would expect.

If I replace "p.communicate()" with "p.wait()" it returns immediately
on both. If I don't point stdin, stdout and stderr of the child
process to os.devnull then it will wait 10 seconds on Linux also,
which I'd also expect as we can't collect info from these places if
they've been forwarded elsewhere. It seems like Windows somehow
doesn't notice this.

Any help gratefully appreciated.

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


Re: UnicodeEncodeError - opening encoded URLs

2009-03-27 Thread Matt Nordhoff
D4rko wrote:
> Hi!
> 
> I have a problem with urllib2 open() function. My application is
> receiving the following request - as I can see in the developement
> server console it is properly encoded:
> 
> [27/Mar/2009 22:22:29] "GET /[blahblah]/Europa_%C5%9Arodkowa/5 HTTP/
> 1.1" 500 54572
> 
> Then it uses this request parameter as name variable to build
> wikipedia link, and tries to acces it with following code:
> 
>   url = u'http://pl.wikipedia.org/w/index.php?title=' + name +
> '&printable=yes'
>   opener = urllib2.build_opener()
>   opener.addheaders = [('User-agent', 'Mozilla/5.0')]
>   wikipage = opener.open(url)
> 
> Unfortunately, the last line fails with the exception:
> UnicodeEncodeError 'ascii' codec can't encode character u'\u015a' in
> position 30: ordinal not in range(128).  Using urlencode(url) results
> in TypeError "not a valid non-string sequence or mapping object", and
> quote(url)  fails because of KeyError u'\u015a' . How can I properly
> parse this request to make it work (ie. acces
> http://pl.wikipedia.org/wiki/Europa_%C5%9Arodkowa)?

What if you just used a regular byte string for the URL?

>>> url = 'http://pl.wikipedia.org/w/index.php?title=' + name +
'&printable=yes'

(Unless "name" is a unicode object as well.)

(Nice user-agent, BTW. :-P )
-- 
--
http://mail.python.org/mailman/listinfo/python-list


Re: UnicodeEncodeError - opening encoded URLs

2009-03-27 Thread D4rko
> (Unless "name" is a unicode object as well.)

Unfortunately it is, it's the argument that is automagically handed to
the handler function by the Django URL dispatcher. I guess I may need
to encode it back to the pure ascii with the "%xx" things, but I can't
find the function that would do it. Any idea?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python print and types selection

2009-03-27 Thread Gabriel Genellina

En Fri, 27 Mar 2009 18:43:16 -0300,  escribió:


Python 2.5, PC.

I have a question about getting Python print to be able to recognize a
long type.

[...]

print 'TEST 3'
bird = bignumber(dog)
print 'type(bird) = %s' % type(bird)
print 'bird val = 0x%016X' % long(bird)
print 'bird val = 0x%016X' % bird

When I run this, I get:
[...]
TEST 3
type(bird) = 
bignumber.__long__ returning a 
bird val = 0x123456789ABCDEF0
bignumber.__int__ returning a 
Traceback (most recent call last):
  File "C:\PythonTesting\bignmber.py, line 32, in 
print 'bird val = 0x%016X' % bird
TypeError: int argument required

Python print recognizes the local constant "dog", but it goes and
fetches the __int__ type from my object-based class, even though it's
value is a long.  Then Python print doesn't expect a long to come back
and bombs out.  I don't want to force the main program to cast the
long value getting returned.  I know Python print can print a long,
but how can I make it select the __long__ instead of the __int__ ?


This bug was corrected in version 2.6 - see  
http://bugs.python.org/issue1742669
If you have to stay with 2.5 I'm afraid any solution would require to  
modify your code:


-- put long() around those arguments
-- "%s" % format_hex(val) (where format_hex does the long conversion)
-- redefine __str__ and use %s

--
Gabriel Genellina

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


Re: Python print and types selection

2009-03-27 Thread Miles
On Fri, Mar 27, 2009 at 6:56 PM, Gabriel Genellina wrote:
> En Fri, 27 Mar 2009 18:43:16 -0300,  escribió:
>> Python print recognizes the local constant "dog", but it goes and
>> fetches the __int__ type from my object-based class, even though it's
>> value is a long.  Then Python print doesn't expect a long to come back
>> and bombs out.  I don't want to force the main program to cast the
>> long value getting returned.  I know Python print can print a long,
>> but how can I make it select the __long__ instead of the __int__ ?
>
> This bug was corrected in version 2.6 - see
> http://bugs.python.org/issue1742669
> If you have to stay with 2.5 I'm afraid any solution would require to modify
> your code:
>
> -- put long() around those arguments
> -- "%s" % format_hex(val) (where format_hex does the long conversion)
> -- redefine __str__ and use %s

Or make your class a subclass of long.

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


Re: please include python26_d.lib in the installer

2009-03-27 Thread Mark Hammond

Please note: I want to build my own code in Debug mode for debugging.
I don't want to build or use the debug version of Python. I also can't


Python does this on purpose so you don't accidentally mix different 
versions of the C runtime library.  This would happen ff you defined 
DEBUG in your code but use Python built without DEBUG - Python using a 
different name for its lib prevents this.


Note that just shipping the _d.lib wouldn't help - you would need the 
_d.dll itself, plus *all* extension modules you use - *all* .pyd/.dll 
etc files have the trailing _d, and a debug version of Python refuses to 
load the release versions without the _d.


I'd recommend leaving DEBUG etc disbled, but enable debug information 
and disable optimizations while debugging.


Cheers,

Mark

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


Re: dict view to list

2009-03-27 Thread Terry Reedy

Luis Gonzalez wrote:

Yes, I know the python approach is to use built-ins.
But wouldn't it be cool if we could do mydict.values().tolist()
instead?


Should we also give every collection a .toset(), .tofrozenset(), 
.totuple(), and .todict() method?  This way lies the madness of 
combinatorial explosion.



It would be more regular and intuitive and readable from an OO point
of view.


In my opinion, this is backwards.  From an OO point of view, instances 
of class X should be created by the constructor for that class.  That is 
where the knowledge of the intermal structure of class X instances 
belongs.  The principle of information hiding dictates that other 
classes should not know how to create an X.  On the other hand, 
collection classes should be iterable and know how to de-structure 
themselves. So list(iterable) operates by iterable providing an iterator 
that list uses to create an instance.  The stream of object provided by 
the iterator is the common means of transferring information.



In my oppinion, this would be cleaner.


To me, the hypothetical

import operator
map(operator.attrgetter('tolist'), [[1,2,3], (1,2,3), 
{1,2,3},{1:'a',2:'b',3:'c'}])


is a lot dirtier than the current

map(list, [[1,2,3], (1,2,3), {1,2,3},{1:'a',2:'b',3:'c'}])


Built-ins used like this look like an early decission made when
designing an imperative language.


It is part of python basic design.  Functions used as functions can be 
passed as arguments to functions and used to operator on heterogeneous 
collections, as in the example above.


Terry Jan Reedy


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


Re: how to arrange classes in .py files?

2009-03-27 Thread Terry Reedy

Kent wrote:


thanks you guys' explaination. I did some refactory on my codes. Now
it look's like:

myapp/ # this is a package, it is the root package
   - gui/ # this is package, contains all gui related modules
- mainFrame.py


   - dao.py # all daos are in this module
   - service.py # all service classes, responsible for handling DB
connections, Txn mgmt, and Business logic Task (calling daos)
   - entity.py  # like 'pojo's, in java,
   - util.py # utils
   - myapp.py # start main script


Really clear.


with this structure, import statements were *significantly*
reduced. :)


Bingo!

tjr

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


Re: Accessing wx.TextCtrl after refactoring

2009-03-27 Thread Rhodri James

On Fri, 27 Mar 2009 21:51:19 -, alex  wrote:


Hi all
I am working on a Dialog window for a gui in wxPython and started
refactoring it, below code is a simplified version of it.
"def createInput1" should create a static text, a button and a
textcontrol using the information in "def box1Labels".
"def makeStaticBox1" then arranges all widgets in staticbox1.

My problem is that it works fine for the static text and the button
label but I cant "rename" self.txtctrl that it
becomes self.txtctrl_inpath or self.txtctrl_outpath for getting the
path from either "def BrowseInDlg" or "def BrowseOutDlg".


You need the special __setattr__ method.  A normal object attribute
assignment like:

  self.wombat = "go"

is equivalent to a call of

  self.__setattr__("wombat", "go")

So in your createInput1 method, once the widgets have been created
and all the dust has settled, if you add the line:

  self.__setattr__(txtctrl_path, self.txtctrl)

it will do exactly what you're after!

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python print and types selection

2009-03-27 Thread Terry Reedy

Miles wrote:

On Fri, Mar 27, 2009 at 6:56 PM, Gabriel Genellina wrote:

En Fri, 27 Mar 2009 18:43:16 -0300,  escribió:

Python print recognizes the local constant "dog", but it goes and
fetches the __int__ type from my object-based class, even though it's
value is a long.  Then Python print doesn't expect a long to come back
and bombs out.  I don't want to force the main program to cast the
long value getting returned.  I know Python print can print a long,
but how can I make it select the __long__ instead of the __int__ ?

This bug was corrected in version 2.6 - see
http://bugs.python.org/issue1742669
If you have to stay with 2.5 I'm afraid any solution would require to modify
your code:

-- put long() around those arguments
-- "%s" % format_hex(val) (where format_hex does the long conversion)
-- redefine __str__ and use %s


Or make your class a subclass of long.


Or use Python 3, where the int/long issue is gone ;-)

tjr

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


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Erik Max Francis

Albert Hopkins wrote:

I agree. If the argument is simply that some devs no longer hang here
but do on -dev than that's not declining to me, especially as the amount
of traffic on -dev increases.  That's ordinary.  Same for people coming
and going.

For me declining means the rate of (non-spam) posts is steadily dropping
over time.

If you look at http://mail.python.org/pipermail/python-list/ it doesn't
make it clear that there is any sort of decline.

...

And made all purdy-like:

http://www.alcyone.com/tmp/python-list%20traffic.pdf

--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  Always forgive your enemies -- nothing annoys them so much.
   -- Oscar Wilde
--
http://mail.python.org/mailman/listinfo/python-list


pyqt drop to open a file

2009-03-27 Thread rui . li . spam
Hi,

anyone can give a simple example or a link on how to use 'drop' with
pyqt.

what I'm looking for is drop a file to main widget then program get
the path\filename

something like: main_widget set to accept 'drop event', set filename
when 'drop event happens' then the filename is path\filename of the
file user drag from any location to main widget.


Thanks for any help.

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


Re: how do you prevent distutils from downloading and building packages without consent?

2009-03-27 Thread Gabriel Genellina
En Thu, 26 Mar 2009 07:59:15 -0300, lkcl   
escribió:



a number of people using pyjamas are not only encountering
difficulties with setup.py endeavouring to download and install
"setuptools" but also they are ... the best word to use is
unfortunately "offended" - by the fact that distutils, in its default
configuration, downloads and even _compiles_ its dependencies -
*without consent*.

a copy of the setup.py can be found here:
http://pyjamas.svn.sourceforge.net/viewvc/pyjamas/trunk/setup.py


distutils doesn't attempt to download *anything*. You're confusing it with  
setuptools and easy_install, which is a different beast.
Your setup.py seems overly complicated to me. For a pure Python package,  
setup.py looks like this:


from distutils.core import setup
setup(name='Foo package',
  description='My fine foo package',
  version='1.0',
  packages=['foo'])

Two statements, nothing more. To include an extension module bar.c:

setup(...
  ext_modules=[Extension('bar', ['bar.c', 'other.c'])],
  ...)

See http://docs.python.org/distutils/index.html

--
Gabriel Genellina

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


Re: pyqt drop to open a file

2009-03-27 Thread Albert Hopkins
On Fri, 2009-03-27 at 17:55 -0700, rui.li.s...@gmail.com wrote:
> Hi,
> 
> anyone can give a simple example or a link on how to use 'drop' with
> pyqt.
> 
> what I'm looking for is drop a file to main widget then program get
> the path\filename
> 
> something like: main_widget set to accept 'drop event', set filename
> when 'drop event happens' then the filename is path\filename of the
> file user drag from any location to main widget.

Google is your friend:

http://www.zetcode.com/tutorials/pyqt4/dragdrop/


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


Re: Accessing wx.TextCtrl after refactoring

2009-03-27 Thread Rhodri James
On Sat, 28 Mar 2009 00:51:04 -, Rhodri James  
 wrote:



On Fri, 27 Mar 2009 21:51:19 -, alex  wrote:


Hi all
I am working on a Dialog window for a gui in wxPython and started
refactoring it, below code is a simplified version of it.
"def createInput1" should create a static text, a button and a
textcontrol using the information in "def box1Labels".
"def makeStaticBox1" then arranges all widgets in staticbox1.

My problem is that it works fine for the static text and the button
label but I cant "rename" self.txtctrl that it
becomes self.txtctrl_inpath or self.txtctrl_outpath for getting the
path from either "def BrowseInDlg" or "def BrowseOutDlg".


You need the special __setattr__ method.  A normal object attribute
assignment like:

   self.wombat = "go"

is equivalent to a call of

   self.__setattr__("wombat", "go")

So in your createInput1 method, once the widgets have been created
and all the dust has settled, if you add the line:

   self.__setattr__(txtctrl_path, self.txtctrl)

it will do exactly what you're after!



or in a slightly less "magic" way:

  setattr(self, txtctrl_path, self.txtctrl)

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Any way to use a range as a key in a dictionary?

2009-03-27 Thread Carl Banks
On Mar 27, 1:06 pm, Duncan Booth  wrote:
> Carl Banks  wrote:
> > On Mar 27, 11:20 am, Paul Rubin  wrote:
> >> Carl Banks  writes:
> >> > >      if x in theDict:
> >> > >           print x, v
>
> >> > Where does v come from?
>
> >> Oops, pasted from original.  Meant of course "print x, theDict[x]".
>
> > You have look up x twice with that code, whereas you wouldn't have to
> > with this:
>
> > v = theDict.get(x)
> > if v is not None:
> >     print x, v
>
> Note that while you only lookup x in the dict once your code does still
> involve two dict lookups: once to lookup the get method and once to lookup
> x. It also involves creating a new bound method object so if performance is
> a concern you'll find that either the 'if x in theDict: ...' or the
> try...except are likely to be faster.

Not necessarily: if the hash calculation for x is expensive enough the
get version would still be faster.  If all you're doing is looking up
strings or ints (as the OP is doing) it's hardly going to matter
either way.


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


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread andrew cooke
Erik Max Francis wrote:
[...]
> And made all purdy-like:
>
>   http://www.alcyone.com/tmp/python-list%20traffic.pdf

That's very pretty, but neither the volume of posts, nor the quality of
the people posting here is really what I was talking about.  I don't think
I explained very well, but seeing the posts here helped clarify things a
little.

c.l.python used to be the core of a community built around a language.  It
no longer is.  It is a very useful place, where some very helpful and
knowledgeable people hang out and give advice, but instead of representing
the full interests of the Python community it is now very much a resource
for helping new users.

At least, that's how it seems to me.  And I don't think this is
necessarily "natural" or "normal" - I think it may be a failure on the
part of someone (who?  I don't quite know, perhaps all of us) in managing
a community.  Now there is an obvious argument against that - that the
language was becoming so popular that a single meeting place was no longer
practical - but without a crystal ball it is hard to know how true that
is, or what alternatives might have been.

I feel quite strongly about this.  I thought that c.l.python was almost
exceptional in the range (the perl group was another, similar community
back then).  I do worry that someone might have screwed up in a quite
major way, and that Python will suffer seriously, in the longer term, as a
result.

Another reason might be that the action has moved on to Haskell.  I get
the impression that it is undergoing the same kind of surge in popularity
from the "smart early adopters" that Python might have benefited from back
in the day (for some perverse reason I am actually moving back to Python
from more strongly typed functional languages).

Andrew


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


Re: Calendar module: HTMLCalendar overrides style sheet settings

2009-03-27 Thread Gabriel Genellina
En Fri, 27 Mar 2009 17:48:33 -0300, Sibylle Koczian  
 escribió:



Terry Reedy schrieb:

Calendar is an ancient and not-well-maintained module which may even
predate html.  (There have even been suggestions that it be dropped.)


(I would prefer it to be moved into the Tools directory)


But the Calendar class and its subclasses, including HTMLCalendar, are
new in Python 2.5?! I'll try to change the formatting a bit, shouldn't
be a big thing, but who knows...


new in Python 2.5??

Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam

import calendar
calendar.prmonth(2009,3)

 March 2009
Mo Tu We Th Fr Sa Su
   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31




--
Gabriel Genellina

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


Re: how do you prevent distutils from downloading and building packages without consent?

2009-03-27 Thread Gabriel Genellina
En Thu, 26 Mar 2009 08:34:58 -0300, John Machin   
escribió:

On Mar 26, 9:59 pm, lkcl  wrote:



a number of people using pyjamas are not only encountering
difficulties with setup.py endeavouring to download and install
"setuptools" but also they are ... the best word to use is
unfortunately "offended" - by the fact that distutils, in its default
configuration, downloads and even _compiles_ its dependencies -
*without consent*.

Whatever is happening, don't blame distutils -- it's absolutely
nothing to do with distutils. *You* are using a setup.py that calls
setuptools, which is a quite different distribution method. Have you
read the setuptools documentation? Didn't you *test* your setup.py
before making it available to the world?


(Ouch, I didn't notice your earlier reply when I posted mostly the same  
thing, sorry!)


--
Gabriel Genellina

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


Unladen-Swallow: A faster python

2009-03-27 Thread Luis M . González
This is a new project started by two Google engineers to speed up
python:
http://code.google.com/p/unladen-swallow/

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


Re: Python print and types selection

2009-03-27 Thread mark . seagoe
On Mar 27, 4:00 pm, Miles  wrote:
> On Fri, Mar 27, 2009 at 6:56 PM, Gabriel Genellina wrote:
> > En Fri, 27 Mar 2009 18:43:16 -0300,  escribió:
> >> Python print recognizes the local constant "dog", but it goes and
> >> fetches the __int__ type from my object-based class, even though it's
> >> value is a long.  Then Python print doesn't expect a long to come back
> >> and bombs out.  I don't want to force the main program to cast the
> >> long value getting returned.  I know Python print can print a long,
> >> but how can I make it select the __long__ instead of the __int__ ?
>
> > This bug was corrected in version 2.6 - see
> >http://bugs.python.org/issue1742669
> > If you have to stay with 2.5 I'm afraid any solution would require to modify
> > your code:
>
> > -- put long() around those arguments
> > -- "%s" % format_hex(val) (where format_hex does the long conversion)
> > -- redefine __str__ and use %s
>
> Or make your class a subclass of long.
>
> -Miles- Hide quoted text -
>
> - Show quoted text -

Absolute genius.  Wish I had thought of that.  Thanks to both of you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python print and types selection

2009-03-27 Thread mark . seagoe
On Mar 27, 7:48 pm, mark.sea...@gmail.com wrote:
> On Mar 27, 4:00 pm, Miles  wrote:
>
>
>
>
>
> > On Fri, Mar 27, 2009 at 6:56 PM, Gabriel Genellina wrote:
> > > En Fri, 27 Mar 2009 18:43:16 -0300,  escribió:
> > >> Python print recognizes the local constant "dog", but it goes and
> > >> fetches the __int__ type from my object-based class, even though it's
> > >> value is a long.  Then Python print doesn't expect a long to come back
> > >> and bombs out.  I don't want to force the main program to cast the
> > >> long value getting returned.  I know Python print can print a long,
> > >> but how can I make it select the __long__ instead of the __int__ ?
>
> > > This bug was corrected in version 2.6 - see
> > >http://bugs.python.org/issue1742669
> > > If you have to stay with 2.5 I'm afraid any solution would require to 
> > > modify
> > > your code:
>
> > > -- put long() around those arguments
> > > -- "%s" % format_hex(val) (where format_hex does the long conversion)
> > > -- redefine __str__ and use %s
>
> > Or make your class a subclass of long.
>
> > -Miles- Hide quoted text -
>
> > - Show quoted text -
>
> Absolute genius.  Wish I had thought of that.  Thanks to both of you.- Hide 
> quoted text -
>
> - Show quoted text -

I mean all three of you.  :)

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


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Albert Hopkins
On Fri, 2009-03-27 at 21:15 -0400, andrew cooke wrote:
[...]

> c.l.python used to be the core of a community built around a language.  It
> no longer is.  It is a very useful place, where some very helpful and
> knowledgeable people hang out and give advice, but instead of representing
> the full interests of the Python community it is now very much a resource
> for helping new users.

> At least, that's how it seems to me.  And I don't think this is
> necessarily "natural" or "normal" - I think it may be a failure on the
> part of someone (who?  I don't quite know, perhaps all of us) in managing
> a community.  Now there is an obvious argument against that - that the
> language was becoming so popular that a single meeting place was no longer
> practical - but without a crystal ball it is hard to know how true that
> is, or what alternatives might have been.
> 
> I feel quite strongly about this.  I thought that c.l.python was almost
> exceptional in the range (the perl group was another, similar community
> back then).  I do worry that someone might have screwed up in a quite
> major way, and that Python will suffer seriously, in the longer term, as a
> result.
> 
> Another reason might be that the action has moved on to Haskell.  I get
> the impression that it is undergoing the same kind of surge in popularity
> from the "smart early adopters" that Python might have benefited from back
> in the day (for some perverse reason I am actually moving back to Python
> from more strongly typed functional languages).

Sentimental... yet comical.  It's still, to me, a natural event.  The
same things happens to nearly every new, upcoming, grassroots
technology.  Linux was the same way.  So was KDE (and probably GNOME as
well).  This is just a natural evolution of the connection between
community and technology.

Simply put, Python isn't a baby anymore.  I remember being on c.l.python
back in like '97 or '98.  Back then it was pretty much the only place to
come to share info/interest Python.  There was the newsgroup,
python.org, and Starship.  That's it.  Nowadays Python is everywhere.
There are forums, blogs, magazines, books, local user groups, PyCon,
PyPi. etc.  And Python is so big that there are sub-communities such as
CherryPy and Django, SQLAlchemy, Jython and IronPython, etc.  There are
so many sub-groups with their own visions and plans and momentum, and
that's a good thing!  c.l.python is no longer the big fish in a small
pond.

So I'm sorry but c.l.python can no longer be the sole place to represent
the "full interests of the Python community" because the community is
much too big for it.  It can't be "managed" by a central source.  It's
bigger than that. And, let's face it, a smaller fraction of people get
their information from Usenet and mailing lists today compared to 1996. 

Looking back at some postings from '95 [1] I don't see that much
different from then and now, except there was a lot more off-topic
stuff,  there was a periodic FAQ,  GvR, and I didn't see any GIL
flamewars.  Some similarities include newbie-type questions, style
questions, questions regarding the C API, architecture- and
module-specific questions, posts from some of the same people I still
see today and, of course, regular expressions.  But maybe your nostalgia
predates 1995 (I didn't start using Python until 1997).

Anyway, I'm bored with this discussion. It seems to be a natural part of
technology communities as well.  I'm on another mailing list where,
almost every month, a different person independently comes to the
conclusion that the technology is dying.  And it's been that way ever
since I joined the mailing list 6 years ago.  If these things are dying
why can't they do so quickly (and quietly)?

-a


1.
http://groups.google.com/group/comp.lang.python/topics?hl=en&start=109792&sa=N


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


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Aaron Brady
On Mar 27, 8:15 pm, "andrew cooke"  wrote:
> Erik Max Francis wrote:
>
> [...]
>
> > And made all purdy-like:
>
> >    http://www.alcyone.com/tmp/python-list%20traffic.pdf
>
> That's very pretty, but neither the volume of posts, nor the quality of
> the people posting here is really what I was talking about.  I don't think
> I explained very well, but seeing the posts here helped clarify things a
> little.
>
> c.l.python used to be the core of a community built around a language.  It
> no longer is.  It is a very useful place, where some very helpful and
> knowledgeable people hang out and give advice, but instead of representing
> the full interests of the Python community it is now very much a resource
> for helping new users.
>
> At least, that's how it seems to me.  And I don't think this is
> necessarily "natural" or "normal" - I think it may be a failure on the
> part of someone (who?  I don't quite know, perhaps all of us) in managing
> a community.  Now there is an obvious argument against that - that the
> language was becoming so popular that a single meeting place was no longer
> practical - but without a crystal ball it is hard to know how true that
> is, or what alternatives might have been.
>
> I feel quite strongly about this.  I thought that c.l.python was almost
> exceptional in the range (the perl group was another, similar community
> back then).  I do worry that someone might have screwed up in a quite
> major way, and that Python will suffer seriously, in the longer term, as a
> result.
>
> Another reason might be that the action has moved on to Haskell.  I get
> the impression that it is undergoing the same kind of surge in popularity
> from the "smart early adopters" that Python might have benefited from back
> in the day

Hi, andrew.

> (for some perverse reason I am actually moving back to Python
> from more strongly typed functional languages).

I don't want to criticize you for this comment.  In fact, it
illustrates a good point and a potential source of confusion: the
language and the newsgroup are two different things.  Someone could
like the language and dislike the newsgroup; dislike the language and
like the newsgroup; or like or dislike both.  Likes and dislikes can
each be passive or active by the way.

It is a shame that you are so prohibited from getting a foot in the
door of the dev newsgroup.  From what you say, much of the Python-
focused, seasoned-dev discussion that you like takes place there; and
no one asks about references to parameters.  I can't attest to the
intensity, formality, or tolerance there, however.  It could be they
have goals, and you need more familiarity with Usenet protocol to be
understood, and not merely excluded.  I am not saying that c-l-py vets
don't have goals; just that they're not the same as the dev vets'.

I see how c-l-py doesn't represent the full interests of Python,
although I can't attest to whether it used to.  Naturally, among any
person or people, conflicts arise, dilemmas arise, and c-l-py vets
don't solve them in the same manner, or with the same results, that
dev vets do.  The long term direction of this is dissent, struggle,
and mutiny.  Logically, one of the c-l-py posters, not necessarily the
vets, will fork the source, it will become popular, and Pythoneers
will no longer be able to cut-and-paste source to share.  It is a sad
destiny, but with all the authorities, veterans, and movers and
shakers cloistered away in an entrance-restricted, exclusive-
membership corner, the newbies won't see the long-term consequences.
We get our direction from the adults, and they aren't here.  And, with
the community split in two, newbies will not get the answers they
need, and we'll wither away.

The motive for the fork could be anything.  It could be a coup
d'elite, a lunge for power, or an honest but shallow improvement
attempt, from someone who doesn't know it will divide the community,
or doesn't know to care.

You have proposed that the precaution is greater control: it won't
happen if it can't happen; and if it can happen, it will.  I don't
think either of those premises need proof, so the conclusion is
imminent.  If two parties want two different things, they'll both get
them.

There are many people to control.  They include the newbies, who have
taken your word for many characteristics of the language and the
group.  They include the vets who already know them.  Do you appoint
yourself sheriff?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Any way to use a range as a key in a dictionary?

2009-03-27 Thread andrew cooke
andrew cooke wrote:
> i don't completely follow what you are doing, but i currently use the
> following to find a transition in a finite automaton for a regular
> expression, and i suspect it's similar to what you want.

i get the impression the original poster went away, and maybe they just
wanted dict.get(x, default) anyway, but i ended up needing this, so here
it is.  it makes a vague attempt to trade memory for lookup speed (which
will be in a tight loop) and is for open intervals (eg integer intervals,
not floats).

class IntervalMap(dict):
'''
Note - this is for open intervals!  This means it will not work as
expected for continuous variables (which will overlap when two intervals
share a single boundary value).  In other words, you cannot store
(1,2) and (2,3) together because both contain 2.
'''

def __init__(self):
# None is used as a flag to indicate that a new index is needed
self.__index = None

def index(self):
'''
Build the internal indices.  Called automatically when necessary.
'''
second = lambda x: x[1]
self.__intervals = list(sorted(self.keys(), key=second))
self.__index = list(map(second, self.__intervals))

def __setitem__(self, interval, value):
# these are rather inefficient, but perhaps useful during development
assert None == self[interval[0]], 'Overlap'
assert None == self[interval[1]], 'Overlap'
self.__index = None
super(IntervalMap, self).__setitem__(interval, value)

def __getitem__(self, point):
'''
The argument here is a single value, not an interval.
'''
if self.__index is None:
self.index()
if self.__index:
index = bisect_left(self.__index, point)
if index < len(self.__index):
# keep interval for identity on retrieval, just in case
(a, b) = interval = self.__intervals[index]
if a <= point <= b:
return super(IntervalMap, self).__getitem__(interval)
return None

def __delitem__(self, interval):
self.__index = None
super(IntervalMap, self).__delitem__(interval)

andrew

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


Re: Any way to use a range as a key in a dictionary?

2009-03-27 Thread Paul Rubin
Carl Banks  writes:
> Not necessarily: if the hash calculation for x is expensive enough the
> get version would still be faster. 

Yeah, the get version with the special marker value is just ugly IMO,
as is the version with exceptions.  Maybe there should be a two-value
version:

   found, value = d.xget(key [,default])

xget returns a 2-tuple, the first element of which is a boolean
indicating whether the key was present.  The second is the value (if
present) or the default (if supplied), or None.

Another possible interface:

   values = d.vget(key)

This returns a list containing the values found for the key, or an
empty list if none are found.  In the case where d is a dict, 
the list is therefore always either 1-element or empty, but one
could imagine other mapping types where longer lists could come back.
--
http://mail.python.org/mailman/listinfo/python-list


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread skip

Andrew> c.l.python used to be the core of a community built around a
Andrew> language.  It no longer is.  It is a very useful place, where
Andrew> some very helpful and knowledgeable people hang out and give
Andrew> advice, but instead of representing the full interests of the
Andrew> Python community it is now very much a resource for helping new
Andrew> users.

Two observations:

* The Python community has grown significantly, especially in the past
  couple years.  It's quite understandable that the bulk of
  comp.lang.python participants now are new users.  Also, as the most
  readily visible "hangout", it's the natural place where most new users
  will come to get help.  The help and tutor mailing lists, IRC, various
  other forums and subject-specific mailing lists are all much less
  visible.

* As the community grows it's difficult for there to be one place where
  everybody congregates.  The needs of different elements of the Python
  "family" differ.  You will find lots of scientific users more involved
  with scipy, matplotlib and ipython mailing lists, for example.  I'm
  sure Blender has some sort of online community for its users.  The
  people doing GUI programming with PyGtk probably tend to gravitate
  there.  The core developers spend much of their time at python-dev.
  In the end, it winds up being more efficient for those subsections of
  the overall Python user base to participate where they can either get
  the most help, offer the most assistance, or contribute the most to
  Python development or advocacy.  It's too big for one size fits all.

An anecdote.  I started using Sun workstations back about the time the sales
reps were delivering them out of the back of their cars.  Heck, I remember
the first one at Lawrence Livermore Lab sat idle for quite awhile because
there was no software at all.  No OS.  Nothing.  Probably just a boot
loader.  Back then if you had a problem with, say, dbx, vi or cc, you called
Sun and after a couple transfers you were talking to the software engineer
who directly developed or maintained the recalcitrant program or library.
Fast forward about 25 years.  I haven't spoken directly to a Sun employee in
years.  I don't even think the company I work for buys its Sun computers
directly from Sun (we buy a lot of them).  It's disappointing in some ways,
but I doubt it would be very efficient if all people who had problems with
Sun's C compiler were patched directly through to the head of the compiler
group at Sun.  They've grown.  (Well, up until relatively recently.)  Their
user base has grown.  There's no way they could manage their customer
interactions today the same way they managed them 25 years ago.

-- 
Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ban Xah Lee

2009-03-27 Thread Xah Lee
over the past 15 years, every few months i got emails from authors for
permission request of materials on my website.

today, while searching for my name on google, i found a result in
books.google.com . Out of curiosity, i searched my name in
books.google.com, and here's a hilarious result:

Machine Learning and Data Mining in Pattern Recognition: 5th
International Conference, MLDM 2007, Leipzig, Germany, July 18-20,
2007, Proceedings (Lecture ... / Lecture Notes in Artificial
Intelligence) (Paperback)
by Petra Perner (Editor)

http://books.google.com/books?id=CE1QzecoVf4C&pg=PA401&dq=xah+lee#PPA401,M1

Hilarious! (^o^)

He says: “... Barely considering du, he is easily to be neglected”.
What the hell does that mean!!? :)

  Xah
∑ http://xahlee.org/

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


Re: is there a way to collect twitts with python?

2009-03-27 Thread alex23
On Mar 28, 3:54 am, "'2+"  wrote:
> i found a guy twittin supercollider code
> if there's a lib already any good pointers to start learnin thangs at?

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


Re: file transfer over LAN

2009-03-27 Thread Gabriel Genellina
En Thu, 26 Mar 2009 21:52:18 -0300, MRAB   
escribió:

prakash jp wrote:


On generating log file on remote systems(say client), I want to  
transfer them to the Network Admins(say Server) Computer. In doing so  
all the contents of the log file r not transfered, only part of the  
file.



f=open(r'C:\\Python25\src\log.txt', 'rb')


(better if all of those \ are doubled)


s.send(str(fsize).zfill(8))
s.send(f.read())


You might want to try sendall() instead of send(). send() doesn't
guarantee to send all the data, but instead returns the number of bytes
that it did actually send. sendall(), on the other hand, will keep
going until all of the data is sent.


Yes, I'd say this is the OP's problem. Same happens on the receiving side,  
unfortunately there is no recvall() method.

A safer approach would be to use s.makefile and shutil.copyfileobj:

(sender) (untested)

s.send(str(fsize).zfill(8))
sfile = s.makefile("wb")
shutil.copyfileobj(f, sfile)
sfile.close()
s.close()
f.close()

(receiver):

fsize=int(conn.recv(8))
sfile = conn.makefile("rb")
shutil.copyfileobj(sfile, f)
sfile.close()
conn.close()
s.close()
f.close()

http://docs.python.org/library/socket.html#socket.socket.makefile
http://docs.python.org/library/shutil.html#shutil.copyfileobj

--
Gabriel Genellina

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


Getting the type of an AST Node

2009-03-27 Thread Nick Edds
Is there an easy way to figure out what the type of an AST Node is? If I
have a node n, doing type(n) doesn't help because it gives me , but what I really want is If, or And, or whatever node type the
node actually is. I could always just look at n.__repr__(), because the repr
for each node type is in the format NodeType(x), but this seems like an
inelegant solution.
--
http://mail.python.org/mailman/listinfo/python-list


Re: c.l.py dead, news at 11 (was Re: Mangle function name with decorator?)

2009-03-27 Thread Aahz
In article ,
andrew cooke  wrote:
>
>c.l.python used to be the core of a community built around a language.  It
>no longer is.  It is a very useful place, where some very helpful and
>knowledgeable people hang out and give advice, but instead of representing
>the full interests of the Python community it is now very much a resource
>for helping new users.

It seems to me that you're making two separate assertions here.  I don't
think that c.l.py ever represented the full interests of the Python
community once python-dev took off (which was essentially before I
started using Python in 1999).  I do think that c.l.py is still in many
ways the core of the community, because it's the only hangout where the
disparate parts of the community come together, but the core has
diminished to a small fraction of the whole community.

>I feel quite strongly about this.  I thought that c.l.python was almost
>exceptional in the range (the perl group was another, similar community
>back then).  I do worry that someone might have screwed up in a quite
>major way, and that Python will suffer seriously, in the longer term, as a
>result.

>From my POV as someone who has been observing Usenet for eighteen years,
c.l.py is *still* an exceptional community.  And while Usenet is now an
Internet backwater, there's far too much useful traffic to claim that
Usenet is in any danger of dying.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22
--
http://mail.python.org/mailman/listinfo/python-list


Re: Import aliases for moving a module?

2009-03-27 Thread Gabriel Genellina

En Thu, 26 Mar 2009 15:23:50 -0300, zopyxfil...@googlemail.com
 escribió:


For a while a maintained a Python package  'foo' with a number of
modules (including a nested structure of module). Now the package
moved into a namespace package
'a.b.foo'. What is the way to approach making old code work with the
new package in order
that imports like

 import foo.bar.xxx
 or
 from foo.bar import xxx

remain working for existing code.


A quick and dirty solution is to have a foo package with an __init__.py
that imports *every* single name in the old package, from the new one, and
puts it in sys.modules under the old name.

C:\temp>tree /f a
C:\TEMP\A
│   __init__.py
│
└───b
 │   __init__.py
 │
 └───foo
 one.py
 three.py
 two.py
 __init__.py


C:\temp>tree /f foo
C:\TEMP\FOO
 __init__.py

C:\temp>type foo\__init__.py
import warnings
warnings.warn("The 'foo' package is obsolete; use 'a.b.foo' instead",
 DeprecationWarning, 2)

import sys
 from a.b import foo
 from a.b.foo import one, two
sys.modules['foo.one'] = one
sys.modules['foo.two'] = two

# very last line!
sys.modules['foo'] = foo
# now *this* module is gone

C:\temp>type a\b\foo\one.py
print "This is one.py", __file__, __name__

C:\temp>type a\b\foo\two.py
print "This is two.py", __file__, __name__

C:\temp>type a\b\foo\three.py
print "This is three.py", __file__, __name__

All other __init__.py files are empty. Now, you can import foo and its
contents under the old and new names:

py> import foo
__main__:1: DeprecationWarning: The 'foo' package is obsolete; use
'a.b.foo' ins
tead
This is one.py a\b\foo\one.pyc a.b.foo.one
This is two.py a\b\foo\two.pyc a.b.foo.two
py> import foo.one
py> import a.b.foo.one
py> a.b.foo.one

py> foo.one

py> foo.one is a.b.foo.one
True
py> import foo.two
py> import a.b.foo.two

Note that one.py and two.py are imported only once. *BUT* notice what
happens when you import three.py, that was NOT included in foo\__init__.py:

py> import foo.three
This is three.py a\b\foo\three.pyc foo.three
py> import a.b.foo.three
This is three.py a\b\foo\three.pyc a.b.foo.three

That module was imported *twice*. So it's important to pre-import (inside
foo\__init__.py) *every* name that was present in the old foo package. If
this is not feasible (there are many names, or loading all of them would
be too slow, or whatever) you may implement a "lazy" importer. See
__init__.py in the email package for an example.

--
Gabriel Genellina

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


Re: Problems with background processes on Windows

2009-03-27 Thread Tim Roberts
geoff.ba...@gmail.com wrote:
>
>The following code behaves differently on Windows and Linux using
>Python 2.5.2. The Linux behaviour is what I expect in both places :)
>Perhaps somebody could help explain this. Or maybe it is a Python bug.
>Or a Windows feature...
>...
>On Windows if I run "communicate.py" it does not return for 10
>seconds, i.e. until the "grandchild" background process terminates. On
>Linux it returns immediately as I would expect.
>
>If I replace "p.communicate()" with "p.wait()" it returns immediately
>on both. If I don't point stdin, stdout and stderr of the child
>process to os.devnull then it will wait 10 seconds on Linux also,
>which I'd also expect as we can't collect info from these places if
>they've been forwarded elsewhere. It seems like Windows somehow
>doesn't notice this.

If you trace through this:
python -m trace --trace communicate.py

you'll see that it hangs in subprocess in the stdout_thread waiting for
stdout to close.

I'm not sure I expect this to work as you expect.  When you open a null
device, it's just another file handle.  Why should the behavior be
different?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >