Re: Multithreaded Python FSM (Harel State Machines)
WOW! Thanks, this looks remarkabley close to what I was talking about. Len fraca7 wrote: Leonard J. Reder a crit : [snip] http://smc.sourceforge.net/ It's probably not what you're looking for, but it's the closest I can think of. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: IssueTrackerProduct 0.6.9 with AJAX and Reports
selam benim ismim samet bende sizin gruba katilmak istiyorumkabul ederseniz sevinirim etmeseniz ayrilirim -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop until condition is true
Quoth Remi Villatel [EMAIL PROTECTED]: | What I'm trying to achieve is a conditionnal loop of which the condition | test would be done at the end so the loop is executed at least once. It's | some way the opposite of while. | | So far, all I got is: | | while True: | some(code) | if final_condition is True: | break | # | # | | What I don't find so nice is to have to build an infinite loop only to | break it. | | Is there a better recipe? It depends, but that isn't too bad. The alternative would be flag variable, like looping = 1; while looping: ... The construct you're looking for is until in C, and there have been plenty of proposals to add this or other improvements to Python's repertoire. As far as I know, it hasn't happened because it isn't really needed. If you look at C code, at least in my experience the until loop is quite rarely used. (I don't see it once in the source to Python 2.4, for example.) Meanwhile, the while True (or while 1) idiom is very familiar to Python programmers (just as the Python source has dozens of for (;;)), so it's preferred for legibility. It's nice, don't worry. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
OO approach to decision sequence?
OO approach to decision sequence? - In a recent thread (Cause for using objects?), Chris Smith replied with (in part): If your table of photo data has several types of photos, and you find yourself saying if is_mugshot: #something elif is_freehand: #something else: #something then OOP will help organize your code. This struck a chord because I'm trying to refactor a top-down approach to an OO approach. The reason I am doing such is to try and get my mind wrapped around OO design, not because the particular module will benefit from an OO approach (it's a simple top-down recursive tree utility). In fact it's probably ill suited for OO and that is why I chose it. I've used an OO approach where I built up record (instance) content in a variable record file, but here I'm trying to come at it from the opposite direction as variable record mapping (deconstructing) would be to such. Anyway, a tree node can be any of seven types where: if node_type_1: # recurse elif node_type_2: # terminus - do something elif node_type_3: # terminus - do something else ... else: # terminus - catch all, do yet something else return #to parent So, where is the magic :~) Seriously, how might OO help me organize this type of problem (alleviate the conventional lengthy if structure)? I've looked at the cookbook, class interface techniques, factory functions and metaclasses till my head is swimming. Am I missing a bolt in the machinery somewhere, or simply trying to find magic that doesn't exist for a straightforward decision sequence? Thank you, Lee C -- http://mail.python.org/mailman/listinfo/python-list
regarding popen function
Dear All, The following way of popen function usage is wrong or not kindly give me answer regarding this time = os.popen(echo %s | tai64nlocal % line[2]).read() Actually here I didn't use any file handler and I didn't close file handler. regards Prabahar __ Free antispam, antivirus and 1GB to save all your messages Only in Yahoo! Mail: http://in.mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tree functions daily exercise: Table
The Perl version of the Tree function is posted. It's a bit long. Please see the code here: http://xahlee.org/tree/Table.html the choice of having a string as the first argument to Table is a bit awkward in Perl. Possibly i'll have to rewrite it so that the first argument is a function instead, where in each iteration the the variables are fed to the function. This necessarily breaks the Mathematica's syntactical form of Table, and is slightly less flexible in power, but is more natural and practical in non-symbolic languages like Perl, Python, Java. I think the goal of the whole tree functions project http://xahlee.org/tree/tree.html would make the code actually practically useful for processing trees in each language, as opposed to sticking to uniformness of these functions across languages. later on, as we write more tree functions, the whole set will be very useful in processing tree structures, such as XML and many other things spurn from it today. Disclaimer: this project is not affiliated with Wolfram Research Inc. Xah [EMAIL PROTECTED] http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree Namespace Prefixes
Chris Spencer: Fredrik Lundh wrote: Chris Spencer wrote: If an XML parser reads in and then writes out a document without having altered it, then the new document should be the same as the original. says who? Good question. There is no One True Answer even within the XML standards. It all boils down to how you define the same. Which parts of the XML document are meaningful content that needs to be preserved and which ones are mere encoding variations that may be omitted from the internal representation? One can point out the XML namespaces spec all one wants, but it doesn't matter. The fact is that regardless of what that spec says, as you say, Chris, there are too many XML technologies that require prefix retention.As a simple example, XPath and XSLT, W3C specs just like XMLNS, uses qnames in context, which requires prefix retention. Besides all that, prefix retention is generally more user friendly in round-trip or poartial round-trip scenarios. That's why cDomlette, part of 4Suite [1] and Amara [2], a more Pythonic API for this, both support prefix retention by default. [1] http://4suite.org [2] http://uche.ogbuji.net/tech/4Suite/amara/ -- Uche http://copia.ogbuji.net -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On 17 Jun 2005 21:10:37 -0700, Michele Simionato [EMAIL PROTECTED] wrote: Andrea Griffini wrote: Why hinder ? ... To be able to content himself with a shallow knowledge is a useful skill ;) Ah! ... I agree. Currently for example my knowledge of Zope is pretty close to 0.00%, but I'm using it and I'm happy with it. I did what I was asked to do and took way less time than hand-writing the cgi stuff required. Every single time I've to touch those scripts I've to open the Zope book to get the correct method names. But I'd never dare to call myself a zope developer... with it I'm just at the hello world stage even if I accomplished what would require a lot of CGI expertise. But once I remember running in a problem; there was a file of about 80Mb uploaded in the Zope database that I wasn't able to extract. I was simply helpless: download always stopped arount 40Mb without any error message. I wandered on IRC for a day finding only other people that were better than me (that's easy) but not good enough to help me. In the end someone gave me the right suggestion, I just installed a local zope on my pc, copied the database file, extracted the file from the local instance and, don't ask me why, it worked. This very kind of problem solution (just try doing stupid things without understanding until you get something that looks like working) is what I hate *MOST*. That's one reason for which I hate windows installation/maintenance; it's not an exact science, it's more like try and see what happens. With programming that is something that IMO doesn't pay in the long run. I'm sure that someone that really knows Zope would have been able to get that file out in a minute, and may be doing exactly what I did. But knowing why! And this is a big difference. Indeed when talking about if learning C can hinder or help learning C++ I remember thinking that to learn C++ *superficially* learning C first is surely pointless or can even hinder. But to learn C++ deeply (with all its quirks) I think that learning C first helps. So may be this better explain my position; if you wanna become a real programmer, one that really has things under control, then learning a simple assembler first is the main path (ok, may be even a language like C can be a reasonable start, but even in such a low-level language there are already so many things that are easier to understand if you really started from bytes). However, to be able to do just useful stuff with a computer you don't need to start that low; you can start from python (or, why not, even dreamweaver). Andrea -- http://mail.python.org/mailman/listinfo/python-list
Re: Overcoming herpetophobia (or what's up w/ Python scopes)?
Steven D'Aprano wrote: The language is *always* spelt without the a, and usually all in lower-case: perl. The language is title-cased (Perl), but the standard interpreter is written in all lowercase (perl). Sort of like the distinction between Python and CPython. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex for repeated character?
Doug Schwarz wrote: In article [EMAIL PROTECTED], Leif K-Brooks [EMAIL PROTECTED] wrote: How do I make a regular expression which will match the same character repeated one or more times, instead of matching repetitions of any (possibly non-same) characters like .+ does? In other words, I want a pattern like this: re.findall(.+, foo) # not what I want ['foo'] re.findall(something, foo) # what I want ['f', 'oo'] How's this? [x[0] for x in re.findall(r'((.)\2*)', 'abbccccccbba')] ['a', 'bb', 'ccc', '', 'ccc', 'bb', 'a'] I think it's fantastic, but I'd be bound to say that given that it's the same as what I posted almost two days ago :-) -- http://mail.python.org/mailman/listinfo/python-list
functions with unlimeted variable arguments...
how can i define a function with variable parameters? For example, f(a) would return [a] f(a,b) would return [a,b] f(a,b,...) would return [a,b,...] One solution is of course to make the argument as a list. i.e. f([a,b,...]) but are there other solutions? Xah [EMAIL PROTECTED] http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
Your position reminds me of this: http://www.pbm.com/~lindahl/real.programmers.html Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Migrating from Windows to OS X
Hello, fellow programmers! I am sitting in front of a nice new PowerBook portable which has OS 10.4 installed. The Python.org web site says that Apple has shipped OS 10.4 with Python 2.3.5 installed. How exactly do I access this? I have searched through the Applications and Libraries folders. I found the site-packages directory, but nothing other than that. Thanks for your help, John Ladasky -- http://mail.python.org/mailman/listinfo/python-list
Re: OO approach to decision sequence?
I've coded some simple recursive tree data structures using OO before (unfortunately not in Python though). It's not nessecarily an ill-suited approach to the task, although it depends on the specific details of what you're doing. What's the the piece of code from which your if...elif fragment is taken actually supposed to do? Without knowing more about your problem, I think the most obvious OO approach would be to write a seperate (simple) class for each of node_type_1, node_type_2, etc. Make sure each one provides the same interface, i.e. defines the same set of methods. Then put the different decision branches as implementations of a certain method in each class. class Node_Type_1(object): def recurse(self): # do stuff here class Node_Type_2(object): def recurse(self): # do other stuff here only make sure you use more informative names than Node_Type_1 and recurse :) Your if elif code then collapses to: node.recurse() where the node variables refers to an instance of any one of your Node_Type classes. OO isn't magic. You still in the end have to write the code that implements the decision choices. In this example, its likely the OO code is actually more verbose, since you have all the class and method definitions to write as well. But there are advantages. Adding new cases (new node_types) is simpler and less error prone - you just write a new node_type class. The code for the new class, unlike a new elif brach, is kept cleanly and safely seperate from your existing, correctly working code. If you forget to provide the new class with the recurse method, you get a runtime error. But if you forget to add the case to your if..elif statement, you just end up silently going with your sentinel else branch, which may not be what you really want to do with that node_type. (in fact I'd usually raise an exception on reaching the else branch in any such extended if..elif structure, because it's almost always the result of an error in your program logic) Essentially, although you may end up writing more code, its also better organised, since as you wish it avoids your 'conventional lengthy if struture'. Its a partciularily useful approach if you have several different functions that need to branch on node-type in this fashion (e.g. pretty print the tree, post-order traverse it, run a search over it, etc). For each such function, you just provide a method on every node_type class. Again, if you forget to provide the code for a certain node_type, the error is very easy to detect. If your problem is simple, the OO approach may be overkill - your current if..elif code may be the most straightfoward solution. But if the problem is complicated, or has the potential to grow more complicated, the advantages of the OO approach may be a worthwhile trade off. Fortuantely Python is a multi-paradigm language, so the choice to use or not use OO according to what best suits the design and the problem is left up to you, the programmer, and is not thrust upon you by the language. And you certainly don't want metaclasses or anything else that complex and deep for something like this. Chinook wrote: OO approach to decision sequence? - In a recent thread (Cause for using objects?), Chris Smith replied with (in part): If your table of photo data has several types of photos, and you find yourself saying if is_mugshot: #something elif is_freehand: #something else: #something then OOP will help organize your code. This struck a chord because I'm trying to refactor a top-down approach to an OO approach. The reason I am doing such is to try and get my mind wrapped around OO design, not because the particular module will benefit from an OO approach (it's a simple top-down recursive tree utility). In fact it's probably ill suited for OO and that is why I chose it. I've used an OO approach where I built up record (instance) content in a variable record file, but here I'm trying to come at it from the opposite direction as variable record mapping (deconstructing) would be to such. Anyway, a tree node can be any of seven types where: if node_type_1: # recurse elif node_type_2: # terminus - do something elif node_type_3: # terminus - do something else ... else: # terminus - catch all, do yet something else return #to parent So, where is the magic :~) Seriously, how might OO help me organize this type of problem (alleviate the conventional lengthy if structure)? I've looked at the cookbook, class interface techniques, factory functions and metaclasses till my head is swimming. Am I missing a bolt in the machinery somewhere, or simply trying to find magic that doesn't exist for a straightforward decision sequence? Thank you, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib and TLS
Matthias Kluwe [EMAIL PROTECTED] writes: The server accepts and delivers my messages, but the last command raises socket.sslerror: (8, 'EOF occurred in violation of protocol') Did I miss something? Any hint is welcome. Looks like the module didn't send an TLS Close Notify message before closing the socket. I don't see anything in the docs about how to send one from smtplib or socket, though. Hmm. I tried server.sock.realsock.shutdown(2) before server.quit() with the result of SMTPServerDisconnected('Server not connected') being raised. Quite an improvement ... Matthias -- http://mail.python.org/mailman/listinfo/python-list
Re: functions with unlimeted variable arguments...
Xah Lee [EMAIL PROTECTED] writes: but are there other solutions? Xah Geez man, haven't you been around long enough to read the manual? def f(*a): return a -- http://mail.python.org/mailman/listinfo/python-list
Re: Migrating from Windows to OS X
On Sat, 18 Jun 2005 09:26:23 +0200, [EMAIL PROTECTED] wrote (in article [EMAIL PROTECTED]): I am sitting in front of a nice new PowerBook portable which has OS 10.4 installed. The Python.org web site says that Apple has shipped OS 10.4 with Python 2.3.5 installed. How exactly do I access this? I have searched through the Applications and Libraries folders. I found the site-packages directory, but nothing other than that. Launch Terminal (can be found in /Application/Utilities/) type python that's it jem -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
Another thing to keep in mind is that while technically both Python and Java are converted into intermediate byte-codes, which are then interpreted, the Java Virtual Machine runs java bytecode significantly faster. Partly this is because Sun have put a lot of effort into making Java as fast as possible, in an attempt to lure away clockcycle-addicted C programmers; and partly its because having your langugage statically typed makes it easier to do things quickly (for technical reasons that I don't fully understand ;)) So Java has and probably always will have an advantage in the execution speed steaks. That doesnt change the fact that I'd rather code in Python over Java any day of the wek, though :) -- http://mail.python.org/mailman/listinfo/python-list
Re: functions with unlimeted variable arguments...
Xah Lee wrote: how can i define a function with variable parameters? For example, f(a) would return [a] f(a,b) would return [a,b] f(a,b,...) would return [a,b,...] One solution is of course to make the argument as a list. i.e. f([a,b,...]) but are there other solutions? def foo(*args): ... print repr(args) ... return list(args) ... foo() () [] foo(42) (42,) [42] foo(666, 'hello', 1.234) (666, 'hello', 1.234) [666, 'hello', 1.234] -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib and TLS
Matthias Kluwe [EMAIL PROTECTED] writes: Hmm. I tried server.sock.realsock.shutdown(2) before server.quit() with the result of I don't think that's exactly what you want. You need to send a specific TLS message BEFORE shutting down the socket, to tell the other end that the TLS connection is ending. That tells the server that it shouldn't accept a TLS session resumption later. The close notify message is required because if you don't send it, an attacker could truncate one of your TLS messages by cutting your connection. Basically the socket library's SSL implementation is pretty crude. You might try http://trevp.net/tlslite for a pure-Python implementation that's also still missing stuff, but is getting there. -- http://mail.python.org/mailman/listinfo/python-list
Python documentation problem
Python documentation, http://python.org/doc/2.4.1/lib/typesfunctions.html - 2.3.10.3 Functions Function objects are created by function definitions. The only operation on a function object is to call it: func(argument-list). There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types. See the Python Reference Manual for more information. - Fuck the python doc wasted my time. Fuck python coders. Each time i tried to use python doc and got frustrated because it being grossly incompetent, i'll post a message like this, no more frequent than once a week. This will go on as long the python community does nothing to fix it or that i remain coding in python. For reference, see http://xahlee.org/perl-python/re-write_notes.html Xah [EMAIL PROTECTED] http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: OO approach to decision sequence?
Chinook said unto the world upon 18/06/2005 02:17: OO approach to decision sequence? - In a recent thread (Cause for using objects?), Chris Smith replied with (in part): If your table of photo data has several types of photos, and you find yourself saying if is_mugshot: #something elif is_freehand: #something else: #something then OOP will help organize your code. This struck a chord because I'm trying to refactor a top-down approach to an OO approach. The reason I am doing such is to try and get my mind wrapped around OO design, not because the particular module will benefit from an OO approach (it's a simple top-down recursive tree utility). In fact it's probably ill suited for OO and that is why I chose it. I've used an OO approach where I built up record (instance) content in a variable record file, but here I'm trying to come at it from the opposite direction as variable record mapping (deconstructing) would be to such. Anyway, a tree node can be any of seven types where: if node_type_1: # recurse elif node_type_2: # terminus - do something elif node_type_3: # terminus - do something else ... else: # terminus - catch all, do yet something else return #to parent So, where is the magic :~) Seriously, how might OO help me organize this type of problem (alleviate the conventional lengthy if structure)? I've looked at the cookbook, class interface techniques, factory functions and metaclasses till my head is swimming. Am I missing a bolt in the machinery somewhere, or simply trying to find magic that doesn't exist for a straightforward decision sequence? Thank you, Lee C Hi Lee, I'm a hobbyist who came to grok the OO approach in the last 6 months or so ago. So, take the comments with that in mind. A simple toy example with the if type test approach: class A(object): ... pass ... class B(object): ... pass ... a = A() b = B() for item in (a, b): ... if type(item) == A: ... ident = an A ... if type(item) == B: ... ident = a B ... print Found %s %ident ... Found an A Found a B Now, the same sort of behaviour where the if type testing has been replaced with code more in keeping with the OOP approach: class C(object): ... def report(self): ... print Found a C ... class D(object): ... def report(self): ... print Found a D ... c = C() d = D() for item in (c, d): ... item.report() ... Found a C Found a D A metaphorical explanation that is a bit handwavy, but that I find useful: In both approaches, there is a common behaviour you want the various types of objects to exhibit. (In a less 'toy' example the behaviour would be more complicated.) In the if type style, you are asking each object what kind of object it is, and then setting an aspect of the behaviour as a function of the answer. In the more OOP approach, you rely on the fact that each object knows what kind of object it is. So, you don't need to ask it, and adjust the behaviour accordingly. You just tell it to behave, and, knowing what kind of thing it is, it knows how to behave as befits that kind of thing. Two big benefits in the context are that if you need to exhibit the same behaviour in multiple places, you don't have multiple if type chains, and, if you want to add a type, with its own specific behaviour, you just add a class, and there is no worry about hunting down the if type chains to update them. There was a thread on the tutor list around mid-Feb. which really helped me come to understand the idea. Actually, from Dec. to Feb. or so, there are several long tutor threads where people gave me much useful help coming to see how to employ OOP. Might be worth a trip through the archive. HTH, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
Xah Lee wrote: Fuck the python doc wasted my time. Fuck python coders. Use your words! -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis The mind is not a vessel to be filled but a fire to be kindled. -- Plutarch -- http://mail.python.org/mailman/listinfo/python-list
Re: OO approach to decision sequence?
Jordan Rastrick wrote: I've coded some simple recursive tree data structures using OO before (unfortunately not in Python though). It's not nessecarily an ill-suited approach to the task, although it depends on the specific details of what you're doing. What's the the piece of code from which your if...elif fragment is taken actually supposed to do? Without knowing more about your problem, I think the most obvious OO approach would be to write a seperate (simple) class for each of node_type_1, node_type_2, etc. Make sure each one provides the same interface, i.e. defines the same set of methods. Then put the different decision branches as implementations of a certain method in each class. class Node_Type_1(object): def recurse(self): # do stuff here etc etc and perhaps if you found by the time you got to Node_Type_2 that its opensesame() method was identical to the opensesame() method for Node_Type_1, you might decide that having separate simple classes could be improved on by having a Node class, which you would subclass for each Node_Type_n ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Back to the future - python to C++ advice wanted
D H wrote: That's why so many people have switched to Java or C# (or Python and other langugages of course). You might talk to them about using Python, since Python and C/C++ fit together very nicely (with tools like BOOST, SWIG, Pyrex,...). But me personally I like to avoid C++ altogether when possible, and use Java or C# instead, both of which also can be combined with python or python-like languages such as jython, groovy, or boo. But accessing Java packages from jython does not reduce effecively the underlying pain. Personally I favour for programming in C++ over Java, because I feel at least the mind of an evil genius ( C++ template programming is Turing complete, operator overloading enables objects having a builtin groove ) where Java is plain mediocrity. In spirit it is a kind of Anti-Python. I recommend studying C++ idioms carefully. http://www1.bell-labs.com/user/cope/Patterns/C++Idioms/EuroPLoP98.html If Georges starts on greenfields he may have a look at Qt and it's object library which is not only concerned with widgets. http://doc.trolltech.com/3.3/ BOOST is more high brow and I guess that it compiles slow because it uses templates extensively. Template metaprogramming as a compile time language was a funny discovery. Here is some prove of it's capabilities: http://osl.iu.edu/~tveldhui/papers/2003/turing.pdf Regards, Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
i wanted to find out if Python supports eval. e.g. somecode='3+4' print eval(somecode) # prints 7 in the 14 hundred pages of python doc, where am i supposed to find this info? Xah [EMAIL PROTECTED] http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
Xah Lee said unto the world upon 18/06/2005 03:49: Python documentation, http://python.org/doc/2.4.1/lib/typesfunctions.html - 2.3.10.3 Functions Function objects are created by function definitions. The only operation on a function object is to call it: func(argument-list). There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types. See the Python Reference Manual for more information. - Fuck the python doc wasted my time. Fuck python coders. Each time i tried to use python doc and got frustrated because it being grossly incompetent, i'll post a message like this, no more frequent than once a week. This will go on as long the python community does nothing to fix it or that i remain coding in python. For reference, see http://xahlee.org/perl-python/re-write_notes.html Xah [EMAIL PROTECTED] http://xahlee.org/ I'm sure I will regret this in the morning . . . . Xah, since the docs are a community effort, you surely can (and have) pointed to genuine blemishes in them. I am however at a loss to understand just what the perceived problem is here. 5 short sentences, one defining a term, 1 stipulating the interface, two pointing out and clearing up a potential cause of confusion, and a reference. All are clear, and score quite well on the content:words measure to boot. (Certainly it is clearer and more informative than the words either you or I have here added.) What's your complaint? Not enough cursing? Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
Xah Lee said unto the world upon 18/06/2005 04:11: i wanted to find out if Python supports eval. e.g. somecode='3+4' print eval(somecode) # prints 7 in the 14 hundred pages of python doc, where am i supposed to find this info? Xah [EMAIL PROTECTED] http://xahlee.org/ http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-23 which I got to from http://starship.python.net/crew/theller/pyhelp.cgi?keyword=evalversion=current in less time that in took to type this. Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: OO approach to decision sequence?
On Sat, 18 Jun 2005 03:52:28 -0400, Brian van den Broek wrote (in article [EMAIL PROTECTED]): Chinook said unto the world upon 18/06/2005 02:17: OO approach to decision sequence? - In a recent thread (Cause for using objects?), Chris Smith replied with (in part): If your table of photo data has several types of photos, and you find yourself saying if is_mugshot: #something elif is_freehand: #something else: #something then OOP will help organize your code. This struck a chord because I'm trying to refactor a top-down approach to an OO approach. The reason I am doing such is to try and get my mind wrapped around OO design, not because the particular module will benefit from an OO approach (it's a simple top-down recursive tree utility). In fact it's probably ill suited for OO and that is why I chose it. I've used an OO approach where I built up record (instance) content in a variable record file, but here I'm trying to come at it from the opposite direction as variable record mapping (deconstructing) would be to such. Anyway, a tree node can be any of seven types where: if node_type_1: # recurse elif node_type_2: # terminus - do something elif node_type_3: # terminus - do something else ... else: # terminus - catch all, do yet something else return #to parent So, where is the magic :~) Seriously, how might OO help me organize this type of problem (alleviate the conventional lengthy if structure)? I've looked at the cookbook, class interface techniques, factory functions and metaclasses till my head is swimming. Am I missing a bolt in the machinery somewhere, or simply trying to find magic that doesn't exist for a straightforward decision sequence? Thank you, Lee C Hi Lee, I'm a hobbyist who came to grok the OO approach in the last 6 months or so ago. So, take the comments with that in mind. A simple toy example with the if type test approach: class A(object): ... pass ... class B(object): ... pass ... a = A() b = B() for item in (a, b): ... if type(item) == A: ... ident = an A ... if type(item) == B: ... ident = a B ... print Found %s %ident ... Found an A Found a B Now, the same sort of behaviour where the if type testing has been replaced with code more in keeping with the OOP approach: class C(object): ... def report(self): ... print Found a C ... class D(object): ... def report(self): ... print Found a D ... c = C() d = D() for item in (c, d): ... item.report() ... Found a C Found a D A metaphorical explanation that is a bit handwavy, but that I find useful: In both approaches, there is a common behaviour you want the various types of objects to exhibit. (In a less 'toy' example the behaviour would be more complicated.) In the if type style, you are asking each object what kind of object it is, and then setting an aspect of the behaviour as a function of the answer. In the more OOP approach, you rely on the fact that each object knows what kind of object it is. So, you don't need to ask it, and adjust the behaviour accordingly. You just tell it to behave, and, knowing what kind of thing it is, it knows how to behave as befits that kind of thing. Two big benefits in the context are that if you need to exhibit the same behaviour in multiple places, you don't have multiple if type chains, and, if you want to add a type, with its own specific behaviour, you just add a class, and there is no worry about hunting down the if type chains to update them. There was a thread on the tutor list around mid-Feb. which really helped me come to understand the idea. Actually, from Dec. to Feb. or so, there are several long tutor threads where people gave me much useful help coming to see how to employ OOP. Might be worth a trip through the archive. HTH, Brian vdB Thanks for the reply Brian. I understand what you are saying. The point I'm messing up my head with though, is when the entity (tree node in my case or variable record content deconstructing in the aspect example I noted) is not an instance of a class already - it is obtained from an external source and only decipherable by its content. In practical terms that leaves me with some decision sequence regardless and I was wondering (from what Chris Smith said) how that might be done in OOP. The whole problem may be that I'm reading too much into what Chris said :~) I will dig back through the Tutor archives as you suggested. Thanks again, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: regarding popen function
praba kar wrote: The following way of popen function usage is wrong or not kindly give me answer regarding this time = os.popen(echo %s | tai64nlocal % line[2]).read() I don't know, I don't know what tai64nlocal is or what's in line[2]. What happened when you tried it? Personally I try to use the subprocess module rather than os.popen. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Overcoming herpetophobia (or what's up w/ Python scopes)?
On Sat, 18 Jun 2005 04:26:13 +, Dennis Lee Bieber wrote: On Sat, 18 Jun 2005 03:02:13 +1000, Steven D'Aprano [EMAIL PROTECTED] declaimed the following in comp.lang.python: The language is *always* spelt without the a, and usually all in lower-case: perl. Given that, at least one well known, book relates the name to Practical Extraction () Report Language, whether that was a retrofit or not -- I'd be tempted to user PERL for the name... According to Larry Wall, PERL is *officially* wrong and should *never* be used. All lowercase most likely reflects the standard habits of Linux/Unix command naming. And since Larry came from that tradition, you are most likely correct. And that is why originally the official name of the language was all lowercase. Things change, and now Perl is officially the name of the language, and perl officially the name of the implementation of the language. Reading the Perl FAQs at www.perl.org is a good place to start. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Using swig to use an existing dll/library
Hi together, i have a Windows DLL in C that is internally multithreaded and provides a callback function to signal specific events. As I understood one can use normal C-code with swig. Is it also possible to use existing DLLs? Does swig can also handel the callback method? If not - is there another wrapper toolkit that can do that? Thanks, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
Apparently i tried it before posting eval '3' and got misleading errors because i forgot the parenthesis... This is a easy one to find in the doc... The unhelpful doc organization and past experiences confounded this case. Thanks. Xah [EMAIL PROTECTED] http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: exceptions considered harmful
On Fri, 17 Jun 2005 20:00:39 -0400, Roy Smith wrote: H. S. Lahman [EMAIL PROTECTED] wrote: Never throw an exception. And if someone throws one at you, catch it immediately and don't pass it on. IMO, this is generally fine advice. Languages provide exception handlers so that applications have a chance to respond gracefully when the software is in an unstable state. IOW, you should never see an exception unless the software is seriously broken. A corollary is that if the software is corrupted, then even processing the exception becomes high risk. So one should do as little as possible when processing exceptions. (Some languages provide a degree of bullet proofing, but that just make the exception handling facility too expensive to use for routine processing.) This sounds like a very C++ view of the world. In Python, for example, exceptions are much more light weight and perfectly routine. Yes. Furthermore, there is a reason why they are called exceptions and not errors. Exceptions don't necessarily mean something has gone wrong. They can also mean, something has gone right, but it is an exceptional case. For example, Guido recommends using exceptions for handling exceptional cases for command-line tools. Eg, something like this: try: for switch in sys.argv[1:]: if switch in (-h, --help): raise HelpException else: do_something() except HelpException: print __doc__ sys.exit(0) # because asking for help is not an error except: print Program failed! sys.exit(1) # but an error is an error do_main_calculation() sys.exit(0) Or something like this: try: # long slow calculation do_lots_of_work_here() if condition(): # we can jump out of the slow calculation and take a short cut raise QuickException # and more long slow calculation here partial_result = do_lots_more_work_here() except QuickException: # short and easy calculation partial_result = do_quick_calculation() # in either case, we need to do more work here return do_more_work(partial_result) Or even roll-back of processing: try: process_data() # can raise RecoverableError or FatalError except RecoverableError: roll_back() except FatalError: print A fatal error occurred. sys.exit(1) Because Python's handling of try...except is lightweight and fast, this is an idiom which is very practical to use in many situations where it wouldn't be practical in other languages. In conclusion: in Python, it is just not true that you should never see an exception unless the software is seriously broken. It is very bad advice to say that even processing the exception becomes high risk. If the exception genuinely is an error, then it may be difficult to recover, and the best thing you can do is fail gracefully. But that's no reason to not use exceptions. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
Also sprach Xah Lee: i wanted to find out if Python supports eval. e.g. somecode='3+4' print eval(somecode) # prints 7 in the 14 hundred pages of python doc, where am i supposed to find this info? You are not going to find it in comp.lang.perl.misc. Tassilo -- use bigint; $n=71423350343770280161397026330337371139054411854220053437565440; $m=-8,;;$_=$n(0xff)$m,,$_=$m,,print+chr,,while(($m+=8)=200); -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
what is wrong with python doc http://python.org/doc/2.4.1/lib/typesfunctions.html the problem is that the page essentially says nothing. Nothing that is relevant to programing, and such nothingness occupies a significant portion of the python doc. (at least a quarter) It is like reading a manual to operate a machinery, and in every other paragraph it offers the (technically-fantastically-correct) explanations of what bolt or material were used where. the cause of such nothingness situation is because the brainlessness approach to doc organization coupled with standard computer industry geeking moron's need to computer-sciency speak with implementation infatuation. And in part it came to that really because they are comparative morons. for a more sincere, detailed account, please see: http://xahlee.org/perl-python/re-write_notes.html Thanks. Xah [EMAIL PROTECTED] http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pygtk question
RunLevelZero [EMAIL PROTECTED] wrote: Hopefully someone can help me out here. It's probably super simple but how do you select multiple items in a treeview? I have gtk.SELECTION_MULTIPLE set but of course that was enough. It should be enough to do this: treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE) If it doesn't work, try posting a short example so someone can have a look. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
On Sat, 18 Jun 2005 11:49:38 +0200, Xah Lee wrote (in article [EMAIL PROTECTED]): the problem is that the page essentially says nothing. Nothing that is relevant to programing, and such nothingness occupies a significant portion of the python doc. (at least a quarter) It is like reading a manual to operate a machinery, and in every other paragraph it offers the (technically-fantastically-correct) explanations of what bolt or material were used where. I'm new to Python and the information that's in the docs (at least that example) was what I was looking for. I read this as the referece manual, not a cookbook or a tutorial which clearly requires another style of documentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: utf8 and ftplib
Richard Lewis wrote: OK, I've fiddled around a bit more but I still haven't managed to get it to work. I get the fact that its not the FTP operation thats causing the problem so it must be either the xml.minidom.parse() function (and whatever sort of file I give that) or the way that I write my results to output files after I've done my DOM processing. I'll post some more detailed code: def open_file(file_name): ftp = ftplib.FTP(self.host) ftp.login(self.login, self.passwd) content_file = file(file_name, 'w+b') ftp.retrbinary(RETR + self.path, content_file.write) ftp.quit() content_file.close() ## Case 1: #self.document = parse(file_name) ## Case 2: #self.document = parse(codecs.open(file_name, 'r+b', utf-8)) # Case 3: content_file = codecs.open(file_name, 'r', utf-8) self.document = parse(codecs.EncodedFile(content_file, utf-8, utf-8)) content_file.close() In Case1 I get the incorrectly encoded characters. case 1 is the only one where you use the XML parser as it is designed to be used (on the stream level, XML is defined in terms of encoded text, not Unicode characters. the parser will decode things for you) given that he XML tree returned by the parser contains *decoded* Uni- code characters (in Unicode string objects), what makes you so sure that you're getting incorrectly encoded characters from the parser? /F (I wonder why this is so hard for so many people? hardly any programmer has any problem telling the difference between, say, a 32-bit binary floating point value on disk, a floating point object, and the string representation of a float. but replace the float with a Unicode character, and anglocentric programmers immediately resort to poking-with-a-stick-in-the-dark programming. I'll figure it out, some day...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
On Sat, 18 Jun 2005 12:02:07 +0200, Kalle Anke wrote: On Sat, 18 Jun 2005 11:49:38 +0200, Xah Lee wrote (in article [EMAIL PROTECTED]): the problem is that the page essentially says nothing. Nothing that is relevant to programing, and such nothingness occupies a significant portion of the python doc. (at least a quarter) It is like reading a manual to operate a machinery, and in every other paragraph it offers the (technically-fantastically-correct) explanations of what bolt or material were used where. I'm new to Python and the information that's in the docs (at least that example) was what I was looking for. I read this as the referece manual, not a cookbook or a tutorial which clearly requires another style of documentation. At the risk of making an ad hominem attack, Xah Lee's posts usually have all the characteristics of Internet trolling. He unnecessarily cross-posts to multiple newsgroups. He makes sweeping generalizations and inflammatory criticisms based on little understanding. He frequently uses abusive language. He tries to critique Python as an expert, and yet frequently makes silly newbie mistakes or displays ignorance of some very basic Python features. http://en.wikipedia.org/wiki/Internet_troll http://www.teamtechnology.co.uk/troll.htm -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On 18 Jun 2005 00:26:04 -0700, Michele Simionato [EMAIL PROTECTED] wrote: Your position reminds me of this: http://www.pbm.com/~lindahl/real.programmers.html Yeah, but as I said I didn't use a TRS-80, but an Apple ][. But the years were those ;-) Andrea -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
thanks all for the advice. The reason I was thinking about using java (or C or something) was that it is a little more secure than distributing the source code isn't it? And also, from what I know, the Java virtual machine is more popular (and installed on more computers). Although it might take me awhile to get to that stage. once again thanks for your advice. The Dive into Python book looks promising. cpunerd4 -- http://mail.python.org/mailman/listinfo/python-list
MixIn method to call the method it overrides: how?
I have a MixIn class which defines a method foo(), and is then mixed in with another class by being prepended to that class's __bases__ member, thus overriding that class's definition of foo(). In my application though it is necessary for the MixIn's foo() to call the overridden foo(). How can I do this? My current hack is to do this: def foo(): # MixIn's method orig_bases = self.__class__.__bases__ bases = list(orig_bases) bases.remove(OptEdgeCache) self.__class__.__bases__ = tuple(bases) foo_orig = self.foo self.__class__.__bases__ = orig_bases # other stuff here... Is there a better way? Does the above even work as I think it does? -- http://mail.python.org/mailman/listinfo/python-list
Re: functions with unlimeted variable arguments...
Hi All-- Paul Rubin wrote: Xah Lee [EMAIL PROTECTED] writes: but are there other solutions? Xah Geez man, haven't you been around long enough to read the manual? def f(*a): return a He's been around long enough to rewrite the manual. Metta, if-he-succeeds-we'll-all-have-to-take-up-perl-ly y'rs, Ivan -- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours -- http://mail.python.org/mailman/listinfo/python-list
Re: exceptions considered harmful
On Fri, 17 Jun 2005 20:00:39 -0400, Roy Smith [EMAIL PROTECTED] wrote: This sounds like a very C++ view of the world. In Python, for example, exceptions are much more light weight and perfectly routine. The problem with exceptions is coping with partial updatd state. Suppose you call a complex computation routine (say a boolean operation between winged edge data structures representing nurbs boundary of two solids) and that you get back a ZeroDivision exception... how good is the data structure now ? Either you have some way to be able to easily *guarantee* coherence or you're doomed. Allowing the user to continue without being sure about what is in memory is not going to be that helpful; the result could be that instead of losing last ten minuts you're going to waste the last month of user work (because the user will save the corrupted data and will notice problems only much later). If however you can restore the situation by a rollback or by loading a preimage, or you know that the operation works only *reading* two solids and creating a new one *and* you know that it's not a problem to drop a broken solid data structure then I think it's ok to swallow an exception. IMO either you know exactly what caused the exception and how the state got influenced, or you must have thick logical walls protecting you and allowing the problem to not propagate (for example an RDBMS rollback facility). With python it's sort of easy to get rollback for class instances if the code to protect doesn't plays strange tricks. Even C++ is powerful enough to allow that. With C++ care must be taken to just avoid memory leaks or other resource related problem while in python this is rarely a problem; but the real issue with exception is partial state update and in this python is not different. If you really have to check every place for possible exceptions then the exception machinery is not such a big win compared to return codes. IMO exceptions are nice when there are many raise and few try or except in the code; but then either you have state protection or swallowing an exception is taboo. Andrea -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
cpunerd4 ha scritto: thanks all for the advice. The reason I was thinking about using java (or C or something) was that it is a little more secure than distributing the source code isn't it? As in protecting your code from prying eyes? Then java is exactly like python: I can distribute a fully functional python program using only .pyc or .pyo files (unreadable) just as I can distribute only .class files (or jars) in java. And reverse engineering (de-compiling) both is damn easy. The produced code won't be beautiful, sure, but don't rely on it if you want to keep your code secret (for whatever reason). And also, from what I know, the Java virtual machine is more popular (and installed on more computers). And it is also HUGE, so anyone NOT having it will think twice before downloading it only for your app. Python on the other hand is installed by default on all linux and OSX machines, and on windows you can use py2exe and produce packages of 2-3MBs (correct me if I'm wrong) with everything bundled. -- Renato Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org -- http://mail.python.org/mailman/listinfo/python-list
Threading and serial port access
Hi, I'm writing a program which requires the use of three serial ports and one parallel port. My application has a scanning devices on each port, which I can access fine with pyserial. However, I'm unsure of how exactly I should be designing the program, I thought I could use threading to start class: class scanner(Thread): def __init__(self,port): Thread.__init__(self) self.port = port def scan(self): ser = serial.Serial(port) print ser.portstr id = ser.read(12) ser.close But this doesn't work as I thought when I call it like: for port in range(0,totalserialports): # loop through all serial ports print starting thread for port %d %(port) NewThread = scanner(port) NewThread.scan() NewThread.start() I get: starting thread for port 0 /dev/ttyS0 Now, I know that I haven't specified any port timeouts, but I don't want it to timeout, I want to open each port and keep it open indefinately. Threading seems to block waiting for the read from the serial port. How can I open every serial port at the same time, read from it, do an action and then go back to it? Anyone got any good documentation sources for threading that explain things clearly and gives examples? (I'm running python 2.3.4) What's the most python like way of achieving my end goal? Thanks Regards William MacLeod -- http://mail.python.org/mailman/listinfo/python-list
Re: pysqlite - Checking the existance of a table
| I am starting to play with pysqlite, | and would like to know if there is a function | to determine if a table exists or not. rh0dium One way to get at a list of table names in an SQLite data base is to query the sqlite_master table import sys import sqlite this_db = sys.argv[ 1 ] list_sql = [ select tbl_name , from sqlite_master ] str_sql = '\n'.join( list_sql ) dbc = sqlite.connect( db = %s % this_db ) curs = dbc.cursor() curs.execute( str_sql ) list_tables = curs.fetchall() print '\nTable Names in SQLite DB %s \n' % ( this_db ) for table_name in list_tables : print %s % ( table_name ) print dbc.close() -- Stanley C. Kitching Human Being Phoenix, Arizona == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib and TLS
- Original Message - From: Paul Rubin http://phr.cx@NOSPAM.invalid Matthias Kluwe [EMAIL PROTECTED] writes: Hmm. I tried server.sock.realsock.shutdown(2) before server.quit() with the result of I don't think that's exactly what you want. You need to send a specific TLS message BEFORE shutting down the socket, to tell the other end that the TLS connection is ending. That tells the server that it shouldn't accept a TLS session resumption later. The close notify message is required because if you don't send it, an attacker could truncate one of your TLS messages by cutting your connection. Basically the socket library's SSL implementation is pretty crude. You might try http://trevp.net/tlslite for a pure-Python implementation that's also still missing stuff, but is getting there. I have found problems with the TLS built into smtplib when you are doing something with sock elswhere in your app. eg for me using [something].sock.settimeout(x) or setting the default timeout anywhere broke TLS in smtplib. Have you verified that its your end that is broken, not gmail's, do other servers give the same response ?The following servers accept incoming TLS on port 25 e32.co.us.ibm.com mail.donkeyisland.com smtp.myrealbox.com And for quick tests you don't need to send an email (or authenticate), just use a NOOP after STARTTLS (and perhaps a RSET) then QUIT eg server = smtplib.SMTP(hostname [,port]) server.set_debuglevel(1) server.ehlo('x') server.starttls() server.ehlo('x') server.noop() server.rset() server.quit() Trevor's http://trevp.net/tlslite did the job nicely, solving my previous TLS problems (completely untested) from tlslite.api import * server = SMTP_TLS('smtp.gmail.com', 587) server.set_debuglevel(1) server.ehlo() settings = HandshakeSettings() server.starttls(settings=settings) server.ehlo() server.login('[EMAIL PROTECTED]', password) server.sendmail([EMAIL PROTECTED], toaddress, message) server.quit() HTH :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Threading and serial port access
[EMAIL PROTECTED] wrote: Hi, I'm writing a program which requires the use of three serial ports and one parallel port. My application has a scanning devices on each port, which I can access fine with pyserial. However, I'm unsure of how exactly I should be designing the program, I thought I could use threading to start class: class scanner(Thread): def __init__(self,port): Thread.__init__(self) self.port = port def scan(self): ser = serial.Serial(port) print ser.portstr id = ser.read(12) ser.close But this doesn't work as I thought when I call it like: for port in range(0,totalserialports): # loop through all serial ports print starting thread for port %d %(port) NewThread = scanner(port) NewThread.scan() NewThread.start() I get: starting thread for port 0 /dev/ttyS0 Now, I know that I haven't specified any port timeouts, but I don't want it to timeout, I want to open each port and keep it open indefinately. Threading seems to block waiting for the read from the serial port. How can I open every serial port at the same time, read from it, do an action and then go back to it? Anyone got any good documentation sources for threading that explain things clearly and gives examples? (I'm running python 2.3.4) The problem is not your code (as far as I can see that w/o running it), but that you didn't understand the threading API. You have to overload the run-method of a Thread object and then start your thread - which will result in executing the run method in a separate thread. Like this: class Poll(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) self.running = True def run(self): while self.running: # do whatever you want here for t in [Poll() for i in xrange(3)]: t.start() Apart from that the approach you use is wasting resources - if you are concerned about that (or better style...) use e.g. twisted with the serial and parallel support and its so-called select reactor. The idea behind that concept is that the OS is responsible for scannig IO-Ports. It notifies an application about newly arrived data by the system function select - which means that your program sits and waits not cosuming any resources until actual data arrives. See the module select for an overview, and google for python twisted serial. regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
On 2005-06-18, Renato Ramonda [EMAIL PROTECTED] wrote: And also, from what I know, the Java virtual machine is more popular (and installed on more computers). And it is also HUGE, so anyone NOT having it will think twice before downloading it only for your app. Python on the other hand is installed by default on all linux and OSX machines, and on windows you can use py2exe and produce packages of 2-3MBs (correct me if I'm wrong). with everything bundled. That's about right assuming you thrown in a few of the larger libraries like wxWidgets. A Win32 installer for a simple Python app with bundled Python .dll starts at about 750K. Python + py2exe + innoSetup rocks. People have no idea they're running a Python app. The app installs and runs just like any other. -- Grant Edwards grante Yow! I feel like a wet at parking meter on Darvon! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop until condition is true
On 2005-06-18, Peter Otten [EMAIL PROTECTED] wrote: IfyoulookatCcode,atleastinmyexperiencethe until loop is quite rarely used.(Idon'tseeitonceinthesource to Python 2.4, for example.) Long time no C? 'until' in C is actually do statement while (expression); I found 136 occurrences of do { versus 754 of while ( and 1224 of for ( in the Python 2.4 source, so using these rough estimates do-while still qualifies as rarely used. AFAICT, the main use for do/while in C is when you want to define a block of code with local variables as a macro: #define DoSomething(foo) \ do \ { \ int i; \ /* do something with foo and i */ \ } while (0) -- Grant Edwards grante Yow! I HIJACKED a 747 to at get here!! I hope those visi.comfabulous CONEHEADS are at HOME!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
On 2005-06-18, Xah Lee [EMAIL PROTECTED] wrote: [...] Fuck the python doc wasted my time. Fuck python coders. Each time i tried to use python doc and got frustrated because it being grossly incompetent, i'll post a message like this, no more frequent than once a week. This will go on as long the python community does nothing to fix it or that i remain coding in python. I guess it's kind of him to warn everybody who hasn't already plonked him... -- Grant Edwards grante Yow! I'm wet! I'm wild! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
Xah Lee wrote: Python documentation, [...] Python Reference Manual for more information. [...] python doc wasted my time. [...] python coders. [...] use python doc python community [...] coding in python. [Sexual explicatives deleted] And this outburst has exactly _what_ to do with Perl (see list of NGs)? jue -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
Xah Lee wrote: i wanted to find out if Python supports eval. e.g. somecode='3+4' print eval(somecode) # prints 7 in the 14 hundred pages of python doc, where am i supposed to find this info? Why are you asking in a Perl NG for information about Python? Or are you also asking your backer how to trim a steak? jue -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
what is this py2exe thing? I think its what i've been looking for...(and inno setup was in my plans (or maby null soft installer...)). Another reason I was thinging java was because you can run it in the browser. Is py2exe included? Where can I find it? thanks, cpunerd4 -- http://mail.python.org/mailman/listinfo/python-list
Re: pysqlite - Checking the existance of a table
rh0dium wrote: Hi all, I am starting to play with pysqlite, and would like to know if there is a function to determine if a table exists or not. You can try to access the table in a try-catch block, something like: cur.execute(select * from tablename where 1=2) and check if it fails. Or you can query the sqlite_master table (don't know any specification off-hand, but it contains the schema information). Instead of doing a select on sqlite_master, you can use pragma table_info, which returns information for each column in the table, and, apparently, an empty list if the table does not exist: cur.execute(pragma table_info(foo)) print cur.fetchall() [(0, u'bar', u'integer', 0, None, 0)] cur.execute(pragma table_info(foo_does_not_exist)) print cur.fetchall() [] HTH, -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop until condition is true
- Original Message - From: Remi Villatel [EMAIL PROTECTED] There is always a nice way to do things in Python but this time I can't find one. So far, all I got is: while True: some(code) if final_condition is True: break # # What I don't find so nice is to have to build an infinite loop only to break it. If your final_condition is already defined outside the while then how about while not final_condition: some(code) Simplistically, this equates to x = 0 while not x == 5: ... x += 1 ... print x 5 :) -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
On 2005-06-18, cpunerd4 [EMAIL PROTECTED] wrote: what is this py2exe thing? Is py2exe included? Where can I find it? http://www.google.com/search?q=py2exe -- Grant Edwards grante Yow! I just bought at FLATBUSH from MICKEY visi.comMANTLE! -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
On Sat, 18 Jun 2005 15:00:02 +0200, Renato Ramonda wrote: cpunerd4 ha scritto: thanks all for the advice. The reason I was thinking about using java (or C or something) was that it is a little more secure than distributing the source code isn't it? As in protecting your code from prying eyes? Code isn't damaged by prying eyes, so why does it need to be protected? I don't know what cpunerd4 (or whatever she, or he, prefers to be called) means by more secure. But to me, secure means there are no security holes or bugs with security implications in my software. Hiding the source code does not make software more secure. Any bugs and security holes will be there whether the software is distributed in source code, object code, or something in between. Anybody who thinks that hiding the source code makes their programs more secure is in for a rude shock. The basic premise of security by obscurity is that you try to ensure security by hiding certain facts about the software or algorithm from regular users, hoping that nobody will find out what those facts are. This is equivalent to putting an unlocked door in your house, then draping some branches over it, trusting that the burglars won't see the secret door and gain access to your house. Anybody who doesn't understand why keeping source code secret does not increase security should google for security by obscurity. -- Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: MixIn method to call the method it overrides: how?
Something like this will do what you want to achieve. I think the above does as well what you want, but to me my solution is much more clear class Base(object): def foo(self): print 'Base foo' class Derived(Base): def foo(self): super(Derived, self).foo() print 'Derived foo' d = Derived() d.foo() -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
what I mean by secure is that no one can steal the code. I want to create comercial applications eventually. (although I will work on open source I hope, so don't get mad at me) and calling me cpunerd4 will be fine. -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
cpunerd4 ha scritto: Another reason I was thinging java was because you can run it in the browser. Bad idea in 99% of the cases: applets are evil. -- Renato Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
Grant Edwards ha scritto: Python is required and Java is optional and not installed by default in the Linux distros I'm familiar with. I don't know how many Windows systems have Java installed. I don't think any of mine do. It's pretty much the other way round: java CANNOT be included by default in any (free) linux distro for license reasons, and it CANNOT be included by default in Windows as a consequence of court ruling: Microsoft is actually _not allowed_ to include Java. The only system (apart from solaris, I guess) that has a JVM by default is OSX, and it's _NOT_ sun's one, but the internally developed one. -- Renato Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
cpunerd4 wrote: what I mean by secure is that no one can steal the code. I want to create comercial applications eventually. (although I will work on open source I hope, so don't get mad at me) and calling me cpunerd4 will be fine. Commercial applications don't suffer from code-stealing. They might suffer from feature replicating competitors, or from non-paying users. But your code is usual so tied to your actual design approach that it is of no or at least limited use to anyone trying to create his own application. And 98% if not 100% of the code is not actually new or innovative by itself. The only part of an app that might be of interest for others is something like a new algorithm - e.g. a videodecoder. But if it _is_ interesting, it can and will be reverse engineered - even if written in pure assembly. The only way to protect it is not to release it at all - by using a RPC mechansim like CORBA or XMLRPC to access it. So - the bottomline is - don't worry about releasing the code too much. The question of FOSS or commercial is a license thing - the hindrance is of legal nature, not technical. Diez -- http://mail.python.org/mailman/listinfo/python-list
Localization in OSX
Hi, I have a problem with L10N of an app, I'm unable to retrieve default language in mac while this works for both Linux and Windows: LOCALE=locale.getdefaultlocale() Where can I find default system settings with mac? -- dariosky http://dariosky.altervista.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
On 2005-06-18, cpunerd4 [EMAIL PROTECTED] wrote: what I mean by secure is that no one can steal the code. Distributing bytecode (Java or Python) vs. source only makes little difference if your code is really worth stealing. Distributing compiled C code will make it a little more difficult, but if somebody wants to reverse engineer it, they can. I want to create comercial applications eventually. Most commercial applications are stolen simply by copying the executable. -- Grant Edwards grante Yow! Either CONFESS now or at we go to PEOPLE'S COURT!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
even so, crackers have a harder time getting into compiled programs rather than intepreted languages. I know hiding the code won't stop all crackers but it will stop some of the casual theifs won't it? It's not so much that they could steal code, it's that they could alter it and release it somewere else and make their own money off it. cpunerd4 -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop until condition is true
Quoth Peter Otten [EMAIL PROTECTED]: ... | 'until' in C is actually | | do | statement | while (expression); Oops. Well, QED - I sure don't need it often. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
by the way, you guys have talked me out of java. Im thinking about this py2exe thing. (anyother suggestions) I like this list. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop until condition is true
On Sat, 18 Jun 2005 13:35:16 -, Grant Edwards [EMAIL PROTECTED] wrote: AFAICT, the main use for do/while in C is when you want to define a block of code with local variables as a macro: When my job was squeezing most out of the CPU (videogame industry) I remember that the asm code generated by while (sz-- 0) { /* do some stuff */ } was indeed worse than do { /* do some stuff */ } while (--sz); because of the initial empty-loop test (conditional jumps were bad, and forward conditional jumps were worse). So where at least one iteration was guaranteed the do-while loop was a better choice. Also I've been told there were compilers that if using for or while loops the generated code was initialize L1: evaluate condition je L2 body jmp L1 L2: Instead the do-while loop would have been L1: body evaluate condition jne L1 I.e. the code was better *for each iteration* (one conditional jump instead of one conditional jump and one inconditional jump). I think compiler got better since then, even if I don't think they already so smart to be able to infer the one interation guaranteed property to avoid the initial test that often. Andrea -- http://mail.python.org/mailman/listinfo/python-list
Re: Migrating from Windows to OS X
Kalle Anke wrote: On Sat, 18 Jun 2005 09:26:23 +0200, [EMAIL PROTECTED] wrote (in article [EMAIL PROTECTED]): I am sitting in front of a nice new PowerBook portable which has OS 10.4 installed. The Python.org web site says that Apple has shipped OS 10.4 with Python 2.3.5 installed. How exactly do I access this? I have searched through the Applications and Libraries folders. I found the site-packages directory, but nothing other than that. Launch Terminal (can be found in /Application/Utilities/) type python that's it O.K., I found it... thanks! I haven't been down to the UNIX prompt on the Mac before. How are the development tools for the Mac? I'll use IDLE if it's available, but I like Scintilla better. Repeating my thanks, John Ladasky -- http://mail.python.org/mailman/listinfo/python-list
Re: Migrating from Windows to OS X
[EMAIL PROTECTED] wrote: Hello, fellow programmers! I am sitting in front of a nice new PowerBook portable which has OS 10.4 installed. The Python.org web site says that Apple has shipped OS 10.4 with Python 2.3.5 installed. How exactly do I access this? I have searched through the Applications and Libraries folders. I found the site-packages directory, but nothing other than that. Thanks for your help, John Ladasky If I recall correctly, the actual Python installation is in /System/Library/Frameworks/Python.framework but the site-package is symlinked to /Library/Python. Do not attempt to touch that. This installation can be accessed in Terminal by typing pythonw. Are you or will you be using package managers such as darwinports or Fink? maurice -- http://mail.python.org/mailman/listinfo/python-list
Re: Python documentation problem
In comp.lang.perl.misc Xah Lee [EMAIL PROTECTED] wrote: i wanted to find out if Python supports eval. e.g. somecode='3+4' print eval(somecode) # prints 7 in the 14 hundred pages of python doc, where am i supposed to find this info? By using the index - it's an alphabetical list of names and topics. Follow-ups set. Axel -- http://mail.python.org/mailman/listinfo/python-list
Re: Migrating from Windows to OS X
On Sat, 18 Jun 2005 17:07:04 +0200, [EMAIL PROTECTED] wrote (in article [EMAIL PROTECTED]): How are the development tools for the Mac? I'll use IDLE if it's available, but I like Scintilla better. Don't know ... I think that MacPython is perhaps what you're looking for. Personally, I use BBEdit jem -- http://mail.python.org/mailman/listinfo/python-list
Static (why?) PyDateTimeAPI and SIP
I use datetime C API in extension module generated with SIP. But SIP break the code into several .cpp files compiled separately and PyDateTimeAPI used by all macros constituting public interface is declared static. The current solution is to define my own functions in main module as workaround: %ModuleHeaderCode PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int seconds, int usecs); %End %ModuleCode PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int seconds, int usecs) { return PyDateTime_FromDateAndTime(year, month, day, hour, minute, seconds, usecs); } // and so on for each macro used %End %PostInitialisationCode PyDateTime_IMPORT; %End But I wonder why PyDateTimeAPI is declared static, and is the a better solution? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: Set of Dictionary
[Vibha] I know sets have been implemented using dictionary but I absolutely need to have a set of dictionaries...any ideas how to do that? Yes. Create a dictionary subclass that is hashable. Be sure not to mutate it after using it in a set. class FrozenDict(dict): def __hash__(self): try: return self._hash except AttributeError: self._hash = hash(tuple(sorted(self.iteritems( return self._hash d1 = FrozenDict(a=1, b=2, c=3) d2 = FrozenDict(d=4, e=5, f=6) d3 = FrozenDict(b=2, c=3, a=1) s = set([d1, d2, d3]) s set([{'e': 5, 'd': 4, 'f': 6}, {'a': 1, 'c': 3, 'b': 2}]) d2 in s True Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
cpunerd4 wrote: even so, crackers have a harder time getting into compiled programs rather than intepreted languages. I know hiding the code won't stop all crackers but it will stop some of the casual theifs won't it? It's not so much that they could steal code, it's that they could alter it and release it somewere else and make their own money off it. Roughly speaking, if your code is so valuable, there's very little you can do to stop if from being used in this way, except for keeping it inside a secured network appliance which prevents all access (though even then the box itself can be stolen, so you have to allow access only through the internet in that case). Furthermore, protecting you from someone else making money off a copy of your program is basically what licenses are for, and if you have noticed they don't protect even Microsoft (see, for example, entire governments like the Indonesian government, which has mass-pirated Microsoft software for a long time). On the other hand, while a license isn't a guarantee of much, it does make it easier to go after violators in a court and sue them for damages. And if you think your software is really worth the efforts you are envisioning to protect it, you should be prepared to go after people in court when they violate your license, not trying to prevent them from copying it in the first place (which is basically impossible, except see my first point again ;-). My main suggestion to you is this. Many people with several decades more experience than you used to feel exactly as you do (I did!), and have now, after years of developing and selling commercial software, changed their view of the whole issue drastically. Learn from others' mistakes and don't waste your time worrying about this stealing code thing... put your efforts into developing really useful, valuable software, and the world will beat a path to your door to give you money (see Google, for example), and while a few people might be trying to profit from your efforts without your permission, you'll either be in a good position to ignore them or sue them, as you will -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Unbound names in __del__
Torsten Bronger wrote: Peter Hansen [EMAIL PROTECTED] writes: What's your use case for del? Every instance represents a session to a measurement instrument. After the instance is deleted, the session should be closed to free resources. You mean like GPIB devices? We've written a lot of software that talks to instruments, as well as pumps, motors, and sensors of all kinds. I haven't even needed to free resources, other than by closing a serial port, for example. Such simple operations don't require the use of __del__ and can easily be done with simple .close() type calls as the application shuts itself down or finishes a test sequence or other operation. Use of __del__ is, in my opinion, a bit of a crutch (meaning it seems to make life easier, but then you start relying on it and find it hard to do without). Given that it isn't really reliable in non-trivial situations, I'd recommend pretending __del__ does not exist and restructuring your system to close these sessions explicitly, under your direct control, at the appropriate point. This has worked very well for us so far. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: thread.start_new_thread question
Konstantin Veretennicov wrote: Thank you, but that doesn't answer my question. I was asking if there is a reason that args is not optional. At the risk of increasing your frustration, I'm going avoid answering your question as well and simply point out that if you use the threading module, as is recommended, you won't have to deal with this issue at all, and your code will generally be simpler. (To answer your real question I'd have to check the docs for thread and, since I _never_ use that module in spite of heavy use of threading, I can't help you more... sorry.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How should threads be terminated? (related to 'Help with thread related tracebacks')
Maxwell Hammer wrote: On Thu, 16 Jun 2005 16:20:23 -0400, Peter Hansen wrote: If the question was well formulated, and it's been more than a couple of days, you should consider reposting. It's very unusual for a post with such a subject (if it was a clear question) to get _no_ feedback around here. Fair enough. The question is not expressed clearly for others. Do you have any suggestions as to how to describe the problem clearer? I hope you didn't get the impression I was criticizing. I don't recall your post at all, and definitely wasn't suggesting that it was unclear, merely asking you to verify that it was and, if not, rewrite it upon reposting. As for suggestions to make it clearer: I can't make any without digging back for your previous posting. I generally don't take the time to do that since older messages are often gone from my server very quickly, and I don't like spending time digging around on Google Groups to find it. Sorry, it's just one of my approaches to conserving my own time, selfishly. I can think of no other way but to say I have an app that when I terminate it, completes ok, However the last thing that happens before the shell prompt returns is that there is a traceback *within* python. (The actual post goes into more details of course.) This sounds very much like the problem where, during the interpreter shutdown, all globals in all modules are rebound to None, but if daemon threads are still running they will quickly crash as a result and raise exceptions, usually referring to AttributeErrors where None doesn't have an attribute of a particular kind, usually the name of a method. If I'd seen your post, I would probably have responded with as much at the time. If you do a Google Groups search for some of those keywords and my name, you'll certainly find a half dozen other threads where someone else asked a similar question, even if I missed your post. I just took a guess that it is *thread* related from the output of the traceback. I'm still learning python, so how could one pose the problem *clearer*? And thanks for the feedback regarding threads, by the way. No problem. And if this post didn't help, please do repost the whole original question so I can see it again, and those who read the group via the mailing list will get a fresh email, etc... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Shortcut to initialize variables
Andrew wrote: I'm writing a program that will take substitution and transposition cipher texts and spit out plain text with no human input. So I suppose I'll have dictionaries of digraphs and trigraphs too; for frequency analysis. Do you think this is to heavy of a project to learn the language? Not at all, provided you're somewhat expert in the domain already, and are just using it as a means to help learn Python. If you are learning both Python and how to break ciphers at the same time, I'd personally call it a little heavy... ;-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
I see your point, although I don't think there is much a 14 year old can do to sue someone. . . I'm sure my code won't be that valuable untill I'm older though. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: case/switch statement?
D H wrote: Peter Hansen wrote: [some stuff Doug didn't like] I don't think you could have misread my simple suggestion to you any more completely than you did. Sorry, I'll try harder next time. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: regarding popen function
praba kar wrote: The following way of popen function usage is wrong or not kindly give me answer regarding this time = os.popen(echo %s | tai64nlocal % line[2]).read() Did you try it? Just open the Python interactive interpreter and see what happens: Python 2.3.4 (#1, Feb 2 2005, 12:11:53) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 import os line = ['', '', '@400042b40a8716ebce34'] time = os.popen('echo %s | tai64nlocal' % line[2]).read() time '2005-06-18 07:50:21.384552500\n' Or were you just asking if it was an appropriate way of using os.popen()? If that's what you were asking, it would have been much clearer not to include the command itself, since clearly it just confuses people about what you are asking. Yes, it's an appropriate way to use popen(), and it does seem to work if you have tai64nlocal in your path. (Michael, tai64nlocal is a program that converts a special packed timestamp to human-readable form. These timestamps are created, as I recall, by the multilog program that the developer of Qmail created.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
D H wrote: Peter Hansen wrote: With respect to the author, and an understanding that there is probably much that didn't go into his self-description (add about.htm to the above URL), it sounds as though he knows primarily, perhaps solely, C and C++, and has done relatively little serious development since he seems to have spent most of his time either teaching or writing (words, not source code). Does he even *know* any real high level languages such as Python? So you say he has done relatively little serious development and that he may not even know about Python. I didn't see any evidence from those pages to draw either conclusion. In fact the 4th paragraph quite contradicts them both. Clearly this is a matter of opinion. Now that you've expressed yours, did you have a point to make besides that you like to contradict my posts? Maybe you'd like to take the opportunity to mention Boo? -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Concurrence 0.0.5.2 Alpha
On 6/17/05, Daniel Bickett [EMAIL PROTECTED] wrote: Concurrence is a networked file editing program that enables multiple people to modify a document simultaneously. It is written entirely in python, and uses the wxPython library for the GUI and the Twisted library for networking. This marks the release of Concurrence 0.0.5.2 Alpha, and it can be found at the following link: http://sourceforge.net/projects/concurrence/ It has been in development for just under three weeks now, and for it's age it has quite a large feature set, including: * All modifications that occur in every client are sent to the server (then to the other clients) real time and on a first-come, first-serve basis * The lines on which the carets of the other users in a given file rest are highlighted * A chat feature is included in each document window to eliminate the necessity of a third party messenger client, while improving the coordination of document editing * All of the features expected of one's day-to-day text editor have been implemented * Python files are automatically detected and the syntax is highlighted (in the near future this feature may be toggled at will) The project can be discussed on the #concurrence channel at irc.freenode.net, or on the mailing list [EMAIL PROTECTED] -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ __ Yahoo! Mail Stay connected, organized, and protected. Take the tour: http://tour.mail.yahoo.com/mailtour.html -- http://mail.python.org/mailman/listinfo/python-list
Re: pysqlite - Checking the existance of a table
Gerhard Hring wrote: Or you can query the sqlite_master table (don't know any specification off-hand, but it contains the schema information). Item #9 in the FAQ (http://www.sqlite.org/faq.html#q9) shows it as: CREATE TABLE sqlite_master ( type TEXT, name TEXT, tbl_name TEXT, rootpage INTEGER, sql TEXT ); -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Unbound names in __del__
Hallchen! Peter Hansen [EMAIL PROTECTED] writes: Torsten Bronger wrote: keithley = GpibInstrument(14) keithley.write(*IDN?) print keithley.read() A keithley.close() would be a wart in my opinion; instead I want to hide the whole session thing from the programmer. Besides, I haven't yet given up the hope that the issues with __del__ can be tackled. At least one alternative comes to mind. Have the GpibInstrument class (or its module) register an atexit() method, and have the constructor for that class track all instances. On shutdown, the atexit method goes through all instruments that are still open and issues the .close() requests, or whatever you do in the __del__ now. However, this doesn't close sessions while the program is running. If the programmer has the above code in a function which is called repeatedly, he may run into trouble. IIRC my current VISA DLL has only 256 session slots. Tsch, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list
Re: [PyKDE] Static (why?) PyDateTimeAPI and SIP
On Sat, 18 Jun 2005 19:52:20 +0400 Denis S. Otkidach [EMAIL PROTECTED] wrote: I use datetime C API in extension module generated with SIP. But SIP break the code into several .cpp files compiled separately and PyDateTimeAPI used by all macros constituting public interface is declared static. The current solution is to define my own functions in main module as workaround: %ModuleHeaderCode PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int seconds, int usecs); %End %ModuleCode PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int seconds, int usecs) { return PyDateTime_FromDateAndTime(year, month, day, hour, minute, seconds, usecs); } // and so on for each macro used %End %PostInitialisationCode PyDateTime_IMPORT; %End But I wonder why PyDateTimeAPI is declared static, and is the a better solution? To prevent namespace pollution. Numeric and numarray have a different solution. From Numeric/arrayobject.h: /* C API address pointer */ #if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY) extern void **PyArray_API; #else #if defined(PY_ARRAY_UNIQUE_SYMBOL) void **PyArray_API; #else static void **PyArray_API; #endif which lets you use whatever you like and even rename the C API address pointer. However, keep in mind that SIP can concatenate all C++ files which breaks clever #defines that work if SIP generates separate C++ source files. In fact, I use your method, when wrapping the Numeric and numarray files for PyQwt. The only difference is that I put all access to the C-API in handwritten C++ files to use the conflicting APIs of Numeric and numarray in the same Python extension. Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
On Sat, 18 Jun 2005 12:05:59 -0400, Peter Hansen wrote: Furthermore, protecting you from someone else making money off a copy of your program is basically what licenses are for, and if you have noticed they don't protect even Microsoft (see, for example, entire governments like the Indonesian government, which has mass-pirated Microsoft software for a long time). Please call it what it is: copyright infringement, not piracy. Piracy takes place in international waters, and involves one or more of theft, murder, rape and kidnapping. Making an unauthorized copy of a piece of software is not piracy, it is an infringement of a government-granted monopoly. In any case, there is a powerful argument for wanna-be Microsofts to turn a blind eye to copyright infringements. It worked for Microsoft and almost every other successful software company. The biggest barrier to success for software developers is getting people to even know your software exists. The second biggest barrier is encouraging them to try your software. The third is getting them to keep using your software once they've tried it. Actually collecting money from them is at the bottom of the list -- you can't expect people to pay you for using your software if they don't even know you exist. Apart from the occasional public rant (such as Bill Gates' plea to users not to make illegal copies of MS BASIC), in the early days Microsoft didn't go out of their way to chase copyright infringers. If they had, the users would have simply stopped using the MS software and used something else. Instead, people grabbed copies of Word or Excel from their friends, taking market share from WordPerfect, WordStar, Lotus etc. Eventually, they would need an upgrade, or find it more convenient to buy than to copy. Every so-called pirated copy had (at least) four benefits to Microsoft: it denied a sale to Microsoft's competitors; it increased users' familiarity and confidence with Microsoft's products; it built Microsoft's brand recognition among software purchasers and IT departments; and it was (usually) a future sale to Microsoft. It was only as Microsoft approached monopoly status that copyright infringement began to hurt them more than it gained them. With few if any competitors, the loss of revenue from unauthorized copies of Word or Excel or Windows became greater than the benefits. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
the problem is that i don't even know the language yet. . . -- http://mail.python.org/mailman/listinfo/python-list
Re: What makes an object uncopyable?
On 17 Jun 2005 15:41:07 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I am trying to make a copy of a certain Python object using the copy.copy() function. When I try to perform this operation I get an error like the following: copy.Error: un(shallow)copyable object of type ... What factors determine whether an object can be copied? You are probably trying to copy an instance of a class implemented in C extension. AFAIK, Python classes have copy support by default, but extension classes need to implement copy/pickle protocol. - kv -- http://mail.python.org/mailman/listinfo/python-list
Re: OO approach to decision sequence?
On Sat, 18 Jun 2005 09:10:25 -0400, George Sakkis wrote (in article [EMAIL PROTECTED]): Chinook wrote: I understand what you are saying. The point I'm messing up my head with though, is when the entity (tree node in my case or variable record content deconstructing in the aspect example I noted) is not an instance of a class already - it is obtained from an external source and only decipherable by its content. In practical terms that leaves me with some decision sequence regardless and I was wondering (from what Chris Smith said) how that might be done in OOP. The whole problem may be that I'm reading too much into what Chris said :~) I will dig back through the Tutor archives as you suggested. What you are looking for is what is called the 'factory method pattern' (http://en.wikipedia.org/wiki/Factory_method_pattern) and it's one of the cases where OOP doesn't eliminate the if/elif/elif (or switch in C++/Java). That's ok though because, as you noticed, at some point you have to take a decision. What's important is the once and only once principle, that is all the decision logic is encapsulated in a single method (or in python in a single function) instead of being replicated every time you want to use an existing Node. Regards, George George, Yes, that answers my question of how the issue is approached in OOP - thank you. I'll do some more googling to find examples in Python and then try refactoring my little utility. The effect on my little utility will be a verbose abstraction of a specific efficient top-down approach, but the intended goal is to learn how to better facilitate extensibility. Thanks to all that took the time to wade through my post and especially to those that offered their thoughts, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: Unbound names in __del__
Peter Hansen [EMAIL PROTECTED] writes on Fri, 17 Jun 2005 08:43:26 -0400: ... And I don't recall the last time I saw a __del__ in third-party code I was examining. What's your use case for del? I had to use one a few days ago: To call the unlink method of a minidom object when its container is destroyed. It would have been possible to let the cyclic garbage collector find and eliminate the cyclic minidom objects. But, DOMs may be large and I create lots of them in a short time (each in its own container)... Dieter -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
So true. Am I the only one who wonders this: If Python at runtime runs very much like Java and has generally about the same speed (or faster) rofl -- http://mail.python.org/mailman/listinfo/python-list
Re: Unbound names in __del__
Torsten Bronger wrote: Torsten Bronger wrote: keithley = GpibInstrument(14) keithley.write(*IDN?) print keithley.read() [on using atexit] However, this doesn't close sessions while the program is running. If the programmer has the above code in a function which is called repeatedly, he may run into trouble. IIRC my current VISA DLL has only 256 session slots. Hmm... it sounds to me as though the design of this DLL is such that one is expected to hold a session open for the duration of the application. So instead of creating new GpibInstrument objects as needed, then just sort of dropping them, the programmers would have to create the required instrument objects at the start of the program and reuse them when needed. But that's as far as my thoughts take me on this, without working directly with you. I guess you'll have to explore the __del__ approach through to its conclusion before you'll be confident it won't work (or perhaps you'll find a solution after all!). -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
On Sat, 18 Jun 2005 14:00:35 -0400, Steven D'Aprano wrote (in article [EMAIL PROTECTED]): On Sat, 18 Jun 2005 12:05:59 -0400, Peter Hansen wrote: Furthermore, protecting you from someone else making money off a copy of your program is basically what licenses are for, and if you have noticed they don't protect even Microsoft (see, for example, entire governments like the Indonesian government, which has mass-pirated Microsoft software for a long time). Please call it what it is: copyright infringement, not piracy. Piracy takes place in international waters, and involves one or more of theft, murder, rape and kidnapping. Making an unauthorized copy of a piece of software is not piracy, it is an infringement of a government-granted monopoly. In any case, there is a powerful argument for wanna-be Microsofts to turn a blind eye to copyright infringements. It worked for Microsoft and almost every other successful software company. The biggest barrier to success for software developers is getting people to even know your software exists. The second biggest barrier is encouraging them to try your software. The third is getting them to keep using your software once they've tried it. Actually collecting money from them is at the bottom of the list -- you can't expect people to pay you for using your software if they don't even know you exist. Apart from the occasional public rant (such as Bill Gates' plea to users not to make illegal copies of MS BASIC), in the early days Microsoft didn't go out of their way to chase copyright infringers. If they had, the users would have simply stopped using the MS software and used something else. Instead, people grabbed copies of Word or Excel from their friends, taking market share from WordPerfect, WordStar, Lotus etc. Eventually, they would need an upgrade, or find it more convenient to buy than to copy. Every so-called pirated copy had (at least) four benefits to Microsoft: it denied a sale to Microsoft's competitors; it increased users' familiarity and confidence with Microsoft's products; it built Microsoft's brand recognition among software purchasers and IT departments; and it was (usually) a future sale to Microsoft. It was only as Microsoft approached monopoly status that copyright infringement began to hurt them more than it gained them. With few if any competitors, the loss of revenue from unauthorized copies of Word or Excel or Windows became greater than the benefits. Steven, Your weigh-in on semantics is misleading, but your elaboration of the aspect is very well put. As to semantics, piracy is to the originator what freedom fighter is to those that perceive themselves as oppressed. On the other hand, your elaboration is a very good example of the altered consciousness of human nature. That is, the acceptance of shades of complicity divorced from shades of guilt. Of course, one can see (if they so chose) many more obvious examples in business, let alone government and religion :~) Lee C -- http://mail.python.org/mailman/listinfo/python-list
oddness in super()
Ok, this works in Python on Windows, but here on Linux, with Python 2.4.1, I'm getting an error. The docs say: A typical use for calling a cooperative superclass method is: class C(B): def meth(self, arg): super(C, self).meth(arg) However, when I try this, which works on windows, with ActiveState ActivePython 2.4.0... class RemGuiFrame(RemGlade.RemFrame): This class is the top-level frame for the application. def __init__(self, *args, **kwds): Class constructor. # Constructor chaining super(RemGuiFrame, self).__init__(*args, **kwds) ...on linux I get this... [EMAIL PROTECTED] pysrc]$ ./RemGui.py Traceback (most recent call last): File ./RemGui.py, line 206, in ? frame_1 = RemGuiFrame(None, -1, ) File ./RemGui.py, line 30, in __init__ super(RemGuiFrame, self).__init__(*args, **kwds) TypeError: super() argument 1 must be type, not classobj Why the difference? Is Python portability overrated? Is this a bug? I'm confused. Mike -- Michael P. Soulier [EMAIL PROTECTED] http://www.digitaltorque.ca http://opag.ca python -c 'import this' Jabber: [EMAIL PROTECTED] signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
Grant Edwards [EMAIL PROTECTED] wrote: I've guessed that python is purely an interpreted language unless its compiled into another language (ie. it needs python installed in order to run programs). Is this correct? It's just like Java. It's compiled into bytecode and then the bytecode is executed on a virtual machine. Keep in mind that all modern JVMs just-in-time compile Java bytecode to native code. It looks something like this: Java source - Java bytecode - Java virtual machine - Native code So, in the end, users are typically running natively compiled code. (Warning: This is a simplification, but this description seems adequate for the OP.) Java typically outperforms Python by a very wide margin. -- http://mail.python.org/mailman/listinfo/python-list