Re: Is it allowed to use function results as default arguments ?
To answer the subject line: param= will assign the result of the expression as the default argument object for the parameter. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing different versions of a module
Why not set up PYTHONPATH together with other environment variables in a shell script (bash, or CMD on Windows) and call that shell script instead of your Python script directly? This is probably the easiest and still a very powerful and generic solution for this kind of problem. We do it that way regardless of the programming language used. Henning -- http://mail.python.org/mailman/listinfo/python-list
Python COM
I have implemented a COM in C++,buy i don't know how to use this COM in python. For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two interfaces,the default interface's name is IAdvMethod,the second interface's name is IBasicMethod. How do i use those interfaces in python.Thank you very much,please answer my question in code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python COM
[EMAIL PROTECTED] schrieb: I have implemented a COM in C++,buy i don't know how to use this COM in python. For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two interfaces,the default interface's name is IAdvMethod,the second interface's name is IBasicMethod. How do i use those interfaces in python.Thank you very much,please answer my question in code. http://starship.python.net/crew/theller/comtypes/ Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: block/lambda
iu2 <[EMAIL PROTECTED]> wrote: > Is it possible to grant Python another syntactic mark, similar to > triple quotes, that will actually make the enclosed code a compiled > code, or an anonymous function? > Yes, the syntactic mark you are looking for is 'def'. Your example becomes: >>> def dotimes(n, callable): for i in range(n): callable(i) >>> def block(i): for j in range(i): print j, print >>> dotimes(5, block) 0 0 1 0 1 2 0 1 2 3 The only thing you asked for that this doesn't do is make 'block' anonymous, but actually that is a good thing. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it allowed to use function results as default arguments ?
Terry Reedy wrote:
To answer the subject line:
param=
will assign the result of the expression as the default argument
object for the parameter.
thanks Terry and others,
brings me to one other question:
I guess this function is only evaluated once, is that correct ?
about os.curdir,
I checked it, it's already a constant ;-)
and because I use afterwards:
os.path.abspath('.'')
which is identical to
os.path.getcwd()
about '.' being the current directory,
well I think windows was thrown at the market about 25 years ago,
and since then we don't use '.' anymore ;-)
cheers,
Stef
tjr
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance and __getattr__
"Bruno Desthuilliers" <[EMAIL PROTECTED]> ha scritto nel messaggio news:[EMAIL PROTECTED] > Indeed. You explicitely raise, so the lookup stops here. You'd need to > explicitely call on superclass instead to have B.__getattr__ called, ie: > > class A(object): > def __getattr__(self, name): > if name == 'a': > return 1 > return super(A, self).__getattr__(name) > > class B(object): > def __getattr__(self, name): > if name == 'b': > return 2 > return super(B, self).__getattr__(name) Hi Bruno, this is an interisting point. Just to understand better: when I raise an AttributeError the search stops but if I call a superclass (that for my understanding raises an AttributeError) the search continues. At this point I suspect that the search is doing something else, like checking if the class is at the top of the hierarchy. Do you know where I can look for this, probably in the core code of Python? > > Since A and B are not written by me I can only work on C. > > Really ? You know, Python is a *very* dynamic language. If A and B are > ordinary Python classes (ie: not builtin types, not C extensions, etc), > you can monkeypatch them. But that's not necessarily the best thing to > do (it would require more work than your actual solution). I know that I can do whatIwant with class A and class B (monkeypatch!) but I prefer to concentrate on my code and write a clean solution. Thanks for your help. Enrico -- http://mail.python.org/mailman/listinfo/python-list
Re: xlrd: error open_workbook
On 2008-07-28 22:22, Fabio Oikawa wrote:
Hello.
I am trying to open an .xls (excel) file using xlrd, but an error message
occurs when I open the workbook.
I can open any other .xls file made by myself (either by MS Excel 2003 SP3
in Windows Vista or by OpenOffice 2.0 in Debian) using the
*open_workbook*function:
wb = xlrd.open_workbook('myworkbook.xls')
but when I try to open a file from one specific site, I get the error
message:
In [2]: wb = xlrd.open_workbook('balanco.xls')
WARNING *** file size (81192) not 512 + multiple of sector size (512)
WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero
This looks like a broken XLS file.
In any case, you're probably better off asking this question on
the python-excel mailing list:
http://groups.google.com.au/group/python-excel?lnk=li&hl=en
You might also want to try pyExcelerator:
http://sourceforge.net/projects/pyexcelerator
---
struct.error Traceback (most recent call
last)
/home/oikawa/DB/
/usr/lib/python2.4/site-packages/xlrd/__init__.py in open_workbook(filename,
logfile, verbos ity, pickleable, use_mmap, file_contents, encoding_override,
formatting_info)
380 bk.parse_globals()
381 else:
--> 382 bk.parse_globals()
383 bk.get_sheets()
384 bk.nsheets = len(bk._sheet_list)
/usr/lib/python2.4/site-packages/xlrd/__init__.py in parse_globals(self)
1309 self.handle_name(data)
1310 elif rc == XL_PALETTE:
-> 1311 self.handle_palette(data)
1312 elif rc == XL_STYLE:
1313 self.handle_style(data)
/usr/lib/python2.4/site-packages/xlrd/formatting.py in handle_palette(book,
data)
550 "PALETTE record with %d colours\n", n_colours)
551 fmt = ' 552 colours = unpack(fmt, data)
553 assert book.palette_record == [] # There should be only 1
PALETTE record
554 # a colour will be 0xbbggrr
error: unpack str size does not match format
I ran the xlrd in both Windows Vista / Python 2.5 and Debian / Python 2.4.4
and got the same problem, so I suppose there is something wrong with the
.xls files (which can be downloaded at www.fundamentus.com.br --> "Dados
Históricos" menu --> "Balancos em Excel" --> choose any company). However, I
need the files in order to create my database system. Actually I want to
build all companies' informations in a mySQL database, and the fastest and
easiest way I found is to download .xls files, to get the data using
xlrd-Python and to add them in the mySQL database. Any sugestions for both
questions? Thanks in advance.
--
Marc-Andre Lemburg
eGenix.com
Professional Python Services directly from the Source (#1, Jul 29 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/
Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free !
eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
Bruno Desthuilliers <[EMAIL PROTECTED]> writes: > Nikolaus Rath a écrit : >> Michael Torrie <[EMAIL PROTECTED]> writes: > > (snip) > >>> In short, unlike what most of the implicit self advocates are >>> saying, it's not just a simple change to the python parser to do >>> this. It would require a change in the interpreter itself and how it >>> deals with classes. >> >> >> Thats true. But out of curiosity: why is changing the interpreter such >> a bad thing? (If we suppose for now that the change itself is a good >> idea). > > Because it would very seriously break a *lot* of code ? Well, Python 3 will break lots of code anyway, won't it? Best, -Nikolaus -- »It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.« -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions on 64 bit versions of Python (Thank-you!)
[EMAIL PROTECTED] wrote: Thanks for everyone's feedback - excellent detail - all my questions have been answered. BTW: Roel was correct that I got confused over the AMD and Intel naming conventions regarding the 64 bit versions of Python for Windows. (I missed that nuance that the Intel build refered to the Itanium vs. the standard off-the-rack 64 bit version of Intel's 586/686 CPU) Frankly, I'm very glad you did get confused: I've learnt more about the various 64-bit architectures in this thread than I ever thought I'd need to know :) TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it allowed to use function results as default arguments ?
On Tue, 29 Jul 2008 09:43:26 +0200, Stef Mientki wrote: > about '.' being the current directory, well I think windows was thrown > at the market about 25 years ago, and since then we don't use '.' > anymore ;-) No, even Windows uses '.' as the current directory -- at least XP does, I haven't tried Vista. However, old Classic Mac OS (pre OS-X) used ':' for the current directory, so dot isn't universal. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
ironpython, exception in mscorlib when reading .py file from network share
Hello, I have a ironpython 1.1.1.0 host in my c# app, and When doing a engine.ExecuteFile(file); i often get the error below, when "file" is on a network share : (winXp client , windows ??? server) 21-07-2008 12:47:28 : Traceback (most recent call last): 21-07-2008 12:47:28 : File c:\sandbox\xxx.cs 21-07-2008 12:47:28 : File c:\sandboxx\yyy.cs 21-07-2008 12:47:28 : File mscorlib, line unknown, in ReadAllBytes 21-07-2008 12:47:28 : File mscorlib, line unknown, in Read 21-07-2008 12:47:28 : File mscorlib, line unknown, in ReadCore 21-07-2008 12:47:28 : File mscorlib, line unknown, in WinIOError 21-07-2008 12:47:28 : IOError: The specified network name is no longer available. 21-07-2008 12:47:28 : Exception is caught before first line in python is executed. Other parts of the program is also accessing the network (for copying files etc), and never fails, so networks connection is "ok" (maybe not perfect, but at least present.) Is the ExecuteFile reading the contents of the .py file differently than a "copy" primitive is (other timeout/retry values) ? Does anyone have any ideas of how to setup windows , ironpython host or .NET lib differently, to stop it doing this ? Fallback solution is to copy file locally before execution, but I would rather fix this. thx -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
On Jul 28, 8:15 pm, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: > > On Jul 28, 10:00 am, Steven D'Aprano <[EMAIL PROTECTED] > > cybersource.com.au> wrote: > >> Cutting to the crux of the discussion... > > >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > >> > I want something where "if x" will do but a simple explicit test > >> > won't. > > >> Explicit tests aren't simple unless you know what type x is. If x could > >> be of any type, you can't write a simple test. Does x have a length? Is > >> it a number? Maybe it's a fixed-length circular length, and the length > >> is non-zero even when it's empty? Who knows? How many cases do you need > >> to consider? > > > Use case, please. I'm asking for code, not arguments. Please give me a > > piece of code where you can write "if x" that works but a simple > > explicit test won't. > > I gave you a piece of code, actual code from one of my own projects. If > you wouldn't accept that evidence then, why would you accept it now? I would accept as "evidence" something that satisfies my criteria, which your example did not: it could have easily (and more robustly) been written with a simple explicit test. I am looking for one that can't. You keep bringing up this notion of "more complex with no benefit", which I'm simply not interested in talking about that at this time, and I won't respond to any of your points. I am seeking the answer to one question: whether "if x" can usefully do something a simple explicit test can't. Everyone already knows that "if x" requires fewer keystrokes and parses to fewer nodes. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: exec(code) not allowing import on top level?
On Tue, 29 Jul 2008 03:26:45 +, Peter Teuben wrote: > if I define a simple string code, with the following contents: > > import math > def foo(x): >return math.sqrt(x) > > and i run it using exec(code) in python, math is not known. Works for me. >>> code = """import math ... def foo(x): ... return math.sqrt(x) ... """ >>> >>> exec code >>> foo(25) 5.0 By the way, exec is a statement, not a function, so you don't need the brackets. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance and __getattr__
Le Monday 28 July 2008 16:48:09 Enrico, vous avez écrit :
> Hi there,
> I have the following situation (I tryed to minimize the code to concentrate
>
> on the issue):
> >>> class A(object):
>
> def __getattr__(self, name):
> print 'A.__getattr__'
> if name == 'a': return 1
> raise AttributeError('%s not found in A' % name)
>
> >>> class B(object):
>
> def __getattr__(self, name):
> print 'B.__getattr__'
> if name == 'b': return 1
> raise AttributeError('%s not found in B' % name)
>
> Both classes have a __getattr__ method.
>
> Now I want to have a class that inherits from both so I write:
> >>> class C(B,A):
>
> pass
>
> The problem arise when I try something like this:
> >>> c=C()
> >>> c.a
>
> A.__getattr__
> 1
>
> >>> c.b
>
> A.__getattr__
>
> Traceback (most recent call last):
> File "", line 1, in
> c.b
> File "", line 5, in __getattr__
> raise AttributeError('%s not found in A' % name)
> AttributeError: b not found in A
>
> I was expecting, after a fail in A.__getattr__, a call to the __getattr__
> method of B but it seems that after A.__getattr__ fails the exception stops
> the flow. So, if I did understand well, B.__getattr__ will be never called
> "automatically". I don't know if this has a reason, if it is a design
> choice or what else, any explanation is welcome.
>
No getattr is a lookup fallback, classes which implement them in a
non-collaborative way are unlikely to be used for multiple inheritance.
Given how multiple inheritance work and __getattr__ semantic, I was surprised
it is not that easy to figure out how it could work in a collaborative, and
how far fromm this are common implementation of __getattr__.
Normally they should be implemented like that :
>>>[89]: class A(object) :
def __getattr__(self, name) :
if name == 'a' : return 'a'
try : g = super(A, self).__getattr__
except : raise AttributeError('no more __getattr__')
return g(name)
:
:
>>>[95]: class B(object) :
def __getattr__(self, name) :
if name == 'b' : return 'b'
try : g = super(B, self).__getattr__
except : raise AttributeError('no more __getattr__')
return g(name)
.:
.:
>>>[101]: class C(A, B) :
def __getattr__(self, name) :
if name == 'c' : return 'c'
try : g = super(C, self).__getattr__
except : raise AttributeError('no more __getattr__')
return g(name)
.:
.:
>>>[107]: C().a
...[107]: 'a'
>>>[108]: C().b
...[108]: 'b'
>>>[109]: C().c
...[109]: 'c'
>>>[110]: C().k
---
AttributeErrorTraceback (most recent call last)
/home/maric/ in ()
/home/maric/ in __getattr__(self, name)
/home/maric/ in __getattr__(self, name)
/home/maric/ in __getattr__(self, name)
AttributeError: no more __getattr__
> Since A and B are not written by me I can only work on C. The solution that
> comes to my mind is to define a __getattr__ also in C and write something
>
> like:
> >>> class C(A,B):
>
> def __getattr__(self, name):
> try:
>return A.__getattr__(self, name)
> except AttributeError:
>return B.__getattr__(self, name)
>
> >>> c=C()
> >>> c.a
>
> A.__getattr__
> 1
>
> >>> c.b
>
> A.__getattr__
> B.__getattr__
> 1
>
> A better solution is welcome.
There is no way to repair those clases for mulitple inheritance except monkey
patching them.
The idea of this patch would be :
def collaborative_getattr(class_, old_name) :
old_one = getattr(class_, old_name)
def __getattr__(self, name) :
try : return old_one(self, name)
except AttributeError :
try : g = super(class_, self).__getattr__
except : raise AttributeError('no more __getattr__')
return g(name)
if not getattr(C, '_C_fixed__', False) :
C._C_fixed__ = C.__getattr__
C.__getattr__ = collaborative_getattr(C, '_C_fixed__')
That said, if your class C is a real facade for its ancestors A and B (A and B
won't appear at all in the hierarchies of your subclasses), your solution is
near the best one in terms of simplicity-efficiency. I said near the best one
because your __getattr__ isn't collaborative yet ! :).
--
_
Maric Michaud
--
http://mail.python.org/mailman/listinfo/python-list
Re: ironpython, exception in mscorlib when reading .py file from network share
On Jul 29, 9:34 am, mindmind <[EMAIL PROTECTED]> wrote: > Hello, > > I have a ironpython 1.1.1.0 host in my c# app, and When doing a > engine.ExecuteFile(file); > i often get the error below, when "file" is on a network share : > (winXp client , windows ??? server) > > 21-07-2008 12:47:28 : Traceback (most recent call last): > 21-07-2008 12:47:28 : File c:\sandbox\xxx.cs > 21-07-2008 12:47:28 : File c:\sandboxx\yyy.cs > 21-07-2008 12:47:28 : File mscorlib, line unknown, in ReadAllBytes > 21-07-2008 12:47:28 : File mscorlib, line unknown, in Read > 21-07-2008 12:47:28 : File mscorlib, line unknown, in ReadCore > 21-07-2008 12:47:28 : File mscorlib, line unknown, in WinIOError > 21-07-2008 12:47:28 : IOError: The specified network name is no longer > available. > 21-07-2008 12:47:28 : > > Exception is caught before first line in python is executed. > > Other parts of the program is also accessing the network (for copying > files etc), and never fails, > so networks connection is "ok" (maybe not perfect, but at least > present.) > > Is the ExecuteFile reading the contents of the .py file differently > than a "copy" primitive is (other timeout/retry values) ? > > Does anyone have any ideas of how to setup windows , ironpython host > or .NET lib differently, to stop it doing this ? Fallback solution is > to copy file locally before execution, but I would rather fix this. > > thx I don't know the answer - I do know that .NET permissions issues and accessing network resources are a bit 'weird'. You're likely to get an answer if you ask on the IronPython mailing list. Michael Foord -- http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
Am Dienstag, 29. Juli 2008 10:37:45 schrieb Carl Banks: > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, > and I won't respond to any of your points. I am seeking the answer to > one question: whether "if x" can usefully do something a simple > explicit test can't. Everyone already knows that "if x" requires > fewer keystrokes and parses to fewer nodes. Yes, there are quite a lot of use cases. Think of a polymorphic function, where the input can be any object that implements the iterator protocol (concerning base types, I'm thinking of strings, tuples, lists, dicts and sets here, which are all iterable and yield a chain of singular values) and you want to check whether the iterable object is empty or not for special-casing that. "if x" uses the special interface method __nonzero__() if that's implemented (which all of the above types implement as returning True iff the container yields at least one value when iterated over, i.e., it isn't empty), and falls back to a test for __len__() != 0, otherwise x is considered to be true. Now, explicitly comparing x against the five "empty" values of the container types I specified above would be broken design in such a function: when I implement a container class myself, which implements the __iter__() and __nonzero__() methods, I can directly use it with the polymorphic function I wrote, and the special case for an empty container will work out of the box. In the case of explicit comparisons, I have to modify the polymorphic function to accept my container type in addition to those it already processes to be able to special-case the empty container for my type. I can't dig up a simple example from code I wrote quickly, but because of the fact that explicit comparisons always hamper polymorphism (which might not be needed initially, but you never know what comes up later, thinking of reusability of components), I personally always stick to the idiom "if x" rather than comparing it to an empty value, even when I'm sure that the type of x is a singular type. Additionally, IMHO "if x" is so much more readable than "if x != ". Just my 2 (euro)cents. -- Heiko Wundram -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
On Jul 29, 5:33 am, "Russ P." <[EMAIL PROTECTED]> wrote: > On Jul 28, 8:44 pm, alex23 <[EMAIL PROTECTED]> wrote: > > > On Jul 29, 4:46 am, "Russ P." <[EMAIL PROTECTED]> wrote: > > > > As I said, I could write a pre-processor myself to > > > implement it in less than a day. > > > So WHY DON'T YOU WRITE IT ALREADY? > > I'm working on something else right now if you don't mind, but I'll > get to it in good time. > > Conceptually, the matter is simple. All I need to do is to grab the > first formal argument of each def, then search for occurrences of any > word in the body of the def that starts with a dot, and insert that > first argument in front of it. > > I expect the "hard" part will be breaking up the body of the def into > "words." I could just split each line on white space, except for > situations like > > x+=.zzz > > So I need to account for the fact that operators do not need to be > surrounded by spaces. That's the hardest part I can think of off the > top of my head. > > Maybe I'll encounter an insurmountable problem and realize that the > idea can't work in general. If so, then so be it. Certainly, no one on > this thread has anticipated such a problem. Had someone pointed out an > actual technical problem with the idea, I would have gladly thanked > them. But I got a load of irrelevant crap instead, not to mention > being addressed as "boy." > > > If you're meeting so much resistance to your idea, why not scratch > > your own damn itch and just do it? > > > Or doesn't that afford you as many chances to insult others while > > feeling smugly superior? > > This coming from a guy who insulted my reading comprehension ability > -- when he was the one who was wrong! Are you actually this stupid? I mean, you were entertaining while you were mouthing of and insulting your betters, but now you're gonna complain the second anyone insults you (and I mean, 'boy' - what an insult!). Never mind that you're never gonna get off your ass to write a PEP, which would be rejected on language design grounds anyway (as demonstrated by alex23's link - the one you aren't comprehending). The most irritating thing is that I like the idea of being able to use '.x = 10' type notation (and have been for a long time), but the person arguing for it is an insufferable buffoon who's too dense to understand a cogent argument, never mind make one. So great, thanks, the chances of this (or a VB 'with'-like 'using' keyword) ever making it into the language get smaller every time you fire up your keyboard. Nice work. Iain p.s. am looking forward to your post whining about the invalid reasons your PEP got rejected, in the slim hope you actually write one. -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > On Jul 28, 8:15 pm, Steven D'Aprano <[EMAIL PROTECTED] > cybersource.com.au> wrote: >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: >> > On Jul 28, 10:00 am, Steven D'Aprano <[EMAIL PROTECTED] >> > cybersource.com.au> wrote: >> >> Cutting to the crux of the discussion... >> >> >> On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: >> >> > I want something where "if x" will do but a simple explicit test >> >> > won't. >> >> >> Explicit tests aren't simple unless you know what type x is. If x >> >> could be of any type, you can't write a simple test. Does x have a >> >> length? Is it a number? Maybe it's a fixed-length circular length, >> >> and the length is non-zero even when it's empty? Who knows? How many >> >> cases do you need to consider? >> >> > Use case, please. I'm asking for code, not arguments. Please give >> > me a piece of code where you can write "if x" that works but a simple >> > explicit test won't. >> >> I gave you a piece of code, actual code from one of my own projects. If >> you wouldn't accept that evidence then, why would you accept it now? > > I would accept as "evidence" something that satisfies my criteria, which > your example did not: it could have easily (and more robustly) been > written with a simple explicit test. Only at the cost of completely ignoring the functional requirements and changing the API. In other words: you ignore my code, and invent your own imaginary code that does something completely different, then say that this imaginary code is better. And I question your assertion that a "simple explicit test" is more robust. Where's your evidence for that? > I am looking for one that can't. If you are writing code that needs to do the right thing with arbitrary types, then your so-called "simple explicit tests" simply can't work. If your code isn't expected to deal with arbitrary types, then you've got an excellent chance that it will work, because you know what types to expect. Until somebody passes a type that you didn't expect, and your code fails because it makes assumptions about the object. If you know that you only get lists, then "if len(x)!=0" is a perfectly good test (apart from being longer to type, harder to read, and slower to execute than "if x"). It will work so long as you only get objects where a length of zero is equivalent to being false. That's a good assumption to make, but it is an *unnecessary* assumption. Any reasonable object you get will know if it is false/nothing or true/something, so why make any assumptions? Just ask the object. It knows. > You keep bringing up this notion of "more complex with no benefit", > which I'm simply not interested in talking about that at this time, and > I won't respond to any of your points. Of course not. > I am seeking the answer to one > question: whether "if x" can usefully do something a simple explicit > test can't. "if x" is completely type agnostic. You can pass an object of any type to it, and it will work. (Excluding objects with buggy methods, naturally.) Try doing that with one of your so-called "simple explicit tests". -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
Steven D'Aprano wrote: On Tue, 29 Jul 2008 00:23:02 +, Steven D'Aprano wrote: Dude. Dude. Just... learn some Python before you embarrass yourself further. I'm sorry Anders, that was a needlessly harsh thing for me to say. I apologize for the unpleasant tone. Still, __nonzero__ is a fundamental part of Python's behaviour. You should learn about it. Hm, first you apologize, then you repeat the insult? That's no basis for a conversation. Bye from here. regards, Anders -- http://mail.python.org/mailman/listinfo/python-list
Re: block/lambda
On Jul 29, 9:36 am, Duncan Booth <[EMAIL PROTECTED]> wrote: > iu2 <[EMAIL PROTECTED]> wrote: > > Is it possible to grant Python another syntactic mark, similar to > > triple quotes, that will actually make the enclosed code a compiled > > code, or an anonymous function? > > Yes, the syntactic mark you are looking for is 'def'. > > Your example becomes: > > >>> def dotimes(n, callable): > > for i in range(n): callable(i) > > >>> def block(i): > > for j in range(i): > print j, > print > > >>> dotimes(5, block) > > 0 > 0 1 > 0 1 2 > 0 1 2 3 > > The only thing you asked for that this doesn't do is make 'block' > anonymous, but actually that is a good thing. > > -- > Duncan Boothhttp://kupuguy.blogspot.com Ok, I've got 2 questions about it: 1. Can you please explain why it is a good thing? 2. Will it be possible in Python 3.0 to do the following: >>> def dotimes(n, callable): for i in range(n): callable() >>> def block(): nonlocal i for j in range(i): print j, print Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes and how to copy data passed to callback
On Jul 28, 4:03 pm, Thomas Heller <[EMAIL PROTECTED]> wrote: > waldek schrieb: > > > > > Hi, > > > I'm trying to handle data passed to Py Callback which is called from > > C dll. Callback passes data to another thread using Queue module and > > there the data are printed out. > > > If data is printed out in a callback itself it's ok. If I put on > > queue and next get from queue in another thread script prints some > > trash. Looks like the data is released when callback returned. I tired > > to make d = copy.deepcopy(data), but it does not work - I got nothing. > > Any idea why it's happening ? > > > - main thread > > def callback(data, size): > > myqueue.put((data, size)) > > > mydll = cdll.MyDLL > > cbproto = CFUNCTYPE(c_int, POINTER(c_char), c_int) > > mycallback = cbproto(callback) > > > mydll.RegisterCallback(mycallback) > > > -- thread listener > > -- > > > while True: > > data, size = myqueue.get() > > print "***", data[:size] > > > -- > > I guess your code would work if you change it in this way: > > > def callback(data, size): > > myqueue.put(data[:size]) > > while True: > > data = myqueue.get() > > print "***", data > > Thomas Both solutions work fine. The secon is nicer :) Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Download excel file from web?
On Tue, Jul 29, 2008 at 1:47 AM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> On Jul 28, 6:05 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>> On Mon, Jul 28, 2008 at 9:39 PM, MRAB <[EMAIL PROTECTED]> wrote:
>> > On Jul 29, 12:41 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>> >> On Jul 28, 4:20 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>>
>> >> > On Mon, Jul 28, 2008 at 8:04 PM, [EMAIL PROTECTED] <[EMAIL PROTECTED]>
>> >> > wrote:
>> >> > > On Jul 28, 3:52 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>> >> > >> On Mon, Jul 28, 2008 at 7:43 PM, [EMAIL PROTECTED] <[EMAIL
>> >> > >> PROTECTED]> wrote:
>> >> > >> > On Jul 28, 3:33 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>> >> > >> >> On Jul 28, 3:29 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>>
>> >> > >> >> > [EMAIL PROTECTED] schrieb:
>>
>> >> > >> >> > > On Jul 28, 3:00 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
>> >> > >> >> > > wrote:
>> >> > >> >> > >> Hi - experienced programmer but this is my first Python
>> >> > >> >> > >> program.
>>
>> >> > >> >> > >> This URL will retrieve an excel spreadsheet containing (that
>> >> > >> >> > >> day's)
>> >> > >> >> > >> msci stock index returns.
>>
>> >> > >> >> > >>http://www.mscibarra.com/webapp/indexperf/excel?priceLevel=0&scope=0&;...
>>
>> >> > >> >> > >> Want to write python to download and save the file.
>>
>> >> > >> >> > >> So far I've arrived at this:
>>
>> >> > >> >> > >> [quote]
>> >> > >> >> > >> # import pdb
>> >> > >> >> > >> import urllib2
>> >> > >> >> > >> from win32com.client import Dispatch
>>
>> >> > >> >> > >> xlApp = Dispatch("Excel.Application")
>>
>> >> > >> >> > >> # test 1
>> >> > >> >> > >> # xlApp.Workbooks.Add()
>> >> > >> >> > >> # xlApp.ActiveSheet.Cells(1,1).Value = 'A'
>> >> > >> >> > >> # xlApp.ActiveWorkbook.ActiveSheet.Cells(2,1).Value = 'B'
>> >> > >> >> > >> # xlBook = xlApp.ActiveWorkbook
>> >> > >> >> > >> # xlBook.SaveAs(Filename='C:\\test.xls')
>>
>> >> > >> >> > >> # pdb.set_trace()
>> >> > >> >> > >> response =
>> >> > >> >> > >> urllib2.urlopen('http://www.mscibarra.com/webapp/indexperf/
>> >> > >> >> > >> excel?
>> >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul
>> >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional')
>> >> > >> >> > >> # test 2 - returns check = False
>> >> > >> >> > >> check_for_data =
>> >> > >> >> > >> urllib2.Request('http://www.mscibarra.com/webapp/
>> >> > >> >> > >> indexperf/excel?
>> >> > >> >> > >> priceLevel=0&scope=0¤cy=15&style=C&size=36&market=1897&asOf=Jul
>> >> > >> >> > >> +25%2C+2008&export=Excel_IEIPerfRegional').has_data()
>>
>> >> > >> >> > >> xlApp = response.fp
>> >> > >> >> > >> print(response.fp.name)
>> >> > >> >> > >> print(xlApp.name)
>> >> > >> >> > >> xlApp.write
>> >> > >> >> > >> xlApp.Close
>> >> > >> >> > >> [/quote]
>>
>> >> > >> >> > > Woops hit Send when I wanted Preview. Looks like the html
>> >> > >> >> > > [quote] tag
>> >> > >> >> > > doesn't work from groups.google.com (nice).
>>
>> >> > >> >> > > Anway, in test 1 above, I determined how to instantiate an
>> >> > >> >> > > excel
>> >> > >> >> > > object; put some stuff in it; then save to disk.
>>
>> >> > >> >> > > So, in theory, I'm retrieving my excel spreadsheet with
>>
>> >> > >> >> > > response = urllib2.urlopen()
>>
>> >> > >> >> > > Except what then do I do with this?
>>
>> >> > >> >> > > Well for one read some of the urllib2 documentation and found
>> >> > >> >> > > the
>> >> > >> >> > > Request class with the method has_data() on it. It returns
>> >> > >> >> > > False.
>> >> > >> >> > > Hmm that's not encouraging.
>>
>> >> > >> >> > > I supposed the trick to understand what urllib2.urlopen is
>> >> > >> >> > > returning
>> >> > >> >> > > to me; rummage around in there; and hopefully find my excel
>> >> > >> >> > > file.
>>
>> >> > >> >> > > I use pdb to debug. This is interesting:
>>
>> >> > >> >> > > (Pdb) dir(response)
>> >> > >> >> > > ['__doc__', '__init__', '__iter__', '__module__', '__repr__',
>> >> > >> >> > > 'close',
>> >> > >> >> > > 'code', '
>> >> > >> >> > > fileno', 'fp', 'geturl', 'headers', 'info', 'msg', 'next',
>> >> > >> >> > > 'read',
>> >> > >> >> > > 'readline', '
>> >> > >> >> > > readlines', 'url']
>> >> > >> >> > > (Pdb)
>>
>> >> > >> >> > > I suppose the members with __*_ are methods; and the names
>> >> > >> >> > > without the
>> >> > >> >> > > underbars are attributes (variables) (?).
>>
>> >> > >> >> > No, these are the names of all attributes and methods. read is
>> >> > >> >> > a method,
>> >> > >> >> > for example.
>>
>> >> > >> >> right - I got it backwards.
>>
>> >> > >> >> > > Or maybe this isn't at all the right direction to take (maybe
>> >> > >> >> > > there
>> >> > >> >> > > are much better modules to do this stuff). Would be happy to
>> >> > >> >> > > learn if
>> >> > >> >> > > that's the case (and if that gets the job done for me).
>>
>> >> > >> >> > The docs (http://docs.python.org/lib/module-urllib2.html) are
Re: Boolean tests [was Re: Attack a sacred Python Cow]
Am Dienstag, 29. Juli 2008 11:15:05 schrieb Heiko Wundram: > I can't dig up a simple example from code I wrote quickly... Just to get back to that: an example I found where "if x" (the generic __nonzero__() test) will work to test for emptiness/non-emptiness of a container, whereas "if len(x) > 0" (the "specific" test for this example) will not, is my for own integer set type I wrote a while back (which you can find on ASPN). The corresponding set type allows you to create infinitely sized sets of integers (which of course are stored as pairs of ,-values, so the storage itself for the set is bounded), for which len(x) does not have a "proper" meaning anymore, and __len__() is limited to returning a (platform dependent) ssize_t anyway IIRC, so even with a bounded set, the length of the set might not necessarily be accessible using len(x); that's why the set type additionally got a member function called .len() to work around this restriction. I should think is a non-contrieved example where the generic test whether the object considers itself True/False (which for containers means non-empty/empty) is preferrable over the special case test whether the length is positive. A polymorphic function, which for example only accesses the first ten members of the container is able to work with an infinite set if it uses the generic test, but is not in case it uses len(x) > 0. -- Heiko Wundram -- http://mail.python.org/mailman/listinfo/python-list
Swap memory in Python ? - three questions
Hi, I am using numpy and wish to create very large arrays. My system is AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap drive. The command I have been trying to use is; g=numpy.ones([1000,1000,1000],numpy.int32) This returns a memory error. A smaller array ([500,500,500]) worked fine.. Two smaller arrays again crashed the system. So... I did the math. a 1000x1000x1000 array at 32 bits should be around 4gb RAM... Obviously larger than RAM, but much smaller than the swap drive. 1. So... does Numpy have a really lot of overhead? Or is my system just not somehow getting to make use of the 15gb swap area. 2. Is there a way I can access the swap area, or direct numpy to do so? Or do I have to write out my own numpy cache system... 3. How difficult is it to use data compression internally on numpy arrays? thanks very much Robert -- http://mail.python.org/mailman/listinfo/python-list
SWIG and char* newb questions :)
Hi i'm relatively new to Python and my C/C++ knowledge is near to None. Having said that I feel justified to ask stupid questions :) Ok now more seriously. I have question refering to char* used as function parameters to return values. I have read SWIG manual to find best way to overcome that, but there are many warnings about memory leaks and stuff, so I feel confused. Ok to put it more simply: how to safely define a variable in Python and have it modified by C/C++ function? Even better would be a way to make a tuple of return value and out parameters, but thats probably a lot more work. Any hint will be appreciated! -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG and char* newb questions :)
Am Dienstag, 29. Juli 2008 12:51:36 schrieb code_berzerker: > Ok now more seriously. I have question refering to char* used as > function parameters to return values. I have read SWIG manual to find > best way to overcome that, but there are many warnings about memory > leaks and stuff, so I feel confused. > > Ok to put it more simply: how to safely define a variable in Python > and have it modified by C/C++ function? At least for strings, this won't work. Python strings are immutable (and Python optimizes some things based on this knowledge), and as such you can pass a Python string(-object) into a C/C++ function and retrieve its value there as a const (!) char* using the PyString_*-API (I have no idea how this is encapsulated in SWIG), but cannot/should not modify it (a const_cast<> is almost always a sign of bad programming, anyway). The only real choice you have is to have your wrapper return a new string object, created using one of the PyString_FromString[AndSize] functions. Check the Python C-API documentation for more info on this. Anyway, on a different note, I personally have always found it simpler to not use SWIG to generate C extensions for Python, but to use the Python C-API directly. Hope this helps! -- Heiko Wundram -- http://mail.python.org/mailman/listinfo/python-list
Re: ironpython, exception in mscorlib when reading .py file from network share
> > I don't know the answer - I do know that .NET permissions issues and > accessing network resources are a bit 'weird'. You're likely to get an > answer if you ask on the IronPython mailing list. > I had it running through the night, ~100 times, 25 of these gave the above exception. Hard to see any pattern. -- http://mail.python.org/mailman/listinfo/python-list
Questions about asyncore
Hi all I have been using my own home-brewed client/server technique for a while, using socket and select. It seems to work ok. The server can handle multiple clients. It does this by creating a new thread for each connection. Each thread runs its own select loop. I am making some fairly big changes, so I thought I would look at asyncore. I modified my program to use asyncore without much trouble, and it feels nicer. It uses async I/O instead of threading, and it relieves me of having to run my own select loop. I have two questions. They both relate to whether I am using the module as intended. The documentation is rather sparse, and I know from experience that just getting something working is no guarantee that I am getting the full benefit. Firstly, having got asyncore working, I had a look at asynchat. As far as I can see I get very little benefit from using it. I have already set up a 'messaging' protocol between server and client, where all messages consist of 5 digits for the message length, followed by the message. The message consists of a pickled tuple, where the first element is a message identifier, and the rest is the message body. This is how it works in asyncore - def __init__(self,channel): [...] self.msgLength = 0 self.recvData = '' # temporary buffer def handle_read(self): self.recvData += self.recv(8192) if not self.msgLength: if len(self.recvData) < 5: # 1st 5 bytes = msg length return self.msgLength = int(self.recvData[:5]) self.recvData = self.recvData[5:] if len(self.recvData) < self.msgLength: return data = loads(self.recvData[:self.msgLength]) self.recvData = self.recvData[self.msgLength:] self.msgLength = 0 [handle data] This is how I got it working in asynchat - def __init__(self,channel): [...] self.recvData = '' # temporary buffer self.set_terminator(5) self.gotMsgLength = False def collect_incoming_data(self, data): self.recvData += data def found_terminator(self): if self.gotMsgLength: # what follows is the message data = loads(self.recvData) self.set_terminator(5) self.gotMsgLength = False [handle data] else: # what follows is the message length self.set_terminator(int(self.recvData)) self.gotMsgLength = True self.recvData = '' It may be slightly neater, but it does not seem worth adding an extra layer just for that. Does asynchat give me any other benefits I may have overlooked? My second question relates to writing a dummy client program to test the server. I just want to send it some messages and print the responses. Some messages incorporate data extracted from previous responses, so I have to wait for the reply before continuing. I am using asyncore for this as well. However, the only way I can think of to get it working is to run asyncore.dispatcher in a separate thread. To send messages, I append them to a list of messages to be sent. The dispatcher method writable() returns True if there is anything in the list, else False. To receive messages, I run a 'while 1' loop in the main thread, with a sleep of 0.1, until recvData has something in it. It works, but it seems odd to use a separate thread, as one of the points of asyncore is to avoid multi-threading. Is there a better way to write the client program? Thanks Frank Millman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python COM
Hi!
Example, with Pywin32:
import win32com.client
moncom = win32com.client.Dispatch('MyCOM1.AdvMethod')
moncom.IAdvMethod(...
See Pywin32 here: http://sourceforge.net/projects/pywin32/
@-salutations
Michel Claveau
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python COM
M�ta-MCI (MVP) wrote:
> Hi!
>
> Example, with Pywin32:
>
> import win32com.client
> moncom = win32com.client.Dispatch('MyCOM1.AdvMethod')
> moncom.IAdvMethod(...
>
> See Pywin32 here: http://sourceforge.net/projects/pywin32/
That's not working, because the OP has a custom interface, not
IDispatch-based.
Diez
--
http://mail.python.org/mailman/listinfo/python-list
Re: method decorators and more on decorators
On Mon, Jul 28, 2008 at 11:12 AM, Gabriel Genellina <[EMAIL PROTECTED]>wrote: > En Sun, 27 Jul 2008 15:26:39 -0300, Themistoklis Bourdenas < > [EMAIL PROTECTED]> escribió: > > > On a related note, as the actual instance method of myclass is not foo > but > > decorate(foo), why are they called method decorators? This does not > decorate > > methods, they decorate functions and eventually the decorated functions > > become methods. The name method decorator sounds a bit misleading to me. > > Where have you found it? I've always seen the expression "function > decorator" or just "decorator", not "method decorator". > well a few occurrences of it can be found in PEP 318 > > > So returning to my original question is there any way I can get the class > > inside decorate()? I guess there is not, but just asking to make sure. > > "the class inside decorate"? What do you mean? The type of the x instance > in an x.foo() call? That should be determined inside the wrapped function > -when it is actually called-. > > Yes, what I was hoping is that it might be possible to get the name of the class the function is eventually is going to be bound to, but I guess that's not very likely to be possible. I wanted the name well before the function is called, actually even before an instance of the class is created. Anyway, I 've solved my problem with other means. Just out curiosity though, has there been any talk about actual method decorators? I guess you can work around them with the introduction of class decorators or even now with meta-classes, but you have to wrap methods manually with no syntactic sugar. Cheers, Themis -- http://mail.python.org/mailman/listinfo/python-list
Re: exec(code) not allowing import on top level?
Peter Teuben wrote:
>
> if I define a simple string code, with the following contents:
>
> import math
> def foo(x):
>return math.sqrt(x)
The
import math
statement puts 'math' in the local namespace, and foo looks it up in the
global namespace. This can only work when these namespaces are the same:
>>> code = """
... import math
... def foo(x):
... return math.sqrt(x)
... print foo(2)
... """
>>> exec code in {}
1.41421356237
>>> exec code in {}, {}
Traceback (most recent call last):
File "", line 1, in
File "", line 5, in
File "", line 4, in foo
NameError: global name 'math' is not defined
You could argue that Python should always look into the local namespace and
then fall back to the global namespace but that would be fruitless extra
work in most cases. I think it can only hapen with exec/eval, and as you
have seen in the other responses even there it works on the module level
because -- tada!
>>> globals() is locals()
True
> and i run it using exec(code) in python, math is not known. But when I
> recode the string as:
>
> def foo(x):
>import math
>return math.sqrt(x)
Here Python "guesses" that math is a local variable and that guess is
correct. If you wrote
import math
def foo(x):
return math.sqrt(x)
math = 42
Python would still guess that math is a local name and you would end up with
a runtime exception.
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: interpreter vs. compiled
On Jul 29, 2:21 pm, castironpi <[EMAIL PROTECTED]> wrote: > On Jul 28, 5:58 pm, Fuzzyman <[EMAIL PROTECTED]> wrote: > > Well - in IronPython user code gets compiled to in memory assemblies > > which can be JIT'ed. > > I don't believe so. Uh, you're questioning someone who is not only co-author of a book on IronPython, but also a developer on one of the first IronPython-based commercial applications. I know authorship isn't always a guarantee of correctness, but what experience do you have with IronPython that makes you so unwilling to accept the opinion of someone with substantial knowledge of the subject? -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG and char* newb questions :)
Ok I think I got it:
PyObject* myFuncXXX(char* p_1, int p_2, char* p_3, int p_4)
{
int res;
char _host[255] = "";
int _port;
res = funcXXX(p_1, p_2, p_3, p_4, _host, &_port);
PyObject* res1 = PyInt_FromLong(res);
PyObject* res2 = PyString_FromStringAndSize(_host, strlen(_host));
PyObject* res3 = PyInt_FromLong(_port);
PyObject* resTuple = PyTuple_New(3);
PyTuple_SetItem(resTuple, 0, res1);
PyTuple_SetItem(resTuple, 1, res2);
PyTuple_SetItem(resTuple, 2, res3);
return resTuple;
}
It seems to work when I put it into swig's "*.i" file.
me proud of me.self :D
--
http://mail.python.org/mailman/listinfo/python-list
Re: Swap memory in Python ? - three questions
Robert LaMarca wrote: Hi, I am using numpy and wish to create very large arrays. My system is AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap drive. The command I have been trying to use is; g=numpy.ones([1000,1000,1000],numpy.int32) This returns a memory error. A smaller array ([500,500,500]) worked fine.. Two smaller arrays again crashed the system. So... I did the math. a 1000x1000x1000 array at 32 bits should be around 4gb RAM... Obviously larger than RAM, but much smaller than the swap drive. 1. So... does Numpy have a really lot of overhead? Or is my system just not somehow getting to make use of the 15gb swap area. 2. Is there a way I can access the swap area, or direct numpy to do so? Or do I have to write out my own numpy cache system... 3. How difficult is it to use data compression internally on numpy arrays? thanks very much Robert There are architectural issues that you should not expect (and really do not want) the libraries / languages / os to handle for you automatically. The reason you don't even _want_ an automatic solution is that the computer has no understanding of the problem you are trying to solve. If the machine guesses wrong, it will be doing computations at I/O speeds, and for 4G of data, that will result in geological computing times. On big problems the programming issue is how to break the problem into tractable sub-problems (of feasible computing size), and how to stitch those results together. This is a place to apply human intellect, not machine effort. So, sorry, there is no way to solve the problem without understanding the field it occurs in and the question being addressed by the code. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Simplify Code
Thanks. That worked. Victor On 7/16/08, Alexandr N Zamaraev <[EMAIL PROTECTED]> wrote: > > header_sizes = (36, 26, 22, 18, 14, 12) > if x not in header_sizes: > raise Exception() > else: > h36, h26, h22, h18, h14, h12 = tuple( >line if x == size else '' for x in header_sizes) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Windows Interpreter
Hi: I would like to make my windows python interpreter work like my linux one. I want to be able to cut and paste multiple lines of code. Now I can only paste one line at a time. I do not want it to indent automatically. How can I change this? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
RTF Parsing
Hi; I have this code: def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass which gives this result: >>> a() \qc \b0 \i \u \b >>> which makes no sense at all. I expected this: >>> a() \qc \i >>> Why do I get more than that? Also, if I change this line thus: c = '(?<=' + char + ')[0 ]' I get this result: >>> a() \b >>> Why? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Interpreter
Victor Subervi wrote: Hi: I would like to make my windows python interpreter work like my linux one. I want to be able to cut and paste multiple lines of code. You can already do this: what are you trying which isn't working? Now I can only paste one line at a time. I do not want it to indent automatically. How can I change this? I realise this is a difficult thing to describe in words, but I regularly cut and paste multiple lines of code into my Python interpreter and it doesn't indent automatically. Can you give some specific examples of what you do and what does or doesn't work? TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests
"Anders J. Munch" <[EMAIL PROTECTED]> writes: > Steven D'Aprano wrote: > > I'm sorry Anders, that was a needlessly harsh thing for me to say. > > I apologize for the unpleasant tone. > > > > Still, __nonzero__ is a fundamental part of Python's behaviour. > > You should learn about it. > > Hm, first you apologize, then you repeat the insult? That's no basis > for a conversation. Bye from here. No, he retracted the *insult* and restated the *advice* as a distinct statement. I think it's quite worthwhile to help people see the difference. -- \ “People are very open-minded about new things, as long as | `\ they're exactly like the old ones.” —Charles F. Kettering | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Interpreter
def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass Now, I can paste that entire fn in linux. But in windows I have to paste it line_by_line. Pain in butt! And it indents automatically. How change that behavior. TIA, Victor On 7/29/08, Tim Golden <[EMAIL PROTECTED]> wrote: > > Victor Subervi wrote: > >> Hi: >> I would like to make my windows python interpreter work like my linux one. >> I want to be able to cut and paste multiple lines of code. >> > > You can already do this: what are you trying which isn't working? > > Now I can only paste one line at a time. I do not want it to indent >> automatically. How can I change this? >> > > I realise this is a difficult thing to describe in words, > but I regularly cut and paste multiple lines of code > into my Python interpreter and it doesn't indent automatically. Can you > give some specific examples of what you do and what does or doesn't work? > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
backspace problems
If I'm in the python interactive interpreter, I get a beep when I hit the backspace key. I must confess, though, that my terminal is "complicated", to put it mildly: I work on a Mac running Leopard; I open a Terminal session, and through it I ssh to an Ubuntu server; on this server I connect to a permanently-running GNU screen session, which has several multiplexed windows going, all running zsh; it is in this convoluted environment that I run the python interactive interpreter.[*] I've determined that the problem occurs only within the GNU screen session. GNU screen is one of the coolest Unix programs ever, one that literally changed the way I work, is there's no way I'll stop using it. So I need to figure out how to fix this. How can I determine the character that the python session is receiving when I hit the backspace key, and how can I tell it to handle it as a backward-delete character? TIA! kynn [*] Actually, it gets worse. My .zshrc file (which gets executed whenever an interactive shell is started) runs the command bindkey '^[[3~' backward-delete-char because, otherwise my regular zsh interaction would not handle the backspace key properly. But the problem I described above occurs whether this command is executed or not. -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Defunct when using subprocess.Popen
Title: Defunct when using subprocess.Popen Hi! I hope someone can help me out here! I'm running a GUI in python which is able to launch a separate python process that will run forever. In rare cases I will want to kill the launched process. Every time I do so, I end up with the process as defunct. Can anybody help me clean it up in a nice way? My code snippets: #Launching a separate process (no communication in between the process needed) # When closing the GUI, the launched program should not be killed. command = ['test.py',' -c ',config] process = subprocess.Popen(command, preexec_fn = os.setsid) On request from GUI I do the following: os.kill(process.pid,9) FYI, it is all running on Linux. All suggestions are appreciated! -- http://mail.python.org/mailman/listinfo/python-list
Defunct when using subprocess.Popen
Title: Defunct when using subprocess.Popen Hi! I hope someone can help me out here! I'm running a GUI in python which is able to launch a separate python process that will run forever. In rare cases I will want to kill the launched process. Every time I do so, I end up with the process as defunct. Can anybody help me clean it up in a nice way? My code snippets: #Launching a separate process (no communication in between the process needed) # When closing the GUI, the launched program should not be killed. command = ['test.py',' -c ',config] process = subprocess.Popen(command, preexec_fn = os.setsid) On request from GUI I do the following: os.kill(process.pid,9) FYI, it is all running on Linux. All suggestions are appreciated! -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Interpreter
Victor Subervi wrote: def a(): chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', '\\yz'] rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the Beast? Who can wage war against him?\par' for char in chars: c = '(?<=' + char + ')' test = re.search(c, rtf_markup) try: junk = test.group(0) print char except: pass Now, I can paste that entire fn in linux. But in windows I have to paste it line_by_line. Pain in butt! And it indents automatically. How change that behavior. Well, I'm not really sure what to say. I've just copied that whole section with drag-mouse, Ctrl-C. I then opened a new interpreter window (effectively, Start > Run > python) and right-clicked over the window. At this point, the lines I copied were copied in and the function accepted by the interpreter. I do have QuickEdit on by default in all by console windows, but the only difference I expect that to make is that you'd otherwise have to use the window's System Menu (Alt-Space, Edit, Paste). TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Swap memory in Python ? - three questions
Robert LaMarca <[EMAIL PROTECTED]> wrote: > Hi, > > I am using numpy and wish to create very large arrays. My system is > AMD 64 x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a > 15 GB swap drive. > > The command I have been trying to use is; > g=numpy.ones([1000,1000,1000],numpy.int32) > > This returns a memory error. Works for me on AMD64x2, 2GB RAM, 3GB swap. With much paging of course ;) Process size of python 4019508kB. > A smaller array ([500,500,500]) worked fine.. About 0.5GB.. no surprise. > Two smaller arrays again crashed the system. Crash as in "computer reboots"? Strange. And you say, that two [500, 500, 500] arrays are two much? > So... I did the math. a 1000x1000x1000 array at 32 bits should be > around 4gb RAM... Obviously larger than RAM, but much smaller than the > swap drive. Sounds like either your kernel or python are not 64bit. For the kernel, have a look at /proc/meminfo, which value you get for VmallocTotal. I have VmallocTotal: 34359738367 kB. For python, check sys.maxint. If it's 2147483647, then you have a 32bit python. Mine says 9223372036854775807. > 1. So... does Numpy have a really lot of overhead? Or is my system > just not somehow getting to make use of the 15gb swap area. No. Yes. > 2. Is there a way I can access the swap area, or direct numpy to do > so? Or do I have to write out my own numpy cache system... > 3. How difficult is it to use data compression internally on numpy > arrays? 2 + 3: Should not be necessary. I just tried a 32bit python on my 64bit system, using Numeric instead of numpy (don't have a 32bit numpy ready): g=Numeric.zeros([1000,1000,1000],Numeric.Int32) Traceback (most recent call last): File "", line 1, in MemoryError: can't allocate memory for array g=Numeric.zeros([1000,1000,500],Numeric.Int32) succeeds. So it looks like you have a 32bit kernel. Marc -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions about asyncore
On 29 Lug, 13:09, Frank Millman <[EMAIL PROTECTED]> wrote: > Firstly, having got asyncore working, I had a look at asynchat. As far > as I can see I get very little benefit from using it. I have already > set up a 'messaging' protocol between server and client, where all > messages consist of 5 digits for the message length, followed by the > message. The message consists of a pickled tuple, where the first > element is a message identifier, and the rest is the message body. > > This is how it works in asyncore - > > def __init__(self,channel): > [...] > self.msgLength = 0 > self.recvData = '' # temporary buffer > > def handle_read(self): > self.recvData += self.recv(8192) > if not self.msgLength: > if len(self.recvData) < 5: # 1st 5 bytes = msg length > return > self.msgLength = int(self.recvData[:5]) > self.recvData = self.recvData[5:] > if len(self.recvData) < self.msgLength: > return > data = loads(self.recvData[:self.msgLength]) > self.recvData = self.recvData[self.msgLength:] > self.msgLength = 0 > [handle data] > > This is how I got it working in asynchat - > > def __init__(self,channel): > [...] > self.recvData = '' # temporary buffer > self.set_terminator(5) > self.gotMsgLength = False > > def collect_incoming_data(self, data): > self.recvData += data > > def found_terminator(self): > if self.gotMsgLength: # what follows is the message > data = loads(self.recvData) > self.set_terminator(5) > self.gotMsgLength = False > [handle data] > else: # what follows is the message length > self.set_terminator(int(self.recvData)) > self.gotMsgLength = True > self.recvData = '' > > It may be slightly neater, but it does not seem worth adding an extra > layer just for that. Does asynchat give me any other benefits I may > have overlooked? The benefit of asynchat is that it automatically handles the buffering of both input and output. Aside from set/found_terminator() the other two methods you could want to look at are push() and push_with_producer(). push() is a buffered version of asyncore.send(), push_with_producer() accepts a data-producer object you can use in case you want to deal with something other than strings (e.g. files, lists, generators, and so on...). > My second question relates to writing a dummy client program to test > the server. I just want to send it some messages and print the > responses. Some messages incorporate data extracted from previous > responses, so I have to wait for the reply before continuing. > > I am using asyncore for this as well. However, the only way I can > think of to get it working is to run asyncore.dispatcher in a separate > thread. > > To send messages, I append them to a list of messages to be sent. The > dispatcher method writable() returns True if there is anything in the > list, else False. > > To receive messages, I run a 'while 1' loop in the main thread, with a > sleep of 0.1, until recvData has something in it. > > It works, but it seems odd to use a separate thread, as one of the > points of asyncore is to avoid multi-threading. Is there a better way > to write the client program? I'm not sure to understand but I doubt you have to use a thread. If you "have to wait for the reply before continuing" just implement this logic into handle_read() or found_terminator() method. --- Giampaolo http://code.google.com/p/pyftpdlib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: backspace problems
In <[EMAIL PROTECTED]> kj <[EMAIL PROTECTED]> writes: Please ignore my question. I found a general solution that works not only for the python interactive interpreter but also for all programs that have a readline-type interaction. This solution has nothing to do with Python, but if anyone's interested, it's here: http://www.macosxhints.com/article.php?story=20040930002324870&query=backspace%2Bdebian kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
Heiko Wundram wrote: Am Dienstag, 29. Juli 2008 11:15:05 schrieb Heiko Wundram: I can't dig up a simple example from code I wrote quickly... Just to get back to that: an example I found where "if x" (the generic __nonzero__() test) will work to test for emptiness/non-emptiness of a container, whereas "if len(x) > 0" (the "specific" test for this example) will not, is my for own integer set type I wrote a while back (which you can find on ASPN). The corresponding set type allows you to create infinitely sized sets of integers (which of course are stored as pairs of ,-values, so the storage itself for the set is bounded), for which len(x) does not have a "proper" meaning anymore, and __len__() is limited to returning a (platform dependent) ssize_t anyway IIRC, so even with a bounded set, the length of the set might not necessarily be accessible using len(x); that's why the set type additionally got a member function called .len() to work around this restriction. I should think is a non-contrieved example where the generic test whether the object considers itself True/False (which for containers means non-empty/empty) is preferrable over the special case test whether the length is positive. A polymorphic function, which for example only accesses the first ten members of the container is able to work with an infinite set if it uses the generic test, but is not in case it uses len(x) > 0. (+1) This an Heiko's previous post sets things out clearly. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
pygtk treview, ListStore not displaying properly
hi group i am running into a problem with gtk. i have a treeview that
just displays tabular data (no down arrows or trees etc). it has 5
columns. The tiny problem i am having is that it is just display the
data of the column named `title` in all the colums!
here the pic of the app in action
http://i36.tinypic.com/2djcqqr.png
the related code of the app is as follows:
self.tv = self.glade.get_widget('treeview1') #the treeview object
def show_sync_wind(self,obj, data = None):
t = Template.select(Template.q.synced == '0')
self.synclstore = gtk.ListStore(str,str,str,str,str)
x = 0
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('#', cr);
col.add_attribute(cr, 'markup', 1)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(0)
self.tv.append_column(col)
self.sno_col = col
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('Title', cr);
col.add_attribute(cr, 'markup', 1)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(1)
self.tv.append_column(col)
self.title_col = col
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('Section', cr);
col.add_attribute(cr, 'markup', 1)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(2)
self.tv.append_column(col)
self.section_col = col
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('Category', cr);
col.add_attribute(cr, 'markup', 1)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(3)
self.tv.append_column(col)
self.category_col = col
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('Sync', cr);
col.add_attribute(cr, 'markup', 1)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(4)
self.tv.append_column(col)
self.sync_col = col
self.tv.set_model(self.synclstore)
self.tv.set_headers_clickable(True)
#self.tv.set_expander_column(self.title_col)
for y in t:
row =
self.synclstore.append([str(x),y.title,y.section.name,y.category.name,y.synced])
self.synclstore.set(row,0,'0')
self.synclstore.set(row,1,y.title)
self.synclstore.set(row,2,y.section.name)
self.synclstore.set(row,3,y.category.name)
self.synclstore.set(row,4,y.synced)
self.sync_window.show()
--
http://mail.python.org/mailman/listinfo/python-list
Re: Automatically loading and initialising objects from a plugins directory
On Jul 25, 7:50 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > It's a potentially brain-exploding topic, -that you made very understandable. Thanks for posting that explanation and example. -- http://mail.python.org/mailman/listinfo/python-list
Re: block/lambda
> 2. Will it be possible in Python 3.0 to do the following: > > >>> def dotimes(n, callable): > > for i in range(n): callable() > > >>> def block(): > > nonlocal i > for j in range(i): > print j, > print dotimes seems ok and what is wrong with that function "block"? You do not need to specify that i is "nonlocal", global i will be used. >>> i=10 >>> def block(): for j in range(i): print j, print >>> block() 0 1 2 3 4 5 6 7 8 9 Jiri -- http://mail.python.org/mailman/listinfo/python-list
[unittest] Run setUp only once
Hello, I have a number of conceptually separate tests that nevertheless need a common, complicated and expensive setup. Unfortunately, unittest runs the setUp method once for each defined test, even if they're part of the same class as in class TwoTests(unittest.TestCase): def setUp(self): # do something very time consuming def testOneThing(self): def testADifferentThing(self): which would call setUp twice. Is there any way to avoid this, without packing all the unrelated tests into one big function? Best, -Nikolaus -- »It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.« -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C -- http://mail.python.org/mailman/listinfo/python-list
Re: block/lambda
On Tue, 29 Jul 2008 07:26:38 -0700 (PDT), "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: 2. Will it be possible in Python 3.0 to do the following: >>> def dotimes(n, callable): for i in range(n): callable() >>> def block(): nonlocal i for j in range(i): print j, print dotimes seems ok and what is wrong with that function "block"? You do not need to specify that i is "nonlocal", global i will be used. i=10 def block(): for j in range(i): print j, print block() 0 1 2 3 4 5 6 7 8 9 Python doesn't have dynamic scoping. >>> def dotimes(n, callable): ... for i in range(n): ... callable() ... >>> def block(): ... for j in range(i): ... print j, ... print ... >>> def f(): ... dotimes(5, block) ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f File "", line 3, in dotimes File "", line 2, in block NameError: global name 'i' is not defined >>> The "nonlocal" keyword in Python 3 won't do this, either. It's for referencing names in outer lexical scopes, not outer dynamic scopes. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: [unittest] Run setUp only once
On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath <[EMAIL PROTECTED]> wrote: Hello, I have a number of conceptually separate tests that nevertheless need a common, complicated and expensive setup. Unfortunately, unittest runs the setUp method once for each defined test, even if they're part of the same class as in class TwoTests(unittest.TestCase): def setUp(self): # do something very time consuming def testOneThing(self): def testADifferentThing(self): which would call setUp twice. Is there any way to avoid this, without packing all the unrelated tests into one big function? class TwoTests(unittest.TestCase): setUpResult = None def setUp(self): if self.setUpResult is None: self.setUpResult = computeIt() ... There are plenty of variations on this pattern. Jean-Paul Best, -Nikolaus -- »It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.« -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Continuous integration for Python projects
Hi. Please correct my if I'm wrong but it seems to me that the major continuous integration servers (Hudson, CruiseControl, TeamCity ..) don't support Python based application. It seems they mainly support Java, .NET and Ruby. Can I use one of the previous listed servers for Python project? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
How do I include a shell variable in my script?
Hi, I'm running a Python script on a Solaris 9 machine, invoking the Python script from ksh, if that matters. There is an enviornment variable, $JAVA_HOME, that I would like to include in my script, replacing "/path/to/java/home'" with the value of $JAVA_HOME. java_home='/path/to/java/home' How do I do this? If I need to pass a command line argument, so be it, but I figure there is a more direct way to get the value. Thanks, - Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Continuous integration for Python projects
Hussein B wrote: > Hi. > Please correct my if I'm wrong but it seems to me that the major > continuous integration servers (Hudson, CruiseControl, TeamCity ..) > don't support Python based application. > It seems they mainly support Java, .NET and Ruby. > Can I use one of the previous listed servers for Python project? Hudson can, and AFAIK CC as well - they only invoke shell-scripts (at least hudson does, and CC you can convince doing that using ANT) So go ahead and use them - shouldn't be much (more) effort than for java projects. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Continuous integration for Python projects
On Tue, 29 Jul 2008 07:47:35 -0700 (PDT), Hussein B <[EMAIL PROTECTED]> wrote: Hi. Please correct my if I'm wrong but it seems to me that the major continuous integration servers (Hudson, CruiseControl, TeamCity ..) don't support Python based application. It seems they mainly support Java, .NET and Ruby. Can I use one of the previous listed servers for Python project? Thanks. I haven't used CruiseControl or the other CIS you mention, but I suspect they can probably support Python programs. The CruiseControl docs suggest that it supports builder plugins which can do arbitrary things. However, one CIS written in Python (which can also handle arbitrary builds, not just builds of Python software) is buildbot: http://buildbot.net/ Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I include a shell variable in my script?
On Tue, Jul 29, 2008 at 10:53 AM, laredotornado <[EMAIL PROTECTED]> wrote: > Hi, > > I'm running a Python script on a Solaris 9 machine, invoking the > Python script from ksh, if that matters. There is an enviornment > variable, $JAVA_HOME, that I would like to include in my script, > replacing "/path/to/java/home'" with the value of $JAVA_HOME. > > java_home='/path/to/java/home' import os java_home = os.environ['JAVA_HOME'] -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Build tool for Python
Hi. Apache Ant is the de facto building tool for Java (whether JSE, JEE and JME) application. With Ant you can do what ever you want: compile, generate docs, generate code, packing, deploy, connecting to remote servers and every thing. Do we have such a tool for Python projects? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
Carl Banks wrote: On Jul 28, 8:15 pm, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: On Jul 28, 10:00 am, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: Cutting to the crux of the discussion... On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: I want something where "if x" will do but a simple explicit test won't. Explicit tests aren't simple unless you know what type x is. If x could be of any type, you can't write a simple test. Does x have a length? Is it a number? Maybe it's a fixed-length circular length, and the length is non-zero even when it's empty? Who knows? How many cases do you need to consider? Use case, please. I'm asking for code, not arguments. Please give me a piece of code where you can write "if x" that works but a simple explicit test won't. I gave you a piece of code, actual code from one of my own projects. If you wouldn't accept that evidence then, why would you accept it now? I would accept as "evidence" something that satisfies my criteria, which your example did not: it could have easily (and more robustly) been written with a simple explicit test. I am looking for one that can't. You keep bringing up this notion of "more complex with no benefit", which I'm simply not interested in talking about that at this time, and I won't respond to any of your points. I am seeking the answer to one question: whether "if x" can usefully do something a simple explicit test can't. Everyone already knows that "if x" requires fewer keystrokes and parses to fewer nodes. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list My use case involves a DAG of filters that pass data (of a variety of types--filters just pass on data types they don't understand) between them. I can also drop out of the filter chain at any point, using critera determined by the filters. These criteria, you guessed it, are bound to __nonzero__ in the filter and I determine whether or not to continue through the graph using "if x". You can't code explicit tests if you don't know what the tests even are beforehand. Also, I wanted to support builtins (ints and lists in particular) because they can be meaningful inputs to filters. Finally, as I add more filters and data types, I don't want to go back and mess with the code that decides whether or not to break out of the graph. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Build tool for Python
Hussein B wrote: > Hi. > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? distutils and setuptools are used to create distributions of python-packages, potentially compiling e.g. C or pyrex-sources, and you can hook into them to create e.g. api-docs. Diez -- http://mail.python.org/mailman/listinfo/python-list
Overloaded Functions
Hi, So this may have been asked before but i haven't found the answer by googling so far. My situation is this: I want this structure for my code: @overloaded def sign_auth(secret, salt, auth_normalized): return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) @sign_auth.register(str, str) def sign_auth(secret_hash_normalized, auth_normalized): return __sign_auth(qcrypt.denormalize(secret_hash_normalized), auth_normalized) def __sign_auth(secret_hash_bin, auth_normalized): auth = qcrypt.denormalize(auth_normalized) aes = AES.new(secret_hash_bin, AES.MODE_CBC) plaintext = aes.decrypt(auth) ciphertext = qcrypt.normalize(xor_in_pi(plaintext)) if debug: print '\n--sign_auth--' print qcrypt.normalize(secret_hash_bin) print qcrypt.normalize(plaintext) print ciphertext print '-sign_auth---\n' return ciphertext I am using the overloading module from: http://svn.python.org/view/sandbox/trunk/overload/overloading.py?rev=43727&view=log However it doesn't actually support this functionality. Does any one know of a decorator that does this? It would be really nice to have a unified interface into the __sign_auth function for the two different use cases. Tim Henderson -- http://mail.python.org/mailman/listinfo/python-list
DB access without object-relation mapping?
Python noob here. I want to write a script that creates and populates a simple Postgres database. The word on the street is to use something like SQLAlchemy for database access in Python, but my experience in the past with packages that perform automated SQL generation has been awful, so I always return to lighter-weight solutions that allow me to write my own SQL. (E.g. when coding in Perl I've used Perl's DBI package and drivers, rather than the likes of Class::DBI.) So what's the standard Python way to send SQL directly to a Postgres database and get back results? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Build tool for Python
On Jul 29, 11:08 am, Hussein B <[EMAIL PROTECTED]> wrote: > Hi. > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? > Thank you. You might want to take a look at Paver. http://www.blueskyonmars.com/projects/paver/ Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: DB access without object-relation mapping?
On Jul 29, 11:20 am, kj <[EMAIL PROTECTED]> wrote: > Python noob here. > > I want to write a script that creates and populates a simple Postgres > database. > > The word on the street is to use something like SQLAlchemy for > database access in Python, but my experience in the past with > packages that perform automated SQL generation has been awful, so > I always return to lighter-weight solutions that allow me to write > my own SQL. (E.g. when coding in Perl I've used Perl's DBI package > and drivers, rather than the likes of Class::DBI.) So what's the > standard Python way to send SQL directly to a Postgres database > and get back results? > > TIA! > > kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. Hi, I believe there are a couple of options but pyscopg, and PyGreSQL seem to be popular. Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: Execution speed question
On Mon, 28 Jul 2008 16:48:28 +0200, Suresh Pillai wrote: > Okay, please consider this my one absolutely stupid post for the year. > I'd like to pretend it never happened but unfortunately the web doesn't > allow that. Having never used sets, I unfort read something that lead > to it, but ... Okay, got some sleep and what I meant to ask, although equally basic, but not silly: For sets, I presume they are built on top of or like dicts, and there is nothing crazy in the low level implementation so that I can be guaranteed that if I don't alter the set, then the order, although arbitrary, will be maintained in successive iterations over the contents? -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing VHDL with python, where to start.
Svenn Are Bjerkem schrieb: Hi again, when I get far enough to parse the VHDL (which is not currently the fact, but I have to look at the work coming up downstream) I will have to put it into an internal data structure and then write some classes to handle the MVC between whatever data I have and the PyQt4 widget that is going to show the block diagram. I own the book "Rapig GUI Programming with Python and Qt" by Mark Summerfield and try to read up on the PyQt way of doing things as I try to make a plan for my application. I have been looking for possible data structures with google just to find out that most of the ideas are stored in proceedings or to conferences or ieee papers not generally available to me. Is anybody experienced with designing data structures willing to share some ideas with me? Since I am using the open-source version of PyQt4, any information will eventually be available to public (if the app pass the planning stage) if that makes helping out any easier: :-) There is already an app called Qucs that is running in Qt-3 and being ported to Qt-4 that is written in C++, but I don't know how wise it is to just reverse-engineering C++ classes and translate them into python classes. For me it is not very clear what you intend to do. After years of parsing parts of VHDL from time to time the rapid parsing way for me is using regular expressions instead of one of the parser frame works because of following reasons: - It is hard for me to understand those frameworks - They are very slow - It is too much work for me to bring them up to work in a sensible way - Compared with regular expression matching they usually need a lot of extra work. Regular expressions work very well once the validation of the VHDL code was done by one of the commercial compilers. Once you can rely on the code that it is valid VHDL - Parse it with a regular expression for simple VHDL structures or - Extract a structure first and analyse that with a set of regular expressions The result can be stored into a combination of lists and dictionaries, dependend on the problem. For processing with other tools the results could be stored into XML structures. PyQt as a widget framework is not useful until here, but of course you could display your results in arbitrary graphical ways with PyQt, if you rally need to. You should know, printing out an ASCII or XML representation is so much more easy and quicker to code so I always prefer that. There are even editors/visualizers ready to display XML... Best regards Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
Re: pygtk treview, ListStore not displaying properly
finally i solved it. This for any googler who comes this way
def show_sync_wind(self,obj, data = None):
t = Template.select(Template.q.synced == '0')
self.synclstore = gtk.ListStore(str,str,str,str,str)
x = 0
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('#', cr);
col.set_attributes(cr, text=0)#<-- attaches col to the 0`th
item
of liststore
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(0)
self.tv.append_column(col)
self.sno_col = col
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('Title', cr);
col.set_attributes(cr, text=1)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(1)
self.tv.append_column(col)
self.title_col = col
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('Section', cr);
col.set_attributes(cr, text=2)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(2)
self.tv.append_column(col)
self.section_col = col
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('Category', cr);
col.set_attributes(cr, text=3)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(3)
self.tv.append_column(col)
self.category_col = col
cr = gtk.CellRendererText()
col = gtk.TreeViewColumn('Sync', cr);
col.set_attributes(cr, text=4)
col.set_expand(True)
col.set_clickable(True)
col.set_resizable(True)
col.set_sort_column_id(4)
self.tv.append_column(col)
self.sync_col = col
self.tv.set_model(self.synclstore)
self.tv.set_headers_clickable(True)
#self.tv.set_expander_column(self.title_col)
for y in t:
x = x+1
row =
self.synclstore.append([str(x),y.title,y.section.name,y.category.name,y.synced])
self.sync_window.show()
--
http://mail.python.org/mailman/listinfo/python-list
Public Pythn Classs, September 9, 2008
Holden Web is please to announce its third public "Introduction to Python" class, near Washington DC, from September 9-11. Further details are available from http://holdenweb.com/py/training/ We are also interested in adding to our course repertoire. If you have ideas for suitable one-day classes please visit http://holdenweb.blogspot.com/2008/07/one-day-python-classes.html and leave a comment on that page. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance and __getattr__
In article <[EMAIL PROTECTED]>,
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> Enrico a écrit :
> > Hi there,
> > I have the following situation (I tryed to minimize the code to concentrate
> > on the issue):
> >
> class A(object):
> > def __getattr__(self, name):
> > print 'A.__getattr__'
> > if name == 'a': return 1
> > raise AttributeError('%s not found in A' % name)
> >
> class B(object):
> > def __getattr__(self, name):
> > print 'B.__getattr__'
> > if name == 'b': return 1
> > raise AttributeError('%s not found in B' % name)
> >
> > Both classes have a __getattr__ method.
> > Now I want to have a class that inherits from both so I write:
> >
> class C(B,A):
> > pass
> >
> > The problem arise when I try something like this:
> c=C()
> c.a
> > A.__getattr__
> > 1
> c.b
> > A.__getattr__
> >
> > Traceback (most recent call last):
> > File "", line 1, in
> > c.b
> > File "", line 5, in __getattr__
> > raise AttributeError('%s not found in A' % name)
> > AttributeError: b not found in A
>
> That's what I would have expected.
>
> > I was expecting, after a fail in A.__getattr__, a call to the __getattr__
> > method of B but it seems that after A.__getattr__ fails the exception stops
> > the flow.
>
> Indeed. You explicitely raise, so the lookup stops here.
??? Surely the reason the lookup stops there is that a __getattr__
was _found_. In the code below the lookup is not continuing,
there's a _second_ lookup started by the request for super.__getattr__.
> You'd need to
> explicitely call on superclass instead to have B.__getattr__ called, ie:
>
> class A(object):
> def __getattr__(self, name):
> if name == 'a':
> return 1
> return super(A, self).__getattr__(name)
>
> class B(object):
> def __getattr__(self, name):
> if name == 'b':
> return 2
> return super(B, self).__getattr__(name)
>
> class C(A, B):
> pass
>
--
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list
Re: Is it allowed to use function results as default arguments ?
On 2008-07-29, Stef Mientki <[EMAIL PROTECTED]> wrote: > brings me to one other question: > I guess this function is only evaluated once, is that correct ? Yes. > about '.' being the current directory, well I think windows > was thrown at the market about 25 years ago, and since then we > don't use '.' anymore ;-) Who's "we"? I stull use "." as the current directory. -- Grant Edwards grante Yow! Mary Tyler Moore's at SEVENTH HUSBAND is wearing visi.commy DACRON TANK TOP in a cheap hotel in HONOLULU! -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloaded Functions
Tim Henderson wrote: Hi, So this may have been asked before but i haven't found the answer by googling so far. My situation is this: I want this structure for my code: @overloaded def sign_auth(secret, salt, auth_normalized): return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) @sign_auth.register(str, str) def sign_auth(secret_hash_normalized, auth_normalized): return __sign_auth(qcrypt.denormalize(secret_hash_normalized), auth_normalized) def __sign_auth(secret_hash_bin, auth_normalized): auth = qcrypt.denormalize(auth_normalized) aes = AES.new(secret_hash_bin, AES.MODE_CBC) plaintext = aes.decrypt(auth) ciphertext = qcrypt.normalize(xor_in_pi(plaintext)) if debug: print '\n--sign_auth--' print qcrypt.normalize(secret_hash_bin) print qcrypt.normalize(plaintext) print ciphertext print '-sign_auth---\n' return ciphertext I am using the overloading module from: http://svn.python.org/view/sandbox/trunk/overload/overloading.py?rev=43727&view=log However it doesn't actually support this functionality. Does any one know of a decorator that does this? It would be really nice to have a unified interface into the __sign_auth function for the two different use cases. Are you aware that you can do this kind of thing yourself, without using a module/decorator. def sign_auth(*args): if len(args) == 3: secret, salt, auth_normalized = args return __sign_auth(saltedhash_bin(secret, salt), auth_normalized) elif len(args) == 2: secret_hash_normalized, auth_normalized = args return __sign_auth(qcrypt.denormalize(secret_hash_normalized), auth_normalized) The checks could be more involved, perhaps checking not jsut the nuimber of args, but their types, and even their values, before calling __sign_auth(...). Gary Herron Tim Henderson -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: DB access without object-relation mapping?
On 29 Jul, 17:20, kj <[EMAIL PROTECTED]> wrote: > > So what's the > standard Python way to send SQL directly to a Postgres database > and get back results? Take a look at this page: http://wiki.python.org/moin/DatabaseInterfaces I've used psycopg2 and pyPgSQL successfully, although pg_proboscis looks very interesting, too. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloaded Functions
Yes i am aware of that but I want the code to be self documenting, so the intent is clear. I actually have an implementation using that style which you suggest. I would like cleaner style, like the one i suggested in my first post. Cheers Tim Henderson -- http://mail.python.org/mailman/listinfo/python-list
proxy class and __add__ method
Hello, I have written the following small proxy class which I expect to pass all function calls to the 'original' object: --- BEGIN --- class proxy(object): def __init__( self, subject ): self.__subject = subject def __getattr__( self, name ): return getattr( self.__subject, name ) prx_i=proxy(1) print hasattr(prx_i,'__add__') j=prx_i.__add__(1) k=prx_i+1 --- END --- Actually the "hasattr(prx_i,'__add__')" returns "True" as expected, and "j=prx_i.__add__(1)" sets j=2. But "k=prx_i+1" raises a : unsupported operand type(s) for +: 'proxy' and 'int'. How is this addition different from the previous line "j=..."? And how can I modify the proxy class so that all methods are passed on, which are not explicitly overloaded? Regards, Magnus -- View this message in context: http://www.nabble.com/proxy-class-and-__add__-method-tp18715799p18715799.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Build tool for Python
On 29 Jul, 17:08, Hussein B <[EMAIL PROTECTED]> wrote: > Apache Ant is the de facto building tool for Java (whether JSE, JEE > and JME) application. > With Ant you can do what ever you want: compile, generate docs, > generate code, packing, deploy, connecting to remote servers and every > thing. > Do we have such a tool for Python projects? There are quite a few similar tools here: http://wiki.python.org/moin/ConfigurationAndBuildTools Having looked at a few such tools recently, I found myself considering using plain old make for automating various non-compilation-related activities, but then again, plain Python is actually very good for automation if you get into the right mindset. Consequently, I've just written a bunch of functions which run programs, test outputs and potentially feed those outputs to other programs. Where most of the available generic tools seem to frustrate is in their support of the often necessary but complicated behaviour required to minimise the amount of unnecessary work performed, through frameworks which seem to obscure the nature of the work itself. I do understand that it can be awkward to work out which object files need recompiling due to changes in source files, for example, and that one doesn't want to see the logic involved reproduced all over the place, but I do wonder whether the machinery around such matters isn't sometimes more complicated in these tools as soon as one strays outside the common cases. It seems to me that some common build-related primitives implemented as functions combined with plain Python would be a good enough combination for a lot of tasks in this domain. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Execution speed question
Suresh Pillai wrote: > On Mon, 28 Jul 2008 16:48:28 +0200, Suresh Pillai wrote: > >> Okay, please consider this my one absolutely stupid post for the year. >> I'd like to pretend it never happened but unfortunately the web doesn't >> allow that. Having never used sets, I unfort read something that lead >> to it, but ... > > Okay, got some sleep and what I meant to ask, although equally basic, but > not silly: > > For sets, I presume they are built on top of or like dicts, and there is > nothing crazy in the low level implementation so that I can be guaranteed > that if I don't alter the set, then the order, although arbitrary, will > be maintained in successive iterations over the contents? It is currently that way, but relying on it is certainly to be considered an implementation detail that might disappear without warning. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Continuous integration for Python projects
Diez B. Roggisch <[EMAIL PROTECTED]> wrote: >Hussein B wrote: >> Please correct my if I'm wrong but it seems to me that the major >> continuous integration servers (Hudson, CruiseControl, TeamCity ..) >> don't support Python based application. >> It seems they mainly support Java, .NET and Ruby. >> Can I use one of the previous listed servers for Python project? >Hudson can, and AFAIK CC as well - they only invoke shell-scripts (at least >hudson does, and CC you can convince doing that using ANT) You can definitely set up CruiseControl to handle Python, but don't ask me for details as it was a couple of years and a change of job ago. I seem to remember it being easier when CC was driving make, but we had makefiles in any case for building the extension modules needed -- writing a makefile from scratch might be a bit much. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Interpreter
I´ll try that. Back online in a week. Victor On 7/29/08, Tim Golden <[EMAIL PROTECTED]> wrote: > > Victor Subervi wrote: > >> def a(): >> chars = ['\\i0', '\\u0', '\\qc', '\\b0', '\\ql', '\\i', '\\u', '\\b', >> '\\yz'] >> rtf_markup = 'viewkind4\uc1\pard\nowidctlpar\qc\i\f0\fs36 Who is like the >> Beast? Who can wage war against him?\par' >> for char in chars: >>c = '(?<=' + char + ')' >>test = re.search(c, rtf_markup) >>try: >> junk = test.group(0) >> print char >>except: >> pass >> >> Now, I can paste that entire fn in linux. But in windows I have to paste >> it line_by_line. Pain in butt! And it indents automatically. How change that >> behavior. >> > > Well, I'm not really sure what to say. I've just copied that > whole section with drag-mouse, Ctrl-C. I then opened a new > interpreter window (effectively, Start > Run > python) and > right-clicked over the window. At this point, the lines I > copied were copied in and the function accepted by the > interpreter. > > I do have QuickEdit on by default in all by console windows, > but the only difference I expect that to make is that you'd > otherwise have to use the window's System Menu (Alt-Space, > Edit, Paste). > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: DB access without object-relation mapping?
In <[EMAIL PROTECTED]> Tim Henderson <[EMAIL PROTECTED]> writes: >I believe there are a couple of options but pyscopg, and PyGreSQL seem >to be popular. Great. Thanks! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: [unittest] Run setUp only once
Jean-Paul Calderone <[EMAIL PROTECTED]> writes: > On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath <[EMAIL PROTECTED]> wrote: >>Hello, >> >>I have a number of conceptually separate tests that nevertheless need >>a common, complicated and expensive setup. >> >>Unfortunately, unittest runs the setUp method once for each defined >>test, even if they're part of the same class as in >> >>class TwoTests(unittest.TestCase): >>def setUp(self): >># do something very time consuming >> >>def testOneThing(self): >> >> >>def testADifferentThing(self): >> >> >>which would call setUp twice. >> >> >>Is there any way to avoid this, without packing all the unrelated >>tests into one big function? >> > >class TwoTests(unittest.TestCase): >setUpResult = None > >def setUp(self): >if self.setUpResult is None: >self.setUpResult = computeIt() > >... > > There are plenty of variations on this pattern. But at least this variation doesn't work, because unittest apparently also creates two separate TwoTests instances for the two tests. Isn't there some way to convince unittest to reuse the same instance instead of trying to solve the problem in the test code itself? Best, -Nikolaus -- »It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.« -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
On Jul 29, 5:27 am, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > > I am looking for one that can't. > > If you are writing code that needs to do the right thing with arbitrary > types, then your so-called "simple explicit tests" simply can't work. I asked for a code example. You say this is true, but neither you nor anyone else here has provided useful code that demonstrates it. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Newbie Python questions
I recently discovered Python and see it as a great language to use for personal projects (and more). I made my living for over a decade as a coder in C, C++, ADA, Fortran, and Assembly before moving to systems engineering. I'm now retired, and would love to code again. I see Python as the perfect language to get a good program working in a short time. My question is in regard to GUI platforms. My primary target would be Windows, but I would also like be able to support Linux and Mac versions if possible. I'm also interested in using a system that also has support for pure C++ applications. As such, and after reading many web pages regarding Python GUIs, I believe I have the candidates narrowed down to pyQT and wxPython. The first question -- how steep is the curve to become proficient with the above GUI packages? If the answer is "not very" then there is no need for the following questions as I can try both on for size to see which I like best. However if it is a sizable investment in time, I'd like to maximize my efforts and choose the one I'll end up using in the end. The biggest hurdle I can see is the cost of the QT licence for commercial software, though apparently it can be acquired for a reasonable price via the BlackAdder package. Does purchasing the BlackAdder also include the needed software support for C++ development? Does the BlackAdder purchase also allow for licence of standard C++ apps? Since there appears to be no commercial licencing fee for wxWidgets/ wxPython, the last question is what do I gain from going QT over wx? I've seen great applications written with both (on my computer I have the wxPython Digsby and the pyQT apps "Mnemosyne" and "Anki". All seem to be solid. -- http://mail.python.org/mailman/listinfo/python-list
Re: [unittest] Run setUp only once
On Tue, 29 Jul 2008 19:26:09 +0200, Nikolaus Rath <[EMAIL PROTECTED]> wrote: Jean-Paul Calderone <[EMAIL PROTECTED]> writes: On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath <[EMAIL PROTECTED]> wrote: Hello, I have a number of conceptually separate tests that nevertheless need a common, complicated and expensive setup. Unfortunately, unittest runs the setUp method once for each defined test, even if they're part of the same class as in class TwoTests(unittest.TestCase): def setUp(self): # do something very time consuming def testOneThing(self): def testADifferentThing(self): which would call setUp twice. Is there any way to avoid this, without packing all the unrelated tests into one big function? class TwoTests(unittest.TestCase): setUpResult = None def setUp(self): if self.setUpResult is None: self.setUpResult = computeIt() ... There are plenty of variations on this pattern. But at least this variation doesn't work, because unittest apparently also creates two separate TwoTests instances for the two tests. Isn't there some way to convince unittest to reuse the same instance instead of trying to solve the problem in the test code itself? Eh sorry, you're right, the above is broken. `setUpResult` should be a class attribute instead of an instance attribute. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
On Jul 29, 5:15 am, Heiko Wundram <[EMAIL PROTECTED]> wrote: > I can't dig up a simple example from code I wrote quickly, but because of the > fact that explicit comparisons always hamper polymorphism I'm not going to take your word for it. Do you have code that demonstrates how "if x" improves polymorphism relative to simple explicit tests? Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
iterating "by twos"
Is there a special pythonic idiom for iterating over a list (or tuple) two elements at a time? I mean, other than for i in range(0, len(a), 2): frobnicate(a[i], a[i+1]) ? I think I once saw something like for (x, y) in forgotten_expression_using(a): frobnicate(x, y) Or maybe I just dreamt it! :) Thanks! -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
On Jul 29, 11:12 am, Matthew Fitzgibbons <[EMAIL PROTECTED]> wrote: > Carl Banks wrote: > > On Jul 28, 8:15 pm, Steven D'Aprano <[EMAIL PROTECTED] > > cybersource.com.au> wrote: > >> On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote: > >>> On Jul 28, 10:00 am, Steven D'Aprano <[EMAIL PROTECTED] > >>> cybersource.com.au> wrote: > Cutting to the crux of the discussion... > On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote: > > I want something where "if x" will do but a simple explicit test > > won't. > Explicit tests aren't simple unless you know what type x is. If x could > be of any type, you can't write a simple test. Does x have a length? Is > it a number? Maybe it's a fixed-length circular length, and the length > is non-zero even when it's empty? Who knows? How many cases do you need > to consider? > >>> Use case, please. I'm asking for code, not arguments. Please give me a > >>> piece of code where you can write "if x" that works but a simple > >>> explicit test won't. > >> I gave you a piece of code, actual code from one of my own projects. If > >> you wouldn't accept that evidence then, why would you accept it now? > > > I would accept as "evidence" something that satisfies my criteria, > > which your example did not: it could have easily (and more robustly) > > been written with a simple explicit test. I am looking for one that > > can't. > > > You keep bringing up this notion of "more complex with no benefit", > > which I'm simply not interested in talking about that at this time, > > and I won't respond to any of your points. I am seeking the answer to > > one question: whether "if x" can usefully do something a simple > > explicit test can't. Everyone already knows that "if x" requires > > fewer keystrokes and parses to fewer nodes. > > > Carl Banks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > My use case involves a DAG of filters that pass data (of a variety of > types--filters just pass on data types they don't understand) between > them. I can also drop out of the filter chain at any point, using > critera determined by the filters. These criteria, you guessed it, are > bound to __nonzero__ in the filter and I determine whether or not to > continue through the graph using "if x". You can't code explicit tests > if you don't know what the tests even are beforehand. Also, I wanted to > support builtins (ints and lists in particular) because they can be > meaningful inputs to filters. Finally, as I add more filters and data > types, I don't want to go back and mess with the code that decides > whether or not to break out of the graph. Much like in Steven D'Aprano's example, still the only actual code snippet I've seen, it seems that this can easily be done with a simple explicit test by having all no-advance filters return None and testing with "if x is not None". So it doesn't pass my criterion of being not replaceable with simple explicit test. Maybe that's not workable for some reason. Perhaps if you'd post a code example that shows this, rather than just talking about it, you might be more persuasive. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
On Jul 29, 1:30 pm, Carl Banks <[EMAIL PROTECTED]> wrote: > On Jul 29, 5:15 am, Heiko Wundram <[EMAIL PROTECTED]> wrote: > > > I can't dig up a simple example from code I wrote quickly, but because of > > the > > fact that explicit comparisons always hamper polymorphism > > I'm not going to take your word for it. Do you have code that > demonstrates how "if x" improves polymorphism relative to simple > explicit tests? And, in case it wasn't obvious, the way to demonstrate that "if x" improves polymorphism relative to simple explicit tests would be posting an example where "if x" works but a simple explicit test doesn't. So don't accuse me of changing the question on you: it's the same question. You see, what you are stating and expecting me to take for granted is exactly what I'm asking for a concrete example of. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing VHDL with python, where to start.
On Jul 29, 5:14 pm, Wolfgang Grafen <[EMAIL PROTECTED]> wrote: > For me it is not very clear what you intend to do. After years of > parsing parts of VHDL from time to time the rapid parsing way for me is > using regular expressions instead of one of the parser frame works > because of following reasons: > > - It is hard for me to understand those frameworks > - They are very slow > - It is too much work for me to bring them up to work in a sensible way > - Compared with regular expression matching they usually need a lot of > extra work. I agree with frameworks being difficult to understand and that is why I also have been using regular expressions in tcl to parse spice netlists before. Now I want to parse spice, vhdl and also maybe verilog. I think I will end up with regular expressions unless I get a grip on SimpleParse. The rationale for the whole project has been to finally be able to view spice and specially vhdl code for projects I work on. This has been something I have wanted to have for years, without having the ressources to complete it. There are commercial tools available, but I was looking for something more open/free that could be maintained independently of what tools I have at work. > PyQt as a widget framework is not useful until here, but of course you > could display your results in arbitrary graphical ways with PyQt, if you > rally need to. You should know, printing out an ASCII or XML > representation is so much more easy and quicker to code so I always > prefer that. There are even editors/visualizers ready to display XML... PyQt4 doesn't help me parse my sources, but it helps me visualise them. I did something in tcl/tk to get hierarchical spice netlists into a tree structure, but extending that app was too much hassle. PyQt4 offers a lot of functionality once the threshold of learning it has been passed. It also installs nicely on windows and most linux distributions offer it ready to install. And I like Qt. -- Svenn -- http://mail.python.org/mailman/listinfo/python-list
I CAN connect socket to any localhost port but I shouldn't be able to
Hi,
I don't have server listening on port 8084 but I can open socket to it
(and to many other ports, tested for all<8000)
import socket
def test(port):
af, socktype, proto, canonname, sa =
socket.getaddrinfo('localhost', port,
socket.AF_INET, socket.SOCK_STREAM)[0]
s = socket.socket(af, socktype, proto)
s.settimeout(1.0)
s.connect(('localhost', port))
s.close()
# This doesn't throw socket.error, it happily finishes
for x in range(1, 8000):
test(x)
Thanks,
Tvrtko
--
http://mail.python.org/mailman/listinfo/python-list
Re: iterating "by twos"
kj wrote: Is there a special pythonic idiom for iterating over a list (or tuple) two elements at a time? I mean, other than for i in range(0, len(a), 2): frobnicate(a[i], a[i+1]) ? I think I once saw something like for (x, y) in forgotten_expression_using(a): frobnicate(x, y) Or maybe I just dreamt it! :) Thanks! I saw the same thing, forgot where though. But I put it in my library. Here it is: # x.py import itertools def pairs(seq): is1 = itertools.islice(iter(seq), 0, None, 2) is2 = itertools.islice(iter(seq), 1, None, 2) return itertools.izip(is1, is2) s = range(9) for x, y in pairs(s): print x, y [EMAIL PROTECTED]> python x.py 0 1 2 3 4 5 6 7 -- http://mail.python.org/mailman/listinfo/python-list
Re: Boolean tests [was Re: Attack a sacred Python Cow]
On Jul 29, 5:27 am, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Tue, 29 Jul 2008 01:37:45 -0700, Carl Banks wrote: > > I would accept as "evidence" something that satisfies my criteria, which > > your example did not: it could have easily (and more robustly) been > > written with a simple explicit test. > > Only at the cost of completely ignoring the functional requirements and > changing the API. In other words: you ignore my code, and invent your own > imaginary code that does something completely different, then say that > this imaginary code is better. And, BTW, you keep making unsubstantiated assertions and keep expecting me to take them at face value. I'm really not going to take your word for it that your "functional requirements" would preclude the possibility of rewriting it as I said to, unless you provide details. Also, your third claim is false since it would have exactly the same behavior. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: iterating "by twos"
Something like this may be fast enough: >>> from itertools import izip >>> xpartition = lambda seq, n=2: izip(*(iter(seq),) * n) >>> xprimes = (x for x in xrange(2, 100) if all(x % i for i in xrange(2, x))) >>> list(xpartition(xprimes)) [(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, 37), (41, 43), (47, 53), (59, 61), (67, 71), (73, 79), (83, 89)] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Python parsing iTunes XML/COM
To ask another way: how do I convert from a file:// URL to a local path in a standard way, so that filepaths from two different sources will work the same way in a dictionary? Right now I'm using the following source: track_id = url2pathname(urlparse(track_id).path) url2pathname is from urllib; urlparse is from the urlparse module. The problems occur when the filenames have non-ascii characters in them -- I suspect that the URLs are having some encoding placed on them that Python's decoder doesn't know about. Thank you all in advance, and thank you for Python. -Wm -- http://mail.python.org/mailman/listinfo/python-list
it is a computer langugage
hai just click this a computer langugage www.insurances8blogspot -- http://mail.python.org/mailman/listinfo/python-list
Re: [unittest] Run setUp only once
Jean-Paul Calderone <[EMAIL PROTECTED]> writes: > On Tue, 29 Jul 2008 19:26:09 +0200, Nikolaus Rath <[EMAIL PROTECTED]> wrote: >>Jean-Paul Calderone <[EMAIL PROTECTED]> writes: >>> On Tue, 29 Jul 2008 16:35:55 +0200, Nikolaus Rath <[EMAIL PROTECTED]> wrote: Hello, I have a number of conceptually separate tests that nevertheless need a common, complicated and expensive setup. Unfortunately, unittest runs the setUp method once for each defined test, even if they're part of the same class as in class TwoTests(unittest.TestCase): def setUp(self): # do something very time consuming def testOneThing(self): def testADifferentThing(self): which would call setUp twice. Is there any way to avoid this, without packing all the unrelated tests into one big function? >>> >>>class TwoTests(unittest.TestCase): >>>setUpResult = None >>> >>>def setUp(self): >>>if self.setUpResult is None: >>>self.setUpResult = computeIt() >>> >>>... >>> >>> There are plenty of variations on this pattern. >> >> >>But at least this variation doesn't work, because unittest apparently >>also creates two separate TwoTests instances for the two tests. Isn't >>there some way to convince unittest to reuse the same instance instead >>of trying to solve the problem in the test code itself? >> > > Eh sorry, you're right, the above is broken. `setUpResult` should be > a class attribute instead of an instance attribute. Yeah, well, I guess that would work. But to me this looks really more like a nasty hack.. isn't there a proper solution? Best, -Nikolaus -- »It is not worth an intelligent man's time to be in the majority. By definition, there are already enough people to do that.« -J.H. Hardy PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C -- http://mail.python.org/mailman/listinfo/python-list
Where is the documentation for psycopg2?
Hi. I can't find any documentation for psycopg2. I'm a noob, so I'm sure I'm just not looking in the right place... Anybody know where it is? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
