comp.lang.python - 25 new messages in 14 topics - digest
comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en
comp.lang.python@googlegroups.com
Today's topics:
* Function that knows its argument's variable name - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/ed0c23c18ff2f584?hl=en
* class inheritance - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/2512697a901d4752?hl=en
* Timer - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/b2122e0f9758428f?hl=en
* Dynamic Class Creation - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/2bd3e29c06ee0899?hl=en
* using DictionaryServices module to get work with python2.6 #OSXspecific - 1
messages, 1 author
http://groups.google.com/group/comp.lang.python/t/ecef71ab683e79be?hl=en
* Python bindings tutorial - 5 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/73dcf6c0b97465aa?hl=en
* How to handle file uploads with http.server - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/fae1c3826fd6edaf?hl=en
* to pass self or not to pass self - 3 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/02e5000548314c86?hl=en
* How to add a library path to pythonpath ? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/2307dae70d0e5aaf?hl=en
* Castrated traceback in sys.exc_info() - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/f2cbe10933438a5d?hl=en
* datetime string conversion error - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/2944ba75fca9d570?hl=en
* Swapping Content of Two Dictionaries. - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/00ff4164b1813b60?hl=en
* question about tkinter - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/b2fa77c91f788a85?hl=en
* multiprocessing on freebsd - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/4ff8efd8478d1d76?hl=en
==============================================================================
TOPIC: Function that knows its argument's variable name
http://groups.google.com/group/comp.lang.python/t/ed0c23c18ff2f584?hl=en
==============================================================================
== 1 of 2 ==
Date: Tues, Mar 16 2010 11:30 pm
From: Tino Wildenhain
Hi,
Am 14.03.2010 12:58, schrieb Helge Stenström:
> I want to write function that prints a value of a variable, for
> debugging. Like:
>
> with
>
> myVariable = "parrot"
> otherVariable = "dead"
>
> probe(myVariable)
> probe(otherVariable)
>
> instead of the longer
>
> print "myVariable = ", myVariable
> print "otherVariable = ", otherVariable
>
> Is that even possible?
>
> The function would look like
>
> def probe(var):
> nameOfVar = someMagic(var)
> print nameOfVar, " = ", var
>
> but can someMagic(var) find the variable name? Is that possible?
apart from very hackery, why don't you just use:
def probe(**vars):
for varname,value in vars.items():
print "%s = %r" % (varname,value)
and call it like that:
probe(myvar="foo")
probe(othervar="bar")
or even
probe(myvar=myvar) (if myvar was assigned before)
please note introspective approaches have a very narrow field
where they can work - as already shown in other posts: you can have
values w/o names and also more then one name to a value (or object).
Regards
Tino Wildenhain
== 2 of 2 ==
Date: Wed, Mar 17 2010 6:20 am
From: Helge Stenström
Thank you to all who answered. Inspection is apparently possible, but
too complex for me.
Greg's solution does what I want, inserting "" is no problem.
/Helge
> Not exactly, but you can come close with a little hackery.
>
> import sys
>
> def print_var(name):
> print name, "=", sys._getframe(1).f_locals[name]
>
> def f():
> fred = 42
> mary = "christmas"
> print_var("fred")
> print_var("mary")
>
> f()
>
> --
> Greg
==============================================================================
TOPIC: class inheritance
http://groups.google.com/group/comp.lang.python/t/2512697a901d4752?hl=en
==============================================================================
== 1 of 1 ==
Date: Wed, Mar 17 2010 12:13 am
From: Dennis Lee Bieber
On Tue, 16 Mar 2010 07:35:54 -0500, Dave Angel <davea@ieee.org>
declaimed the following in gmane.comp.python.general:
> If I recall correctly, APL has a *fuzz* value, which is used in all(?)
> comparisons. But I do not recall anything about how it was defined. I do
> recall that you could change the threshold, and suspect it was relative
> to the operands. For symmetry, it would probably have to be relative to
> the average of the two values, or some such.
I didn't do enough with APL back in 1980 to get to that point (I
needed 2 credits to graduate, so took a 3 credit independent study of
APL -- where my biggest program was to turn a Tektronix storage display
terminal into the worlds most expensive Etch-a-Sketch)
REXX has a similar (from the Regina manual):
"""
The NUMERIC statement is used to control most aspects of arithmetic
operations. It has three distinct forms: DIGITS, FORM and FUZZ; which to
choose is given by the second token in the instruction:
DIGITS
Is used to set the number of significant digits in arithmetic
operations. The initial value is 9, which is also the default value if
expr is not specified. Large values for DIGITS tend to slow down some
arithmetic operations considerably. If specified, expr must be a
positive integer.
FUZZ
Is used in numeric comparisons, and its initial and default value is
0. Normally, two numbers must have identical numeric values for a number
of their most significant digits in order to be considered equal. How
many digits are considered is determined by DIGITS. If DIGITS is 4, then
12345 and 12346 are equal, but not 12345 and 12356. However, when FUZZ
is nonzero, then only the DIGITS minus FUZZ most significant digits are
checked. E.g. if DIGITS is 4 and FUZZ are 2, then 1234 and 1245 are
equal, but not 1234 and 1345.
The value for FUZZ must be a nonnegative integer, and less than the
value of DIGITS. FUZZ is seldom used, but is useful when you want to
make comparisons less influenced by inaccuracies. Note that using with
values of FUZZ that is close to DIGITS may give highly surprising
results.
"""
--
Wulfraed Dennis Lee Bieber KD6MOG
wlfraed@ix.netcom.com HTTP://wlfraed.home.netcom.com/
==============================================================================
TOPIC: Timer
http://groups.google.com/group/comp.lang.python/t/b2122e0f9758428f?hl=en
==============================================================================
== 1 of 2 ==
Date: Wed, Mar 17 2010 1:43 am
From: Sam Bull
I'm writing a pyGTK program, and I need to display the contents of a
window for a few seconds before automatically moving on. I have tried
using the time.sleep method, but this has problems, such as the program
becoming unresponsive.
I have now attempted to use a timer, but this does not seem to run the
function at the end of the time. The code of my latest attempt:
def next(self=None, testnum=10, testspeed=5):
self.count += 1
#Sets label, telling the user the next word to memorise
self.nobtns.set_markup("Word %s is: %s" % (self.count,
self.words[self.count-1]))
self.nobtns.show()
if self.count == testnum: #When all words are shown
self.nobtns.hide()
else:
self.timer = threading.Timer(testspeed, self.next, [testnum,
testspeed])
self.timer.start()
Putting a print statement at the beginning of the function, I can see
that the function is not being run by the timer. Any help on getting
this working would be appreciated.
Thanks,
Sam Bull
== 2 of 2 ==
Date: Wed, Mar 17 2010 2:16 am
From: Peter Otten <__peter__@web.de>
Sam Bull wrote:
> I'm writing a pyGTK program, and I need to display the contents of a
> window for a few seconds before automatically moving on. I have tried
> using the time.sleep method, but this has problems, such as the program
> becoming unresponsive.
>
> I have now attempted to use a timer, but this does not seem to run the
> function at the end of the time. The code of my latest attempt:
>
> def next(self=None, testnum=10, testspeed=5):
> self.count += 1
> #Sets label, telling the user the next word to memorise
> self.nobtns.set_markup("Word %s is: %s" % (self.count,
> self.words[self.count-1]))
> self.nobtns.show()
> if self.count == testnum: #When all words are shown
> self.nobtns.hide()
> else:
> self.timer = threading.Timer(testspeed, self.next, [testnum,
> testspeed])
> self.timer.start()
>
> Putting a print statement at the beginning of the function, I can see
> that the function is not being run by the timer. Any help on getting
> this working would be appreciated.
GUI toolkits usually have their own way of handling timeouts. I don't know
pygtk, but the following looks promising:
http://www.pygtk.org/pygtk2tutorial/ch-TimeoutsIOAndIdleFunctions.html
Peter
==============================================================================
TOPIC: Dynamic Class Creation
http://groups.google.com/group/comp.lang.python/t/2bd3e29c06ee0899?hl=en
==============================================================================
== 1 of 1 ==
Date: Wed, Mar 17 2010 1:54 am
From: Gerard Flanagan
Josh English wrote:
> Chris,
>
> Thanks. This worked for the attributes, but I think the tactic is
> still misleading. There are child elements I can't quite determine how
> to deal with:
>
> <market code='anlg' tier='ProMarket' mail='True'>
> <title field="pref">Analog Science Fiction and Fact</title>
> <nickname>Analog</nickname>
> <keyword>Science Fiction</keyword>
> <keyword>First Contact</keyword>
> <keyword>Hard Science Fiction</keyword>
> <address>
> <attnline>Stanley Schmidt, Editor</attnline>
> <address1>267 Broadway, 4th Floor</address1>
> <address2>New York, NY 10007-2352</address2>
> </address>
> <website>http://www.analogsf.com</website>
> </market>
>
> A child element with text and an attribute or two, for example, pose a
> problem. I can call Market.title but should I try Market.title.field
> or Market.title_field.
>
> Multiple elements, such as keywords, are allowed in xml but harder to
> map to the object. I don't know if I want to go create a list and
> methods for accessing those keywords as a list, or redefine the rules
> of my XML to not allow multiple child elements with the same tag. I
> can't decide.
>
> Then the address is a bit of a bear.
>
> In short, I have to figure out the whole object interface to the XML
> and how I want that to work.
>
Have you heard of or considered PyXB (http://pyxb.sourceforge.net/)? Not
that I've much experience with it, but you can use it to generate python
code from XML Schema files, and, I think, WSDL definitions. It's a bit
of a rabbit hole, but then isn't that half the fun!
The following might give you the idea. You start with a Schema
schema.xsd, generate a python module from it, then read in some XML with
the generated classes to get your custom objects.
---------------- schema.xsd ----------------------
<xs:schema targetNamespace="http://www.josh.com/schema/0.1"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:josh="http://www.josh.com/schema/0.1">
<xs:element name="market" type="josh:MarketType"/>
<xs:complexType name="MarketType">
<xs:sequence>
<xs:element name="title" type="josh:TitleType"/>
<xs:element name="nickname" type="xs:string"/>
<xs:element name="keyword" type="xs:string"
maxOccurs="unbounded"/>
<xs:element name="address" type="josh:USAddress"/>
<xs:element name="website" type="xs:string"/>
</xs:sequence>
<xs:attributeGroup ref="josh:MarketAttributes"/>
</xs:complexType>
<xs:complexType name="TitleType">
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="field" type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:attributeGroup name="MarketAttributes">
<xs:attribute name="code" type="xs:string"/>
<xs:attribute name="tier" type="xs:string"/>
<xs:attribute name="mail" type="xs:string"/>
</xs:attributeGroup>
<xs:complexType name="Address" abstract="true">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="USAddress">
<xs:complexContent>
<xs:extension base="josh:Address">
<xs:sequence>
<xs:element name="state" type="josh:USState"
minOccurs="0"/>
<xs:element name="zip" type="xs:positiveInteger"
minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:simpleType name="USState">
<xs:restriction base="xs:string">
<xs:enumeration value="AK"/>
<xs:enumeration value="AL"/>
<xs:enumeration value="AR"/>
<!-- and so on ... -->
</xs:restriction>
</xs:simpleType>
</xs:schema>
---------------- genbindings.sh ---------------------------
#!/bin/sh
pyxbgen -u schema.xsd -m market_binding -r
---------------- demo.py -----------------------------------
s = """<?xml version="1.0"?>
<josh:market
xmlns:josh="http://www.josh.com/schema/0.1"
code="anlg"
tier="ProMarket"
mail="True">
<title field="pref">Analog Science Fiction and Fact</title>
<nickname>Analog</nickname>
<keyword>Science Fiction</keyword>
<keyword>First Contact</keyword>
<keyword>Hard Science Fiction</keyword>
<address>
<name>Stanley Schmidt, Editor</name>
<street>267 Broadway, 4th Floor</street>
<city>New York</city>
</address>
<website>http://www.analogsf.com</website>
</josh:market>
"""
import xml.dom.minidom
import market_binding
market =
market_binding.CreateFromDOM(xml.dom.minidom.parseString(s).documentElement)
print market.tier
print market.code
print market.keyword
assert len(market.keyword) == 3
print market.address.name
print market.toxml()
==============================================================================
TOPIC: using DictionaryServices module to get work with python2.6 #OSXspecific
http://groups.google.com/group/comp.lang.python/t/ecef71ab683e79be?hl=en
==============================================================================
== 1 of 1 ==
Date: Wed, Mar 17 2010 1:56 am
From: Mark Lawrence
Shashwat Anand wrote:
> I wanted to use dictionary in my OSX terminal.
> So I wrote a function dict() in my ~/.bash_profile
>
> dict () {
> python2.5 -c 'import sys, DictionaryServices; word = "
> ".join(sys.argv[1:]); print DictionaryServices.DCSCopyTextDefinition(None,
> word, (0, len(word)))' $@
> }
>
> here is the output:
>
> Shashwat-Anands-MacBook-Pro:Desktop l0nwlf$ dict lone wolf
> noun
> a person who prefers to act or be alone.
>
> The question is why not :
> DictionaryServices.DCSCopyTextDefinition(None, word, (0, len(word))) works
> with python2.6 ?
> Is DictionaryService module not available for python2.6 ?
>
> Here is the stack-trace:
>
> Shashwat-Anands-MacBook-Pro:Desktop l0nwlf$ python
> Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
> [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import DictionaryServices
>>>> word = "lone wolf"
>>>> DictionaryServices.DCSCopyTextDefinition(None, word, (0, len(word)))
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> IndexError: NSRangeException - *** -[OC_PythonString
> _createSubstringWithRange:]: Range or index out of bounds
>
> Ofcourse it doesnt work with python2.7 too. Is this OSX specific issue ? Can
> I make it work with my compiled version of python ? Is there any workaround
> ?
>
>
Are you thinking of this?
http://pypi.python.org/pypi/pyobjc-framework-DictionaryServices/2.2
HTH.
Mark Lawrence
==============================================================================
TOPIC: Python bindings tutorial
http://groups.google.com/group/comp.lang.python/t/73dcf6c0b97465aa?hl=en
==============================================================================
== 1 of 5 ==
Date: Wed, Mar 17 2010 2:08 am
From: "MikeLisanke@gmail.com"
On Mar 16, 3:12 pm, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
> En Tue, 16 Mar 2010 13:20:40 -0300, Johny <pyt...@hope.cz> escribió:
>
> > Is there any tutorial how to write a bindings for a exe ( dos)
> > program?
> > I would like to run it from a Python directly
> > ( using import command and a particular function from the binding)
> > not using os.system command.
>
> Do you mean that you want to execute a particular function in the .exe
> program?
> That's not possible (ok, you *could* do that if you work hard enough, but
> that's not how things are usually done)
>
> --
> Gabriel Genellina
Gabriel,
Its interesting you've mentioned the hard work involved in this
interface (binding to an EXE instead of a DLL). A year or more ago I
was looking at interfacing IPMITOOL to python. Do to the problems
incurred with swig/python I switched to a running the process through
its command-line interface. I always felt the problems in interfacing
python to an EXE should be worked on (to minimize them), making the
direct use of an EXE API's a routine task. I understand some of the
problems using an EXE (not running all of its startup code but
enough for its proper operation). Have you found this a recurring
question? Thanks.
Regards, Mike
== 2 of 5 ==
Date: Wed, Mar 17 2010 2:36 am
From: Stefan Behnel
MikeLisanke@gmail.com, 17.03.2010 10:08:
> Its interesting you've mentioned the hard work involved in this
> interface (binding to an EXE instead of a DLL). A year or more ago I
> was looking at interfacing IPMITOOL to python. Do to the problems
> incurred with swig/python I switched to a running the process through
> its command-line interface. I always felt the problems in interfacing
> python to an EXE should be worked on (to minimize them), making the
> direct use of an EXE API's a routine task. I understand some of the
> problems using an EXE (not running all of its startup code but
> enough for its proper operation). Have you found this a recurring
> question? Thanks.
I think the point here is that executable binaries are not supposed to be
used as libraries. Libraries are. That's the difference between a DLL and
an executable in the first place. To run an executable, execute it. The
subprocess module is the tool of choice here. To use a DLL, link against it.
Stefan
== 3 of 5 ==
Date: Wed, Mar 17 2010 4:14 am
From: Dave Angel
Stefan Behnel wrote:
> <div class="moz-text-flowed" style="font-family:
> -moz-fixed">MikeLisanke@gmail.com, 17.03.2010 10:08:
>> Its interesting you've mentioned the hard work involved in this
>> interface (binding to an EXE instead of a DLL). A year or more ago I
>> was looking at interfacing IPMITOOL to python. Do to the problems
>> incurred with swig/python I switched to a running the process through
>> its command-line interface. I always felt the problems in interfacing
>> python to an EXE should be worked on (to minimize them), making the
>> direct use of an EXE API's a routine task. I understand some of the
>> problems using an EXE (not running all of its startup code but
>> enough for its proper operation). Have you found this a recurring
>> question? Thanks.
>
> I think the point here is that executable binaries are not supposed to
> be used as libraries. Libraries are. That's the difference between a
> DLL and an executable in the first place. To run an executable,
> execute it. The subprocess module is the tool of choice here. To use a
> DLL, link against it.
>
> Stefan
>
There's no real reason parts of an exe cannot be exported, same as a
dll. They are in fact the same structure. And in fact many other files
in the Windows environment are also the same structure, from fonts to ocx's
Saying they're "not supposed to be used" is like saying that a python
module should not have an
if __name__ == "__main__":
section. After all, who could want to both run a file, and import the
same file??
DaveA
== 4 of 5 ==
Date: Wed, Mar 17 2010 5:03 am
From: "Alf P. Steinbach"
* Dave Angel:
> Stefan Behnel wrote:
>> <div class="moz-text-flowed" style="font-family:
>> -moz-fixed">MikeLisanke@gmail.com, 17.03.2010 10:08:
>>> Its interesting you've mentioned the hard work involved in this
>>> interface (binding to an EXE instead of a DLL). A year or more ago I
>>> was looking at interfacing IPMITOOL to python. Do to the problems
>>> incurred with swig/python I switched to a running the process through
>>> its command-line interface. I always felt the problems in interfacing
>>> python to an EXE should be worked on (to minimize them), making the
>>> direct use of an EXE API's a routine task. I understand some of the
>>> problems using an EXE (not running all of its startup code but
>>> enough for its proper operation). Have you found this a recurring
>>> question? Thanks.
>>
>> I think the point here is that executable binaries are not supposed to
>> be used as libraries. Libraries are. That's the difference between a
>> DLL and an executable in the first place. To run an executable,
>> execute it. The subprocess module is the tool of choice here. To use a
>> DLL, link against it.
>>
>> Stefan
>>
> There's no real reason parts of an exe cannot be exported, same as a
> dll. They are in fact the same structure. And in fact many other files
> in the Windows environment are also the same structure, from fonts to ocx's
>
> Saying they're "not supposed to be used" is like saying that a python
> module should not have an
>
> if __name__ == "__main__":
>
> section. After all, who could want to both run a file, and import the
> same file??
A Windows DLL has defined initialization and cleanup per process and per thread.
This means that e.g. static variables can be properly initialized when you load
the DLL in order to use its functions (I'm skipping discussion of subtle
problems, but that's the essence).
A Windows EXE has (only) a single entry point which is for process startup. It
invokes the EXE's behavior-as-a-program. There is no way to use it to e.g.
initialize static variables in order to use exported functions.
Hence Mike Lisanke's idea of "not running all of its startup code but enough for
its proper operation" is generally not possible.
An EXE can be used as a kind of server, /if/ it is designed for that. In
particular it can be a COM server, allowing access of its functionality from any
COM-enabled binding, which for Python would mean OLE Automation (COM, OLE,
Automation: this is Microsoft technology, we're talking Windows EXEs here). But
a Python binding to EXEs in general can't, as far as I can see, make assumptions
about any particular kind of server being implemented by the EXE.
Cheers & hth.,
- Alf
== 5 of 5 ==
Date: Wed, Mar 17 2010 5:18 am
From: Stefan Behnel
Dave Angel, 17.03.2010 12:14:
> Stefan Behnel wrote:
>> I think the point here is that executable binaries are not supposed to
>> be used as libraries. Libraries are. That's the difference between a
>> DLL and an executable in the first place. To run an executable,
>> execute it. The subprocess module is the tool of choice here. To use a
>> DLL, link against it.
>>
> There's no real reason parts of an exe cannot be exported, same as a
> dll. They are in fact the same structure. And in fact many other files
> in the Windows environment are also the same structure, from fonts to ocx's
So, because you can, you'd also try to link against fonts then, I guess?
I hope you notice that what you and me said isn't contradictory. But
there's a reason why there are libraries and executables, and there's no
reason you *should* export anything from an executable - that's what
libraries are there for. That's my point.
Besides, nothing guarantees that it's safe to call stuff that an executable
exports. The executable may well require some setup code that it only
executes when it is properly started.
Stefan
==============================================================================
TOPIC: How to handle file uploads with http.server
http://groups.google.com/group/comp.lang.python/t/fae1c3826fd6edaf?hl=en
==============================================================================
== 1 of 1 ==
Date: Wed, Mar 17 2010 2:12 am
From: "Neil Blue"
Thanks Gabriel
Yep, that looks like the same one.
Cheers
Neil
-----Original Message-----
From: Gabriel Genellina [mailto:gagsl-py2@yahoo.com.ar]
Sent: 17 March 2010 02:08
To: python-list@python.org
Subject: Re: How to handle file uploads with http.server
En Thu, 11 Mar 2010 07:30:24 -0300, Neil Blue <Neil.Blue@biowisdom.com>
escribió:
> I have a basic http.server instance running (class
> HTTPHandler(http.server.BaseHTTPRequestHandler), with python 3.1, and
> I would like to upload files with multipart forms.
>
> def do_POST(self):
> ctype, pdict = cgi.parse_header(self.headers['Content-Type'])
> if ctype=='multipart/form-data':
> print('parsing...')
> query=cgi.parse_multipart(self.rfile, pdict)
> print(query)
>
> However the file never seems to finish being parsed. There are no
> errors, but the call hangs at: query=cgi.parse_multipart(self.rfile,
> pdict)
This may be related to this bug:
http://bugs.python.org/issue8077
reported last week by Mitchell L. Model in this thread:
http://groups.google.com/group/comp.lang.python/t/8a7752bd79d5f5d6/
--
Gabriel Genellina
*********************************************
The information contained in this message is likely to be confidential. It is intended only for the person named above. Any dissemination, distribution, copying, disclosure or use of this message or its contents unless authorised by BioWisdom Ltd is strictly prohibited. Any views or opinions expressed within this e-mail are those of the author and do not necessarily represent those of BioWisdom Ltd. If you have received this message in error, please immediately notify us and delete it. Thank you. Registered Office: BioWisdom Ltd, Harston Mill, Harston, Cambridge, CB22 7GG. Registered in England: (GB) 3861669. VAT registered: (GB) 750899881. Tel: +44 (0)1223 874800, Fax: +44 (0) 1223 874801, Internet:www.biowisdom.com
*********************************************
==============================================================================
TOPIC: to pass self or not to pass self
http://groups.google.com/group/comp.lang.python/t/02e5000548314c86?hl=en
==============================================================================
== 1 of 3 ==
Date: Wed, Mar 17 2010 2:12 am
From: Bruno Desthuilliers
Patrick Maupin a écrit :
> On Mar 16, 1:59 pm, Jason Tackaberry <t...@urandom.ca> wrote:
>> Why not create the bound methods at instantiation time, rather than
>> using the descriptor protocol which has the overhead of creating a new
>> bound method each time the method attribute is accessed?
>
> Well, for one thing, Python classes are open. They can be added to at
> any time. For another thing, you might not ever use most of the
> methods of an instance, so it would be a huge waste to create those.
A possible optimization would be a simple memoization on first access.
== 2 of 3 ==
Date: Wed, Mar 17 2010 3:41 am
From: Lie Ryan
On 03/17/2010 04:32 PM, Steven D'Aprano wrote:
> On Wed, 17 Mar 2010 15:57:17 +1100, Lie Ryan wrote:
>
>> Most people probably would never need to use
>> descriptor protocol directly, since the immediate benefit of descriptor
>> protocol are property(), classmethod(), and instancemethod() decorators
>> which, without descriptor protocol, would never become a possibility.
>
>
> There's an instancemethod decorator? Where?
>
> Are you thinking of staticmethod? "instancemethod", if you mean what I
> think you mean, doesn't need a decorator because it is the default
> behaviour for new-style classes.
Whoops... yep, sorry about that. Got all it up the mixed head in...
== 3 of 3 ==
Date: Wed, Mar 17 2010 6:16 am
From: Lie Ryan
On 03/17/2010 08:12 PM, Bruno Desthuilliers wrote:
> Patrick Maupin a écrit :
>> On Mar 16, 1:59 pm, Jason Tackaberry <t...@urandom.ca> wrote:
>>> Why not create the bound methods at instantiation time, rather than
>>> using the descriptor protocol which has the overhead of creating a new
>>> bound method each time the method attribute is accessed?
>>
>> Well, for one thing, Python classes are open. They can be added to at
>> any time. For another thing, you might not ever use most of the
>> methods of an instance, so it would be a huge waste to create those.
>
> A possible optimization would be a simple memoization on first access.
But what if, for example, one uses some descriptor/metaclass magic to
make it so that each subsequent access to the attribute returns a method
bound to different objects?
==============================================================================
TOPIC: How to add a library path to pythonpath ?
http://groups.google.com/group/comp.lang.python/t/2307dae70d0e5aaf?hl=en
==============================================================================
== 1 of 1 ==
Date: Wed, Mar 17 2010 3:25 am
From: "Barak, Ron"
> -----Original Message-----
> From: Mark Hammond [mailto:skippy.hammond@gmail.com]
> Sent: Wednesday, March 17, 2010 2:08 AM
> To: Barak, Ron
> Cc: Pablo Recio Quijano; python-list@python.org
> Subject: Re: How to add a library path to pythonpath ?
>
> On 17/03/2010 1:26 AM, Barak, Ron wrote:
> > Thanks for the suggestion Pable.
> > However, I really need the $PYTHONPATH to include this additional
> > library, so all Python scripts could use it.
> > In Windows I have defined PYTHONPATH as
> > c:\views\cc_view\TS_svm_ts_tool\SVMInspector\lib\, and also in the
> > Windows registry I have
> >
> HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\/version/\Python
> Path\ as
> >
> C:\Python26\Lib;C:\Python26\DLLs;C:\views\cc_view\TS_svm_ts_tool\SVMIn
> > spector\lib\;C:\Python26\Lib\lib-tk;
> > However, even with all the above, the SVMInspecor modules
> are not found.
>
> You need to create your own sub-key, with any name, under the
> PythonPath key and add your path there. The reason is that
> Python only looks for that root key when it can't sniff the
> location of the library itself based on the location of the
> executable - and in most cases it can.
> Python does however enumerate and use the sub-keys in all cases.
>
> HTH,
>
> Mark
>
Hi Mark,
Could you give an example ilustrating your suggestion ?
Thanks,
Ron.
==============================================================================
TOPIC: Castrated traceback in sys.exc_info()
http://groups.google.com/group/comp.lang.python/t/f2cbe10933438a5d?hl=en
==============================================================================
== 1 of 3 ==
Date: Wed, Mar 17 2010 3:42 am
From: Pakal
Hello
I've just realized recently that sys.exc_info() didn't return a full
traceback for exception concerned : it actually only contains the
frame below the point of exception catching.
That's very annoying to me, because I planned to log such tracebacks
with logging.critical(*****, exc_info=True), and these partial
tracebacks, like the one below, are clearly unsufficient to determine
where the problem comes from. A whole traceback, from program entry
point to exception raising point, would be much better.
2010-03-17 09:28:59,184 - pims - CRITICAL - This is just a test to
ensure critical emails are properly sent
Traceback (most recent call last):
<< HERE, lots of frames missing >>
File "test_common.py", line 34, in test_email_sending
os.open("qsdsdqsdsdqsd", "r")
TypeError: an integer is required
Is there any workaround for this ? I've thought about a custom logging
formatter, which would take both the exc_info traceback AND its own
full backtrace, and to connect them together on their relevant part,
but it's awkward and error prone... why can't we just have all the
precious traceback info under the hand there (an additional attribute
might have pointed the precise frame in which the exception was
caught).
Tanks for the attention,
Regards,
Pascal
== 2 of 3 ==
Date: Wed, Mar 17 2010 4:40 am
From: Michael Ricordeau
Hi,
to log tracebacks, you can probably try traceback module.
I use it like this :
import traceback
.... # your code
for line in traceback.format_exc().splitlines():
log.trace(line)
Le Wed, 17 Mar 2010 03:42:44 -0700 (PDT),
Pakal <chambon.pascal@gmail.com> a écrit :
> Hello
>
> I've just realized recently that sys.exc_info() didn't return a full
> traceback for exception concerned : it actually only contains the
> frame below the point of exception catching.
>
> That's very annoying to me, because I planned to log such tracebacks
> with logging.critical(*****, exc_info=True), and these partial
> tracebacks, like the one below, are clearly unsufficient to determine
> where the problem comes from. A whole traceback, from program entry
> point to exception raising point, would be much better.
>
> 2010-03-17 09:28:59,184 - pims - CRITICAL - This is just a test to
> ensure critical emails are properly sent
> Traceback (most recent call last):
> << HERE, lots of frames missing >>
> File "test_common.py", line 34, in test_email_sending
> os.open("qsdsdqsdsdqsd", "r")
> TypeError: an integer is required
>
> Is there any workaround for this ? I've thought about a custom logging
> formatter, which would take both the exc_info traceback AND its own
> full backtrace, and to connect them together on their relevant part,
> but it's awkward and error prone... why can't we just have all the
> precious traceback info under the hand there (an additional attribute
> might have pointed the precise frame in which the exception was
> caught).
>
> Tanks for the attention,
> Regards,
> Pascal
== 3 of 3 ==
Date: Wed, Mar 17 2010 6:24 am
From: Vinay Sajip
On Mar 17, 10:42 am, Pakal <chambon.pas...@gmail.com> wrote:
> Hello
>
> I've just realized recently that sys.exc_info() didn't return a full
> traceback for exception concerned : it actually only contains the
> frame below the point of exception catching.
>
> That's very annoying to me, because I planned to log such tracebacks
> withlogging.critical(*****, exc_info=True), and these partial
> tracebacks, like the one below, are clearly unsufficient to determine
> where the problem comes from. A whole traceback, from program entry
> point to exception raising point, would be much better.
>
> 2010-03-17 09:28:59,184 - pims - CRITICAL - This is just a test to
> ensure critical emails are properly sent
> Traceback (most recent call last):
> << HERE, lots of frames missing >>
> File "test_common.py", line 34, in test_email_sending
> os.open("qsdsdqsdsdqsd", "r")
> TypeError: an integer is required
>
> Is there any workaround for this ? I've thought about a customlogging
> formatter, which would take both the exc_info traceback AND its own
> full backtrace, and to connect them together on their relevant part,
> but it's awkward and error prone... why can't we just have all the
> precious traceback info under the hand there (an additional attribute
> might have pointed the precise frame in which the exception was
> caught).
>
> Tanks for the attention,
> Regards,
> Pascal
Do you have a short script which demonstrates the problem? Some more
context is needed. For example, if you have multiple threads of
execution, the traceback will only go up to the top-level function in
the thread.
Regards,
Vinay Sajip
==============================================================================
TOPIC: datetime string conversion error
http://groups.google.com/group/comp.lang.python/t/2944ba75fca9d570?hl=en
==============================================================================
== 1 of 1 ==
Date: Wed, Mar 17 2010 3:55 am
From: Dave Angel
Gabriel Genellina wrote:
> En Tue, 16 Mar 2010 20:31:11 -0300, Josh English
> <joshua.r.english@gmail.com> escribi�:
>
>> On Mar 16, 11:56 am, Jordan Apgar <twistedphr...@gmail.com> wrote:
>>
>>> here's what I'm doing:
>>> date = "2010-03-16 14:46:38.409137"
>>> olddate = datetime.strptime(date,"%Y-%m-%j %H:%M:%S.%f")
>>>
>>
>> Due to circumstances, I'm using Python 2.5.4 on one machine (2.6 on
>> the other).
>>
>> When I have a script as simple as this:
>>
>> import datetime
>>
>> datetime.datetime.strptime('2010-09-14', "%Y-%m-%d")
>>
>>
>> Running this script brings up a calendar, believe it or not. The
>> calendar displays March 2010, and shows the 22nd as a holiday. When I
>> dismiss the dialog box I get:
>> Traceback (most recent call last):
>> File "strptimetest.py", line 3, in <module>
>> datetime.datetime.strptime('2010-09-14', "%Y-%m-%d")
>> File "C:\Python25\lib\_strptime.py", line 272, in <module>
>> _TimeRE_cache = TimeRE()
>> File "C:\Python25\lib\_strptime.py", line 191, in __init__
>> self.locale_time = LocaleTime()
>> File "C:\Python25\lib\_strptime.py", line 74, in __init__
>> self.__calc_weekday()
>> File "C:\Python25\lib\_strptime.py", line 94, in __calc_weekday
>> a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
>> AttributeError: 'module' object has no attribute 'day_abbr'
>
> I'd say you have a calendar.py script somewhere along your sys.path,
> that shadows the calendar module in the standard library.
>
And to find it, you could try the following:
import datetime
print calendar.__file__
I suspect you have more problems than just that file, but perhaps
finding that one can tell you what extra package you've got installed
that shadows parts of the standard library. Try temporarily renaming it
to see if the problem goes away.
DaveA
==============================================================================
TOPIC: Swapping Content of Two Dictionaries.
http://groups.google.com/group/comp.lang.python/t/00ff4164b1813b60?hl=en
==============================================================================
== 1 of 1 ==
Date: Wed, Mar 17 2010 5:34 am
From: Peter Otten <__peter__@web.de>
Hatem Oraby wrote:
> Hello, I want to swap the content of two dictionaries, the obvious way to
> do it is:
> a = {1:"I'am A"}
> b = {2:"I'm B"}
> temp = a
> a = b
> b = temp
That can be simplified to
a, b = b, a
and is almost certainly the right approach.
> tempKeys = a.keys()
> diffKeys = a.keys() - b.keys() #I do it using set()s
>
> #item = a
> temp = {}
> for key in a.keys():
> item[key] = a[key]
>
> for key in diffKeys:
> del a[key] #delete stuff that exist in a but not b.
>
> for key in b.keys():
> a[key] = b[key]
>
> b = temp
>
> This works great as the content referenced by the dictionary is changed
> rather than changing the reference of dictionary itself so it's reflected
> by any "scope" that references the dictionary.
>
> My problem is that i need to do this operation a LOT, simply I got a
> problem that my program go through a very long loop and inside this loop
> this operation is needed to be done twice and the dictionary size ain't
> very small.
You could try
>>> a = {"a": 1, "b": 2}
>>> b = {"b": 3, "c": 4}
>>> t = a.copy()
>>> a.clear()
>>> a.update(b)
>>> b.clear()
>>> b.update(t)
>>> a
{'c': 4, 'b': 3}
>>> b
{'a': 1, 'b': 2}
> If anyone has a suggestion one how to do it faster then please feel free
> and welcome to contribute.
> Anyway, I decided to go and implement it in C to gain performance, And
Premature optimization? If you explain what you are trying to achieve
someone might come up with a way to do it without swapping dict contents.
Peter
==============================================================================
TOPIC: question about tkinter
http://groups.google.com/group/comp.lang.python/t/b2fa77c91f788a85?hl=en
==============================================================================
== 1 of 2 ==
Date: Wed, Mar 17 2010 5:24 am
From: robert schaefer
Hello,
This is my first posting to this list so please be gentle -
I am new to python and am using it on red-hat linux (I am new to that too).
I am responsible for installing open source packages (including python) onto a distributed system of linux boxes.
My question is, on python version 2.6.2 tkinter refuses to install.
Without tkinter, I cannot use Idle.
I looked at the install/configure script and hacked it a bit, but every fix only caused new problems.
There are serious issues with that script for finding necessary libraries.
We have a Sun-OS box with python version 2.5.x (I don't know the means of installation) that
tkinter installed correctly, and Idle works fine.
My question is - has anyone else noticed the problem of tkinter and red-hat linux?
Has this been corrected in python 2.6.4 (or 2.6.5)?
thanks,
bob s.
-----------------------------------
robert schaefer
Atmospheric Sciences Group
MIT Haystack Observatory
Westford, MA 01886
email: rps@haystack.mit.edu
voice: 781-981-5767
www: http://www.haystack.mit.edu
== 2 of 2 ==
Date: Wed, Mar 17 2010 6:00 am
From: Peter Otten <__peter__@web.de>
robert schaefer wrote:
> This is my first posting to this list so please be gentle -
>
> I am new to python and am using it on red-hat linux (I am new to that
> too). I am responsible for installing open source packages (including
> python) onto a distributed system of linux boxes.
>
> My question is, on python version 2.6.2 tkinter refuses to install.
Does it say "I'm sorry Bob, I'm afraid I can't do this"?
> Without tkinter, I cannot use Idle.
>
> I looked at the install/configure script and hacked it a bit, but every
> fix only caused new problems.
> There are serious issues with that script for finding necessary
> libraries.
If there are serious problems you have to give some details.
However, if in the past a newbie had problems with Tkinter support on linux
the most frequent problem was that the Tcl/Tk development libraries weren't
installed. I don't know how those are called on Red Hat, maybe something
like
tcl*-dev.rpm
Did you install these before running the configure script?
Peter
==============================================================================
TOPIC: multiprocessing on freebsd
http://groups.google.com/group/comp.lang.python/t/4ff8efd8478d1d76?hl=en
==============================================================================
== 1 of 1 ==
Date: Wed, Mar 17 2010 6:30 am
From: Tim Arnold
Hi,
I'm checking to see if multiprocessing works on freebsd for any
version of python. My server is about to get upgraded from 6.3 to 8.0
and I'd sure like to be able to use multiprocessing.
I think the minimal test would be:
---------------------
import multiprocessing
q = multiprocessing.Queue()
---------------------
with 6.3, I get
File "/usr/local/lib/python2.6/multiprocessing/__init__.py", line
212, in Queue
from multiprocessing.queues import Queue
File "/usr/local/lib/python2.6/multiprocessing/queues.py", line 22,
in <module>
from multiprocessing.synchronize import Lock, BoundedSemaphore,
Semaphore, Condition
File "/usr/local/lib/python2.6/multiprocessing/synchronize.py", line
33, in <module>
" function, see issue 3770.")
ImportError: This platform lacks a functioning sem_open
implementation, therefore, the required synchronization primitives
needed will not function, see issue 3770.
thanks for any info,
--Tim Arnold
==============================================================================
You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.
To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en
To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com
To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en
To report abuse, send email explaining the problem to abuse@googlegroups.com
==============================================================================
Google Groups: http://groups.google.com/?hl=en
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home