Guaranteed to Run - Python Bootcamp, March 16-20, 2009 May 11-15, 2009
The Open Technology Group is pleased to announce two Guaranteed to Run* Python Bootcamp's, scheduled : . March 16-20, 2009 May 11-15, 2009 OTG's Python Bootcamp is a 5 day intensive course that teaches programmers how to design, develop, and debug applications using the Python programming language. Over a 5 day period, through a set of lectures, demonstrations, and hands-on exercises students will learn how to develop powerful applications using Python and integrate their new found Python skills in their day-to-day job activities. Students will also learn how to utilize Python's Database API and the psycopg2 drivers to interface with the PostgreSQL Object-Relational database. Our course is guaranteed to run, regardless of enrollment, and available in an all inclusive package that includes round-trip airfare, 5 nights of hotel accommodation, shuttle services (to/from the airport, to/from our facility, and to/from local eateries/shopping), and our training. All-inclusive packages are priced at $2,495 for the 5 day course. For more a complete course outline/syllabus, or to enroll, visit our web site at: http://www.otg-nc.com/python-bootcamp Affordable, customizable, on-site training is available (and cost effective) for groups of 3 or more students. For more information - or to schedule an on-site course, please contact us at 877-258-8987 . The Open Technology Group is the world leader in the development and delivery of training solutions focused around Open Source technologies. * Guaranteed to Run courses are guaranteed to run, so long as a single student is enrolled in the course. -- Chander Ganesan Open Technology Group, Inc. One Copley Parkway, Suite 210 Morrisville, NC 27560 919-463-0999/877-258-8987 http://www.otg-nc.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
OSCON 2009: Call For Participation
The O'Reilly Open Source Convention has opened up the Call For Participation -- deadline for proposals is Tuesday Feb 3. OSCON will be held July 20-24 in San Jose, California. For more information, see http://conferences.oreilly.com/oscon http://en.oreilly.com/oscon2009/public/cfp/57 -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
How to deepcopy a list of user defined lists?
Hi, I have a class which is a subclass of builtin-type list. #-- class clist(list): def __new__(cls, values, ctor): val = [] for item in values: item = ctor(item) val.append(item) self = list.__new__(cls, val) self.__values = val self.__ctor = ctor return self #--- I have a list of clists, say c1 = [clist1, clist2, clist3] How do i deepcopy this list? I tried using copy.deepcopy() method. But i got some errors. Please suggest me. Thanks, Srini Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to deepcopy a list of user defined lists?
On Wed, Jan 7, 2009 at 11:59 PM, srinivasan srinivas sri_anna...@yahoo.co.in wrote: Hi, I have a class which is a subclass of builtin-type list. #-- class clist(list): def __new__(cls, values, ctor): val = [] for item in values: item = ctor(item) val.append(item) self = list.__new__(cls, val) self.__values = val self.__ctor = ctor return self #--- I have a list of clists, say c1 = [clist1, clist2, clist3] How do i deepcopy this list? I tried using copy.deepcopy() method. But i got some errors. Please suggest me. And those errors are? Please include a full Traceback. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
RE: listdir reports [Error 1006] The volume for a file has been externally altered so that the opened file is no longer valid
FYI: the '/*.*' is part of the error message returned. -Original Message- From: ch...@rebertia.com [mailto:ch...@rebertia.com] On Behalf Of Chris Rebert Sent: Wednesday, January 07, 2009 6:40 PM To: Per Olav Kroka Cc: python-list@python.org Subject: Re: listdir reports [Error 1006] The volume for a file has been externally altered so that the opened file is no longer valid PS: Why does the listdir() function add '*.*' to the path? Don't know what you're talking about. It doesn't do any globbing or add *.* to the path. Its exclusive purpose is to list the contents of a directory, so /in a sense/ it does add *.*, but then not adding *.* would make the function completely useless given its purpose. PS2: Why does the listdir() function add '/*.*' to the path on windows and not '\\*.*' ? You can use either directory separator (\ or /) with the Python APIs on Windows. rc:\WINDOWS\ works just as well as c:/WINDOWS/. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
On Wed, 07 Jan 2009 03:45:00 -0800, sturlamolden wrote: On Jan 7, 2:02 am, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: In Python code, there are no references and no dereferencing. The why does CPython keep track of reference counts? Two different levels of explanation. At the level of Python code, you don't see reference counts. You never manipulate reference counts directly. The gc module does expose them, if you want to see them, but the gc module deliberately peaks behind the curtains. It's special. At the implementation level, CPython uses references so it needs reference counts. Jython doesn't keep reference counts at all, because it uses Java's garbage collection (or so I understand). And the hypothetical Distributed Python uses clones of objects and a daemon which keeps them in sync, and hence there are no reference counts because each clone is attached once and once only. You can't, because Python doesn't have references. In a language with references, that's easy. Python does not 'pass-by-reference' as Fortran or Pascal do. That's right. But sadly, if you tell people that Python uses references, many people will say How do I pass a reference to this object to a function?. a = 123456789 b = [a] c = [a] d = [a, a] b[0] is a True c[0] is a True d[0] is a True d[1] is a True Where is the object 'a' stored? Somewhere in memory, floating free, where it is referred to under the name 'a'. In CPython, it will be in the heap, unless it has been paged out to disk. In the lists 'b', 'c' and (twice) 'd'. I don't have a problem with objects being in two places at the same time. It's just a mental model. I understand that, underneath, the memory for the object is in *one place*, somewhere, because distributed storage is a hard problem and no existing Python does it. But I also understand that underneath, *everything* is just mutable bytes. There are no ints or strings or lists or dicts, they're just an abstraction. If you keep looking behind the curtains, looking at the implementation of each level of abstraction, eventually you'll get to bytes, and then electrons. If you go there, then you'll conclude that the object 'a' isn't anywhere. I'm happy with a high-level abstraction where Python objects can be in more than one place at once. Now, how do you implement such an abstraction? The easiest way is to have the object in one (hidden?) place, and have everywhere else use a pointer or reference to it. But that's a lower level of description than you can reach from Python code, because you can't access those pointers. You can only infer that they are there because otherwise you have to accept that objects can be in two places at once. Or because you've read the source code, but that's implementation. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: mmap only supports string
On Jan 7, 8:14 pm, Neal Becker ndbeck...@gmail.com wrote: Problem is, AFAIK a string can only be created as a copy of some other data. Say I'd like to take some large object and read/write to/from mmap object. A good way to do this would be the buffer protocol. Unfortunately, mmap only supports string. A string could only be created after copying the original object AFAIK. I think mmap should work directly with buffer protocol, so it could directly read/write with objects supporting buffer protocol. Specifically, mmap slice should support buffer protocol. Hi. It is a weakness. Strings are supposed to be read-only in Python: so. You can use and get the PyObject_AsWriteBuffer C function from 'ctypes' if you are interested. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to deepcopy a list of user defined lists?
-- 964 self.__tmp_data = copy.deepcopy(self.__data) 965 /usr/local/python-2.5.1/lib/python2.5/copy.py in deepcopy(x, memo, _nil) 160 copier = _deepcopy_dispatch.get(cls) 161 if copier: -- 162 y = copier(x, memo) 163 else: 164 try: /usr/local/python-2.5.1/lib/python2.5/copy.py in _deepcopy_list(x, memo) 225 memo[id(x)] = y 226 for a in x: -- 227 y.append(deepcopy(a, memo)) 228 return y 229 d[list] = _deepcopy_list /usr/local/python-2.5.1/lib/python2.5/copy.py in deepcopy(x, memo, _nil) 187 raise Error( 188 un(deep)copyable object of type %s % cls) -- 189 y = _reconstruct(x, rv, 1, memo) 190 191 memo[d] = y /usr/local/python-2.5.1/lib/python2.5/copy.py in _reconstruct(x, info, deep, memo) 320 if deep: 321 args = deepcopy(args, memo) -- 322 y = callable(*args) 323 memo[id(x)] = y 324 if listiter is not None: /usr/local/python-2.5.1/lib/python2.5/copy_reg.py in __newobj__(cls, *args) 90 91 def __newobj__(cls, *args): --- 92 return cls.__new__(cls, *args) 93 94 def _slotnames(cls): type 'exceptions.TypeError': __new__() takes exactly 3 arguments (1 given) - Original Message From: Chris Rebert c...@rebertia.com To: srinivasan srinivas sri_anna...@yahoo.co.in Cc: python-list@python.org Sent: Thursday, 8 January, 2009 1:56:27 PM Subject: Re: How to deepcopy a list of user defined lists? On Wed, Jan 7, 2009 at 11:59 PM, srinivasan srinivas sri_anna...@yahoo.co.in wrote: Hi, I have a class which is a subclass of builtin-type list. #-- class clist(list): def __new__(cls, values, ctor): val = [] for item in values: item = ctor(item) val.append(item) self = list.__new__(cls, val) self.__values = val self.__ctor = ctor return self #--- I have a list of clists, say c1 = [clist1, clist2, clist3] How do i deepcopy this list? I tried using copy.deepcopy() method. But i got some errors. Please suggest me. And those errors are? Please include a full Traceback. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com Check out the all-new Messenger 9.0! Go to http://in.messenger.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to deepcopy a list of user defined lists?
On Thu, 08 Jan 2009 13:29:37 +0530, srinivasan srinivas wrote: Hi, I have a class which is a subclass of builtin-type list. #-- class clist(list): def __new__(cls, values, ctor): val = [] for item in values: item = ctor(item) val.append(item) self = list.__new__(cls, val) self.__values = val self.__ctor = ctor return self #--- I have a list of clists, say c1 = [clist1, clist2, clist3] How do i deepcopy this list? I tried using copy.deepcopy() method. But i got some errors. Please suggest me. Don't tell us what the errors are, I love guessing games!!! Let's see... is it TypeError because your class doesn't override the list.__init__ method? clist1 = clist([1,2,3], str) Traceback (most recent call last): File stdin, line 1, in module TypeError: list() takes at most 1 argument (2 given) Before you get to deepcopy, you actually need to have clist work correctly. Once you've done that, show us what error you get. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: State of the art: Tkinter, Tk 8.5, Tix?
On Wed, 07 Jan 2009 20:31:23 +0100, excord80 excor...@gmail.com wrote: Does Python work with Tk 8.5? I'm manually installing my own Python 2.6.1 (separate from my system's Python 2.5.2), and am about to install my own Tcl/Tk 8.5 but am unsure how to make them talk to eachother. Should I install Tk first? If I put Tk into my home directory (under ~/opt most likely), is there some configure option I need to pass Python to tell it where to find my Tk? There's some important information missing here: the platform you're on... Anyway, you should indeed install tcl/tk first. Then, assuming you're on Linux, you should edit the file named Setup in the Modules sub-directory of your Python installation, find the lines for the _tkinter module and edit them to match your installation. Then, you can build and install Python and it should work without problem. As for Python 2.6 / tk 8.5 compatibility, it depends on what you want to do. Since tk 8.5 still offers the 'regular' tk widgets, these will work in Python 2.6. If you want the new widgets (aka ttk), I'm not sure there are official wrappers for them in the distro (there weren't any last time I checked). If there aren't, you can find the 'pre-official' ones here: http://pypi.python.org/pypi/pyttk Also, I see that Python comes with Tix. Was Tix supposed to be something to make up for what was lacking in Tk prior to its 8.5 release? Is Tix here to stay, or has it been eclipsed by what comes with Tk 8.5 OOTB? I've never worked with Tix myself, but I'd say the widget set offered by tk/ttk is now quite complete. HTH -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiprocessing takes higher execution time
Sibtey Mehdi sibt...@infotechsw.com wrote: I use multiprocessing to compare more then one set of files. For comparison each set of files (i.e. Old file1 Vs New file1) I create a process, Process(target=compare, args=(oldFile, newFile)).start() It takes 61 seconds execution time. When I do the same comparison without implementing multiprocessing, it takes 52 seconds execution time. The oldProjects and newProjects will contains zip files i.e(oldxyz1.zip,oldxyz2.zip, newxyz2.zip,newxyz2.zip) it will unzip both the zip files and compare all the files between old and new (mdb files or txt files) and gives the result. I do this comparision for n number set of zip files and i assigne each set of zip files comparision to a process. I had a brief look at the code and your use of multiprocessing looks fine. How many projects are you processing at once? And how many MB of zip files is it? As reading zip files does lots of disk IO I would guess it is disk limited rather than anything else, which explains why doing many at once is actually slower (the disk has to do more seeks). -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating new instances of subclasses.
J. Cliff Dyer j...@unc.edu wrote: I want to be able to create an object of a certain subclass, depending on the argument given to the class constructor. I have three fields, and one might need to be a StringField, one an IntegerField, and the last a ListField. But I'd like my class to delegate to the proper subclass automatically, so I can just do: f1 = Field('abc') f2 = Field('123') f3 = Field('D,E,F') f1.data 'abc' f2.data 123 f3.data ['D','E','F'] type(f1) class '__main__.StringField' type(f2) class '__main__.StringField' type(f3) class '__main__.ListField' I've come up with a solution, but I suspect there's something cleaner I can do with the inheritance structure of __new__. I don't like explicitly leapfrogging over Field.__new__ to object.__new__. My attempt is below: def is_list(arg): if ',' in arg: return True else: return False def is_integer(arg): try: int(arg) except ValueError: return False else: return True class Field(object): def __new__(cls, a): if is_list(a): return ListField(a) elif is_integer(a): return IntegerField(a) else: return StringField(a) def __init__(self, input): super(Field, self).__init__(input) self.data = input class IntegerField(Field): def __new__(cls, a): return object.__new__(cls, a) def __init__(self, s): super(IntegerField, self).__init__(s) self.s = int(self.s) class ListField(Field): def __new__(cls, a): return object.__new__(cls, a) def __init__(self, s): super(ListField, self).__init__(s) self.s = s.split(',') class StringField(Field): def __new__(cls, a): return object.__new__(cls, a) Is there a cleaner way to do this? The main problem is that Field.__new__ gets in the way of properly constructing the subclasses once I've used it to select the proper subclass in the first place. How about this minor modification? # rest as above class Field(object): def __new__(cls, a): if cls != Field: return object.__new__(cls, a) if is_list(a): return ListField(a) elif is_integer(a): return IntegerField(a) else: return StringField(a) def __init__(self, input): super(Field, self).__init__(input) self.data = input class IntegerField(Field): def __init__(self, s): super(IntegerField, self).__init__(s) self.s = int(s) class ListField(Field): def __init__(self, s): super(ListField, self).__init__(s) self.s = s.split(',') class StringField(Field): pass Or you could go for the full metaclass self registration scheme like this, which is actually less code since I delegated the is this ok test to the subclass - failing it returns a ValueError. class Field(object): registry = [] class __metaclass__(type): def __init__(cls, name, bases, dict): cls.registry.append(cls) def __new__(cls, a): if cls != Field: return object.__new__(cls, a) for subcls in cls.registry: if subcls == Field: continue try: return subcls(a) except ValueError: pass raise ValueError(Couldn't find subclass) def __init__(self, input): super(Field, self).__init__(input) self.data = input # Raise a ValueError in init if not suitable args for this subtype class IntegerField(Field): def __init__(self, s): s = int(s) super(IntegerField, self).__init__(s) self.s = s class ListField(Field): def __init__(self, s): if ',' not in s: raise ValueError(Not a list) super(ListField, self).__init__(s) self.s = s.split(',') class StringField(Field): pass -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
eval('07') works, eval('08') fails, why?
I am baffled by this: IDLE 1.2.2 No Subprocess input() 07 7 input() 08 Traceback (most recent call last): File pyshell#1, line 1, in module input() File string, line 1 08 ^ SyntaxError: invalid token of course, I can work around this using raw_input() but I want to understand why this happens. It boils down to: eval('07') 7 eval('08') Traceback (most recent call last): File pyshell#3, line 1, in module eval('08') File string, line 1 08 ^ SyntaxError: invalid token I can't think of anything that could cause this. Similarly, eval('09') fails, but for string 0x with x8 it works. I am teaching myself Python in order to climb the ladder from Algol(1980s)--Pascal(1990s)-- VisualBasic(2000)--Python. I am a physicist, have programmed computers all my life but I won't understand the real tech jargon of present day computer science. Please keep it simple Thanks in advance, Alex van der Spek -- http://mail.python.org/mailman/listinfo/python-list
Re: eval('07') works, eval('08') fails, why?
Hi, 07 is octal. That's way 08 is invalid. Try this: === python print 011 9 print int('011') 11 -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de -- http://mail.python.org/mailman/listinfo/python-list
Force exception on attribute write access only one object
Hi, for debugging I want to raise an exception if an attribute is changed on an object. Since it is only for debugging I don't want to change the integer attribute to a property. This should raise an exception: myobj.foo=1 Background: Somewhere this value gets changed. But I don't now where. -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de -- http://mail.python.org/mailman/listinfo/python-list
Re: eval('07') works, eval('08') fails, why?
On Jan 8, 9:31 am, Alex van der Spek am...@xs4all.nl wrote: eval('07') 7 eval('08') Traceback (most recent call last): File pyshell#3, line 1, in module eval('08') File string, line 1 08 ^ SyntaxError: invalid token An integer literal with a leading zero is interpreted as an octal (base 8) number, so only digits in the range 0-7 (inclusive) are permitted in such a literal. Mark I can't think of anything that could cause this. Similarly, eval('09') fails, but for string 0x with x8 it works. I am teaching myself Python in order to climb the ladder from Algol(1980s)--Pascal(1990s)--VisualBasic(2000)--Python. I am a physicist, have programmed computers all my life but I won't understand the real tech jargon of present day computer science. Please keep it simple Thanks in advance, Alex van der Spek -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiprocessing takes higher execution time
On Thu, Jan 8, 2009 at 7:31 PM, Nick Craig-Wood n...@craig-wood.com wrote: (...) How many projects are you processing at once? And how many MB of zip files is it? As reading zip files does lots of disk IO I would guess it is disk limited rather than anything else, which explains why doing many at once is actually slower (the disk has to do more seeks). If this is the case, this problem is not well suited to multi processing but rather distributed processing :) --JamesMills -- http://mail.python.org/mailman/listinfo/python-list
Re: Force exception on attribute write access only one object
On Thu, Jan 8, 2009 at 1:38 AM, Thomas Guettler h...@tbz-pariv.de wrote: Hi, for debugging I want to raise an exception if an attribute is changed on an object. Since it is only for debugging I don't want to change the integer attribute to a property. This should raise an exception: myobj.foo=1 Background: Somewhere this value gets changed. But I don't now where. Completely untested: class Protector(object): def __init__(self, delegate, *forbidden): self.__delegate = delegate self.__forbidden = set(forbidden) def __getattr__(self, name): return getattr(self.__delegate, name) def __setattr__(self, name, value): if name in self.__forbidden: raise TypeError(attempt to assign to forbidden attribute '%s' % name) setattr(self.__delegate, name, value) x = Foo() x = Protector(x, bar) x.bar = 6 #should raise TypeError Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Traceback in Logging
The issue is that I am on Python 2.4 which doesnt support func name. I am using filename and lineno now. That does serve the purpose. Thank you, I had not checked all the parameters. Regards K Vinay Sajip wrote: On Jan 6, 4:17 pm, Kottiyath n.kottiy...@gmail.com wrote: I dont want the whole traceback. I just wanted to know where the log was generated from i.e. which procedure and which line. I have 3/4 points in many procedures where I encounter a small error (not an exception) and want to log it. So having individual names for each looks to be somewhat verbose - esp since the application is 10K LOC. Don't the funcName and lineno arguments in the format string work for you? (See http://docs.python.org/library/logging.html#id1) Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Reading C# serialized objects into Python?
Is there a way to read C# serialized objects into Python? I know the definition and structure of the C# objects. The Python docs say that pickle is specific to Python, which does not give me much hope. There may be a library however that I haven't come across yet. Thanks much, Alex van der Spek -- http://mail.python.org/mailman/listinfo/python-list
Re: using subprocess module in Python CGI
Dear Matt, Thank you for your answer. This script is just a kind of test script so as to actually get it started on doing any simple job. The actual process would be much more complicated where in I would like to extract the tar file and search for a file with certain extension and this file would be given as input to another program installed on the server. Later on I would also like to use process.wait() so that I can get a status of the job execution and completion from the server and this information can be displayed to the users on the web-page where they submit their jobs. As to what I understand subprocess.call() would be the best in that case. Please correct, if I am wrong. The whole process is like a user submitting a tar file via the web-browser with some data and getting back the processed results in the form of a new tar file after performing a few operations on the files submitted as input tar file. Thanking you once again for your valuable time. Regards. On Wed, Dec 24, 2008 at 1:54 AM, Matt Nordhoff mnordh...@mattnordhoff.comwrote: ANURAG BAGARIA wrote: Hello, I am a Python Newbie and would like to call a short python script via browser using a CGI script, but initially I am trying to call the same python script directly through python command line. The script intends to perform a few command line in a pipe and I have written the script (a short one) as follows. #!/usr/bin/python import cgi, string, os, sys, cgitb, commands, subprocess import posixpath, macpath #file = x.tar.gz #comd = tar -xf %s % (file) #os.system(comd) #commands.getoutput('tar -xf x.tar.gz | cd demo; cp README ../') comd = [\ tar -xf x.tar.gz, \ cd demo, \ cp README ../, \ ] That's not how subprocess.call() works. You're trying to run an executable called tar -xf x.tar.gz, passing it the arguments cd demo and cp README ../. outFile = os.path.join(os.curdir, output.log) outptr = file(outFile, w) errFile = os.path.join(os.curdir, error.log) errptr = file(errFile, w) retval = subprocess.call(comd, 0, None, None, outptr, errptr) errptr.close() outptr.close() if not retval == 0: errptr = file(errFile, r) errData = errptr.read() errptr.close() raise Exception(Error executing command: + repr(errData)) but after trying to execute this independently, I get the following error which I am unable to interpret : Traceback (most recent call last): File process.py, line 18, in module retval = subprocess.call(comd, 0, None, None, outptr, errptr) File /usr/lib/python2.5/subprocess.py, line 443, in call return Popen(*popenargs, **kwargs).wait() File /usr/lib/python2.5/subprocess.py, line 593, in __init__ errread, errwrite) File /usr/lib/python2.5/subprocess.py, line 1135, in _execute_child raise child_exception Could someone suggest where am I going wrong and if corrected, what is the probability of this script being compatible with being called through the browser. Thanking you people in advance. Well, you'd need to output something, but otherwise, sure, why not? print Content-Type: text/html print print html.../html Regards. Why do you even need to use subprocess to do this? All it's doing is extracting the README file from a tarball, right? You can use the tarfile module for that. http://docs.python.org/library/tarfile.html -- -- I just want to LIVE while I'm alive. AB -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading C# serialized objects into Python?
Alex van der Spek wrote: Is there a way to read C# serialized objects into Python? I know the definition and structure of the C# objects. The Python docs say that pickle is specific to Python, which does not give me much hope. There may be a library however that I haven't come across yet. IronPython might be of help here. You might try to de-serialize in IronPython, and then serialize again using pickle. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
On Jan 8, 1:45 am, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Wed, 07 Jan 2009 10:17:55 +, Mark Wooding wrote: snip The `they're just objects' model is very simple, but gets tied up in knots explaining things. The `it's all references' model is only a little more complicated, but explains everything. But it *over* explains, because it implies things that everybody knows about references in other languages that aren't true for Python. Of course it's not literally true that everybody knows that you can use references to implement a swap(x, y) procedure. But people coming from a C or Pascal background tend to assume that everything is like C/Pascal, and there are a lot of them. If C was a rare, unfamiliar language, my opposition to using the term reference would be a lot milder. Maybe in another five years? No, indeed. Python is a language for talking about paperweights. And it's because of the paperweights that the duck-typing works: all the paperweights are the same shape and size, so they're physically interchangeable. Okay, the abstraction has leaked again... are the paperweights references to the objects, or the names we've bound objects to? I'm confused... How do we deal with anonymous objects in your model? -- Steven Mark, hi, Steven, pleasure as always. Neither side is perfect or wild; (Do admit it); How do we decide what is best for newcomers to Python, depending on background? -- http://mail.python.org/mailman/listinfo/python-list
Re: Generator metadata/attributes
Thanks folks. Will write my own class Andrew PS So for the record, this works and isn't as ugly/verbose as I was expecting: class TaggedWrapper(): def __init__(self, generator, logMixin, stream): self.__generator = generator self.__tag = '%...@%s' % (logMixin.describe(), stream) logMixin._debug('Created %s' % self) def __next__(self): return next(self.__generator) def __str__(self): return self.__tag def tag_generator(f): ''' Log the generator. ''' def call(self, stream): return TaggedWrapper(f(self, stream), self, stream) return call -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
ru...@yahoo.com ru...@yahoo.com wrote: I thought you were objecting to Python's use of the term binding when you wrote: [snip] in response to someone talking about ...all those who use the term \name binding\ instead of variable assignment Oh, that. Well, the terms are `binding' and `assignment'. Python doesn't need another name for assignment, because actually its idea of assignment is the same as anyone else's. The difference is in the way it deals with objects. See argument elsewhere. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: Force exception on attribute write access only one object
Thomas Guettler wrote: for debugging I want to raise an exception if an attribute is changed on an object. Since it is only for debugging I don't want to change the integer attribute to a property. Why? This should raise an exception: myobj.foo=1 Background: Somewhere this value gets changed. But I don't now where. If you change your mind: class A(object): def __init__(self): self.foo = 42 a = A() b = A() class B(A): @property def foo(self): return self.__dict__[foo] b.__class__ = B a.foo = whatever print b.foo b.foo = whatever Peter -- http://mail.python.org/mailman/listinfo/python-list
Python Community Service Awards
Ben Finney recently wrote: Paul McNett p...@ulmcnett.com writes: [...] I always end up sending the first reply to the sender, then going oops, forgot to hit reply-all', and sending another copy to the list.] [...] Thanks to the Python mailing list administrators for conforming to the standards and not breaking the configuration like that! And for the way they keep the mail flowing day after day, and for the news/email gateway function, and ... Brad Knowles is a frequently unsung hero, who thoroughly deserves the PSF Community Award he got for his sterling service in the email area. He is ably assisted in this task by Ralf Hildebrandt and Patrick Koetter, authors of The Book of Postfix. If you know of anyone whom you think deserves to be similarly honored please feel free to let me, or the PSF Board, know about it. When we can't reward people in a material way I believe it's very important to acknowledge these voluntary contributions. http://www.python.org/community/awards/psf-awards/ regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
Aaron Brady wrote: On Jan 8, 1:45 am, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Wed, 07 Jan 2009 10:17:55 +, Mark Wooding wrote: snip The `they're just objects' model is very simple, but gets tied up in knots explaining things. The `it's all references' model is only a little more complicated, but explains everything. But it *over* explains, because it implies things that everybody knows about references in other languages that aren't true for Python. Of course it's not literally true that everybody knows that you can use references to implement a swap(x, y) procedure. But people coming from a C or Pascal background tend to assume that everything is like C/Pascal, and there are a lot of them. If C was a rare, unfamiliar language, my opposition to using the term reference would be a lot milder. Maybe in another five years? No, indeed. Python is a language for talking about paperweights. And it's because of the paperweights that the duck-typing works: all the paperweights are the same shape and size, so they're physically interchangeable. Okay, the abstraction has leaked again... are the paperweights references to the objects, or the names we've bound objects to? I'm confused... How do we deal with anonymous objects in your model? -- Steven Mark, hi, Steven, pleasure as always. Neither side is perfect or wild; (Do admit it); How do we decide what is best for newcomers to Python, depending on background? The crux of this mistake is assuming that all beginners are alike, and that there is therefore a single best way to explain things to them. Teaching should be a dialog, in which the teacher makes use of knowledge revealed by the student about their existing knowledge and ways of thinking to present ideas in an easily assimilable form. In other words, don't treat all students the same. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading C# serialized objects into Python?
Alex van der Spek wrote: Is there a way to read C# serialized objects into Python? I know the definition and structure of the C# objects. The Python docs say that pickle is specific to Python, which does not give me much hope. There may be a library however that I haven't come across yet. struct? regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it ok to type check a boolean argument?
Adal Chiriliuc a écrit : On Jan 7, 10:15 pm, Bruno Desthuilliers bdesth.quelquech...@free.quelquepart.fr wrote: This being said, I can only concur with other posters here about the very poor naming. As far as I'm concerned, I'd either keep the argument as a boolean but rename it ascending (and use a default True value), or keep the 'order' name but then accept 'asc' and 'desc' as values ('asc' being the default). Well, I lied a bit :-p The actual function is 20 lines long, and does other stuff to. The order argument is not passed as an argument, but as a field on an input object. Then the input object should probably be responsible for validating this (IMHO). (snip) You are all right, order is a bad name choice. sort_ascending would be a much better name for a boolean variable. I found Paul's idea very interesting, but I prefer to not introduce new objects which behave like C enums (maybe that would be more Pythonic?), so I found this variant: def find(field, sort_ascending): order_by = {True: asc, False: desc} return _find(field + + + order_by[sort_ascending]) for a simple True/False dispatch, my usual idiom (predating the ternary operator) is: order_by = (desc, asc)[sort_ascending] But what if we can't solve it as ellegantly, and we need to execute different code depending on the condition: def find(field, fast_mode=True): if fast_mode: do_something(field, 1, DEFAULT_PAGE_SIZE) else: do_another_thing(field, False, xml, ignore_error=False) and_another_one() Should we typecheck in this case to ensure that if we pass a string for fast_mode we will raise an exception? I don't think so. Going that way, you will end up typechecking each and any function argument. While there are a couple typechecks here and there even in the stdlib and builtins, this doesn't mean it's how Python is supposed to be used - Python is a dynamic language, leave with it or choose another one !-) But anyway, ensuring a program's correctness requires much more than static typing. What you want IMHO is: 1/ a solid *user input* validation/conversion framework (FormEncode comes to mind) 2/ a sensible set of unittests and integration tests. Trying to forcefit static typing into Python will only buy you pain and frustration (not even talking about the waste of time). -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] compiling python2.5 on linux under wine
On Sat, Jan 3, 2009 at 11:22 PM, Luke Kenneth Casson Leighton l...@lkcl.net wrote: secondly, i want a python25.lib which i can use to cross-compile modules for poor windows users _despite_ sticking to my principles and keeping my integrity as a free software developer. If this eventually leads to being able to compile Python software for Windows under Wine (using for example, py2exe) it would make my life a lot easier. Schiavo Simon -- http://mail.python.org/mailman/listinfo/python-list
RE: Multiprocessing takes higher execution time
Thanks Nick. It processes 10-15 projects(i.e. 10-15 processes are started) at once. One Zip file size is 2-3 MB. When I used dual core system it reduced the execution time from 61 seconds to 55 seconds. My dual core system Configuration is, Pentium(R) D CPU 3.00GHz, 2.99GHz 1 GB RAM Regards, Gopal -Original Message- From: Nick Craig-Wood [mailto:n...@craig-wood.com] Sent: Thursday, January 08, 2009 3:01 PM To: python-list@python.org Subject: Re: Multiprocessing takes higher execution time Sibtey Mehdi sibt...@infotechsw.com wrote: I use multiprocessing to compare more then one set of files. For comparison each set of files (i.e. Old file1 Vs New file1) I create a process, Process(target=compare, args=(oldFile, newFile)).start() It takes 61 seconds execution time. When I do the same comparison without implementing multiprocessing, it takes 52 seconds execution time. The oldProjects and newProjects will contains zip files i.e(oldxyz1.zip,oldxyz2.zip, newxyz2.zip,newxyz2.zip) it will unzip both the zip files and compare all the files between old and new (mdb files or txt files) and gives the result. I do this comparision for n number set of zip files and i assigne each set of zip files comparision to a process. I had a brief look at the code and your use of multiprocessing looks fine. How many projects are you processing at once? And how many MB of zip files is it? As reading zip files does lots of disk IO I would guess it is disk limited rather than anything else, which explains why doing many at once is actually slower (the disk has to do more seeks). -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] compiling python2.5 on linux under wine
On Thu, Jan 8, 2009 at 9:42 PM, Simon Cross hodgestar+python...@gmail.com wrote: On Sat, Jan 3, 2009 at 11:22 PM, Luke Kenneth Casson Leighton l...@lkcl.net wrote: secondly, i want a python25.lib which i can use to cross-compile modules for poor windows users _despite_ sticking to my principles and keeping my integrity as a free software developer. If this eventually leads to being able to compile Python software for Windows under Wine (using for example, py2exe) it would make my life a lot easier. You can already do that: just install windows python under wine. It works quite well, actually. You need mingw, though, of course - Visual Studio is far from being usable on wine. cheers, David -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] compiling python2.5 on linux under wine
On Thu, Jan 8, 2009 at 12:42 PM, Simon Cross hodgestar+python...@gmail.com wrote: On Sat, Jan 3, 2009 at 11:22 PM, Luke Kenneth Casson Leighton l...@lkcl.net wrote: secondly, i want a python25.lib which i can use to cross-compile modules for poor windows users _despite_ sticking to my principles and keeping my integrity as a free software developer. If this eventually leads to being able to compile Python software for Windows under Wine (using for example, py2exe) it would make my life a lot easier. that looks like being an accidental side-effect, yes. where i'm up to so far: * i'm using -I $(src_dir)/PC at the beginning of the includes, so that PC/pyconfig.h gets pulled in as a priority over-and-above the auto-generated pyconfig.h (yukkk - i know); this makes the job of building almost-exactly-like-the-visual-studio-build much easier. * i'm manually compiling-linking the Modules/*.c and PC/*modules.c as i also pulled in PC/config.c and left out Modules/config.c - that got me even further * as a result i've actually got a python.exe.so that damnit, it works! the winreg test actually passes for example! the fly in the ointment i'm presently trying to track down: len([1,2]) returns 1L which of course screws up sre_parse.py at line 515 with TypeError: __nonzero__ should return an int because duh if subpattern is returning a Long not an Int. tracking this down further, it would appear that there's some lovely logic in PyInt_FromSsize_t() which i believe is what's getting called from PyInt_AsSsize_t() which is what's getting called from slot_sq_length() (i think) - and, although in this case this build is _definitely_ returning a Long type when it shouldn't, if the value is ever over LONG_MAX then the result will be if subpattern will definitely fail. but... i mean... if ever anyone passes in over 2^^31 items into sre_parse then they _deserve_ to have their code fail, but that's not the point. anyway, i'm floundering around a bit and making a bit of a mess of the code, looking for where LONG_MAX is messing up. l. which of course means that there's a bug in -- http://mail.python.org/mailman/listinfo/python-list
Default __nonzero__ impl doesn't throw a TypeError exception
In Python empty container equals False in 'if' statements: # prints It's ok if not []: print It's ok Let's create a simple Foo class: class Foo: pass Now I can use Foo objects in 'if' statements: #prints Ouch! f=Foo() if f: print Ouch! So, default __nonzero__ impl is to return True. I think, this behaviour conflicts with 'Explicit is better than implicit' and 'Practicality beats purity' statements. I think, throwing a TypeError exception would be better. It will result in more explicit code with fewer errors. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] compiling python2.5 on linux under wine
On Thu, Jan 8, 2009 at 1:11 PM, David Cournapeau courn...@gmail.com wrote: On Thu, Jan 8, 2009 at 9:42 PM, Simon Cross hodgestar+python...@gmail.com wrote: On Sat, Jan 3, 2009 at 11:22 PM, Luke Kenneth Casson Leighton l...@lkcl.net wrote: secondly, i want a python25.lib which i can use to cross-compile modules for poor windows users _despite_ sticking to my principles and keeping my integrity as a free software developer. If this eventually leads to being able to compile Python software for Windows under Wine (using for example, py2exe) it would make my life a lot easier. You can already do that: just install windows python under wine. i tried that a few months ago - the builder requires the MS installer, which segfaulted on my installation of wine (i installed it using winetricks) which left me flummoxed because other people report successful use of MSI. i also don't want just the python.exe, i want the libpython25.a, i want the libpython25.lib, so as to be able to build libraries such as pywekbit-gtk for win32 (cross-compiled using winegcc of course) unpacking the python installer .exe (which was, again, created with a proprietary program) i found that all of the contents were name-mangled and so were useless: i wasn't about to work my way through nearly a hundred files, manually, when i can just as well get python compiling under wine once and then stand a good chance of being able to repeat the exercise in the future, also for python 2.6. so, basically, i really don't want to use visual studio, i really don't want to install a proprietary MSI installer, i really don't want a proprietarily-built python25.exe, and i really don't want a proprietarily-packed installation. i'd just ... much rather be completely independent of proprietary software when it comes to building free software. onwards :) -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] compiling python2.5 on linux under wine
On Thu, Jan 8, 2009 at 11:02 PM, Luke Kenneth Casson Leighton l...@lkcl.net wrote: On Thu, Jan 8, 2009 at 1:11 PM, David Cournapeau courn...@gmail.com wrote: On Thu, Jan 8, 2009 at 9:42 PM, Simon Cross hodgestar+python...@gmail.com wrote: On Sat, Jan 3, 2009 at 11:22 PM, Luke Kenneth Casson Leighton l...@lkcl.net wrote: secondly, i want a python25.lib which i can use to cross-compile modules for poor windows users _despite_ sticking to my principles and keeping my integrity as a free software developer. If this eventually leads to being able to compile Python software for Windows under Wine (using for example, py2exe) it would make my life a lot easier. You can already do that: just install windows python under wine. i tried that a few months ago - the builder requires the MS installer, which segfaulted on my installation of wine (i installed it using winetricks) which left me flummoxed because other people report successful use of MSI. Hm, I could definitely install python - I have python in wine ATM. wine python -c 'import sys; print sys.version' - 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] IIRC, I could build numpy on it, which is far from a trivial package from a build POV :) I think it crashes on wine, though - which I why I did not pursued it so far. But I believe python itself at least is usable in wine, depending on what you are trying to do. David -- http://mail.python.org/mailman/listinfo/python-list
Nubie question: how to not pass self in call to seek() function ?
Hi, I am getting the error TypeError: seek() takes exactly 2 arguments (3 given), namely: $ ./_LogStream.py Traceback (most recent call last): File ./_LogStream.py, line 47, in module log_stream.last_line_loc_and_contents() File ./_LogStream.py, line 20, in last_line_loc_and_contents self.input_file.seek(-1, 2) # grab the last character TypeError: seek() takes exactly 2 arguments (3 given) When I run the below code. I understand that the extra argument is the self, but I don't know how to change my class to make the seek(-1,2) work. Could you help ? Thanks, Ron. $ cat _LogStream.py #!/usr/bin/env python import gzip import sys from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) self.index_increment = 10 self.last_line_offset = -1 def last_line_loc_and_contents(self, estimated_line_size=1024): assert estimated_line_size 0 file_size = len(self.input_file.read()) self.input_file.seek(-1, 2) # grab the last character if self.input_file.read(1) == '\n': # a proper text file file_size -= 1 def open_file(self, in_file): The gzip module checks if the input file is a gzipped file, only at the read stage. This is why the f.readline() is needed. try: f = gzip.GzipFile(in_file, r) f.readline() except IOError: f = open(in_file, r) f.readline() f.seek(0) return(f) if __name__ == __main__: filename = ../save_state/hp/save_state-ssp8400-0709R4_081126-121659/var/log\\sac.log.4.gz log_stream = LogStream(filename) log_stream.limit_ = 1000 log_stream.index_increment = 12 log_stream.last_line_loc_and_contents() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set a cookie using Cookie Module
On Jan 7, 9:35 am, tryg.ol...@gmail.com wrote: Hello - This is my first attempt at python cookies. I'm using the Cookie module and trying to set a cookie. Below is my code. The cookie does not get set. What am I doing wrong? print Cache-Control: max-age=0, must-revalidate, no-store print Content-type: text/html print print htmlheadtitleMy Page/title link rel=stylesheet href=/ss.css type=text/css c = Cookie.Cookie() c['MyCookie'] = Tryg print c print If I put javascript code to create a cookie in place of my python cookie code, the javascript cookie gets set. Any tips appreciated! Tryg I eventually figured it out myself. The cookie code needs to be part of the HTTP header. See example below. print Cache-Control: max-age=0, must-revalidate, no-store print Content-type: text/html c = Cookie.Cookie() c['MyCookie'] = Tryg print c print print htmlheadtitleMy Page/title link rel=stylesheet href=/ss.css type=text/css -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set a cookie using Cookie Module
On Jan 7, 9:35 am, tryg.ol...@gmail.com wrote: Hello - This is my first attempt at python cookies. I'm using the Cookie module and trying to set a cookie. Below is my code. The cookie does not get set. What am I doing wrong? print Cache-Control: max-age=0, must-revalidate, no-store print Content-type: text/html print print htmlheadtitleMy Page/title link rel=stylesheet href=/ss.css type=text/css c = Cookie.Cookie() c['MyCookie'] = Tryg print c print If I put javascript code to create a cookie in place of my python cookie code, the javascript cookie gets set. Any tips appreciated! Tryg I eventually figured it out myself. The cookie code needs to be part of the HTTP header. See example below. print Cache-Control: max-age=0, must-revalidate, no-store print Content-type: text/html c = Cookie.Cookie() c['MyCookie'] = Tryg print c print print htmlheadtitleMy Page/title link rel=stylesheet href=/ss.css type=text/css -- http://mail.python.org/mailman/listinfo/python-list
Re: Generator metadata/attributes
wrote in news:053df793-9e8e-4855-aba1-f92482cd8922 @v31g2000vbb.googlegroups.com in comp.lang.python: class TaggedWrapper(): def __init__(self, generator, logMixin, stream): self.__generator = generator self.__tag = '%...@%s' % (logMixin.describe(), stream) logMixin._debug('Created %s' % self) Note that self in the above is the instance of the wrapper class TaggedWrapper, not the class that is having its (generator) method decorated. import logging logging.basicConfig( level = logging.DEBUG ) def mydecorator( f ): def decorated(self, *args): logging.debug( Created %s, self.__class__.__name__ ) for i in f(self, *args): yield i return decorated class Example( object ): @mydecorator def foo(self, a, b, ): yield 1 + a + b e = Example() for i in e.foo( 2, 3 ): print( i ) Output of the above is: DEBUG:root:Created Example 6 Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Tree views - Best design practices
Hi! I have certain design problem, which I cannot solve elegantly. Maybe you know some good design patterns for this kind of tasks. Task: We have a model which has two kinds of objects: groups and elements. Groups can hold other groups (subgroups) and elements. It's a simple directory tree, for example. We would like to display it in a tree view (which sound good for this kind of model). What is more required, for groups and elements there are different sets of operations, which should be available under right click. For example for group, there should be operations: 'add element' and 'add group', and for element there should be 'change properties'. Do you know any smart way to achieve this? The simplest way is to ask for the class and display operations accordingly. But from the first day with OO programming I have heard, that asking for class is wrong. But I can hardly see any easy and more maintainable solution for this problem. Could you help me with this? -- Filip Gruszczyński -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating new instances of subclasses.
On Jan 7, 12:00 pm, Paul McGuire pt...@austin.rr.com wrote: On Jan 7, 10:38 am, J. Cliff Dyer j...@unc.edu wrote: I want to be able to create an object of a certain subclass, depending on the argument given to the class constructor. I have three fields, and one might need to be a StringField, one an IntegerField, and the last a ListField. But I'd like my class to delegate to the proper subclass automatically, so I can just do: f1 = Field('abc') f2 = Field('123') f3 = Field('D,E,F') O-O is not always the solution to every problem. Since inheritance is getting in your way, try using a class-level factory method. Instead of using the Field constructor, use a staticmethod of Field, something like: @staticmethod def make_Field(a) if is_list(a): return ListField(a) elif is_integer(a): return IntegerField(a) else: return StringField(a) and then get rid of all those __new__ methods, too. -- Paul After looking this over a bit more, I decided I didn't like make_Field having to know the criteria for creating the different subclasses, but wanted to put the smarts into the subclasses themselves. Here is an excerpt that shows this working: class Field(object): def __init__(self, input): super(Field, self).__init__(input) self.data = input @staticmethod def make_Field(a): subs = (ListField, IntegerField, StringField) ret = None for cls in subs: try: ret = cls(a) except TypeError: continue else: break return ret class IntegerField(Field): def __new__(cls, a): if not is_integer(a): raise TypeError() return Field.__new__(cls, a) ... ListField has a similar __new__ method, and StringField just creates the object, with no validation. make_Field still has to know what order to list the subclasses in (StringField is the most permissive, and so must come last in the list of subclasses), but the specific type tests are moved into the subclasses, which is a more appropriate place I think. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] compiling python2.5 on linux under wine
anyway, i'm floundering around a bit and making a bit of a mess of the code, looking for where LONG_MAX is messing up. fixed with this: PyObject * PyInt_FromSsize_t(Py_ssize_t ival) { if ((long)ival = (long)LONG_MIN (long)ival = (long)LONG_MAX) { return PyInt_FromLong((long)ival); } return _PyLong_FromSsize_t(ival); } raised as http://bugs.python.org/issue4880 next bug: distutils.sysconfig.get_config_var('srcdir') is returning None (!!) -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
Absolutely. Trivially and at a high level, teaching python to kids who are learning programming as introductory material teaching python to motivated college graduate students teaching python to adult non-professional programmers with a need to learn python (like for instance, frustrated accountants who have HAD IT with VBA...) The difference between the last 2 is important. I am not now nor will I ever be a professional programmer; there's a depth of knowledge to the subject that I will not ever systematically study (mostly due to time constraints). On the other hand, the problems I want and need to solve, I want to get right and will put in the effort to learn what I need to get it right. Contrast the college student. He's getting a broad and hopefully deep grounding in more CS theory than I have. How much does he care? Well, the beer bash Friday at 4 probably has a higher priority in his life right now, not unreasonably. So you can explain things to me fairly technically (I've done lots of VBA programming, hated it, and am motivated in self-study in python), but not too abstractly, because I don't have a deep ground in the theory behind CS and programming. (What I know of grammar parsing comes via some linguistics work I did in college, not Backus-Naur Form, although Noam chomsky was important in both fields) In contrast, the CS student should get a generalized explanation because he needs to grow the skills to work it out on his own, and because the generalized and theoretically grounded explanation is more useful for him in extrapolating to other areas. If he can't do more with it than i can, he needs to change majors. On 1/8/09, Steve Holden st...@holdenweb.com wrote: Aaron Brady wrote: On Jan 8, 1:45 am, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Wed, 07 Jan 2009 10:17:55 +, Mark Wooding wrote: snip The `they're just objects' model is very simple, but gets tied up in knots explaining things. The `it's all references' model is only a little more complicated, but explains everything. But it *over* explains, because it implies things that everybody knows about references in other languages that aren't true for Python. Of course it's not literally true that everybody knows that you can use references to implement a swap(x, y) procedure. But people coming from a C or Pascal background tend to assume that everything is like C/Pascal, and there are a lot of them. If C was a rare, unfamiliar language, my opposition to using the term reference would be a lot milder. Maybe in another five years? No, indeed. Python is a language for talking about paperweights. And it's because of the paperweights that the duck-typing works: all the paperweights are the same shape and size, so they're physically interchangeable. Okay, the abstraction has leaked again... are the paperweights references to the objects, or the names we've bound objects to? I'm confused... How do we deal with anonymous objects in your model? -- Steven Mark, hi, Steven, pleasure as always. Neither side is perfect or wild; (Do admit it); How do we decide what is best for newcomers to Python, depending on background? The crux of this mistake is assuming that all beginners are alike, and that there is therefore a single best way to explain things to them. Teaching should be a dialog, in which the teacher makes use of knowledge revealed by the student about their existing knowledge and ways of thinking to present ideas in an easily assimilable form. In other words, don't treat all students the same. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Work with Open Office
Okay, I'm currently stuck with VBA / Excel in work and the following paradigm: VB (6? .NET? not sure) == VBA == Excel 2003 and Access Where I'd like to be is this Python == X == Open Office / (MySQL or other) for some sufficiently useful value of X. Does it exist? Is it just a set of modules I need to be looking for? or something else? -- http://mail.python.org/mailman/listinfo/python-list
Re: Nubie question: how to not pass self in call to seek() function ?
Barak, Ron ron.ba...@lsi.com wrote in message news:7f0503cd69378f49be0dc30661c6ccf602494...@enbmail01.lsi.com... Hi, I am getting the error TypeError: seek() takes exactly 2 arguments (3 given), namely: $ ./_LogStream.py Traceback (most recent call last): File ./_LogStream.py, line 47, in module log_stream.last_line_loc_and_contents() File ./_LogStream.py, line 20, in last_line_loc_and_contents self.input_file.seek(-1, 2) # grab the last character TypeError: seek() takes exactly 2 arguments (3 given) When I run the below code. I understand that the extra argument is the self, but I don't know how to change my class to make the seek(-1,2) work. Could you help ? Perhaps the extra agrument is 2. You don't mention your Python version, but in Python 2.6.1 gzip files don't support seeking from the end. An older (your?) version of Python may not be providing as helpful an error message. f=gzip.GzipFile('blah.gz','r') f.seek(-1,2) Traceback (most recent call last): File stdin, line 1, in module File C:\dev\python\lib\gzip.py, line 368, in seek raise ValueError('Seek from end not supported') ValueError: Seek from end not supported -Mark Thanks, Ron. $ cat _LogStream.py #!/usr/bin/env python import gzip import sys from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) self.index_increment = 10 self.last_line_offset = -1 def last_line_loc_and_contents(self, estimated_line_size=1024): assert estimated_line_size 0 file_size = len(self.input_file.read()) self.input_file.seek(-1, 2) # grab the last character if self.input_file.read(1) == '\n': # a proper text file file_size -= 1 def open_file(self, in_file): The gzip module checks if the input file is a gzipped file, only at the read stage. This is why the f.readline() is needed. try: f = gzip.GzipFile(in_file, r) f.readline() except IOError: f = open(in_file, r) f.readline() f.seek(0) return(f) if __name__ == __main__: filename = ../save_state/hp/save_state-ssp8400-0709R4_081126-121659/var/log\\sac.log.4.gz log_stream = LogStream(filename) log_stream.limit_ = 1000 log_stream.index_increment = 12 log_stream.last_line_loc_and_contents() -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] compiling python2.5 on linux under wine
next bug: distutils.sysconfig.get_config_var('srcdir') is returning None (!!) ok ... actually, that's correct. oops. sysconfig.get_config_vars() only returns these, on win32: {'EXE': '.exe', 'exec_prefix': 'Z:\\mnt\\src\\python2.5-2.5.2', 'LIBDEST': 'Z:\\mnt\\src\\python2.5-2.5.2\\Lib', 'prefix': 'Z:\\mnt\\src\\python2.5-2.5.2', 'SO': '.pyd', 'BINLIBDEST': 'Z:\\mnt\\src\\python2.5-2.5.2\\Lib', 'INCLUDEPY': 'Z:\\mnt\\src\\python2.5-2.5.2\\include'} ... nd, that means disabling setup.py or hacking it significantly to support a win32 build, e.g. to build pyexpat, detect which modules are left, etc. by examining the remaining vcproj files in PCbuild. ok - i'm done for now. the project's not complete, but can be regarded as successful so far. i think the best thing is being able to do import _winreg on a linux system. that absolutely tickles me silly :) been running a few tests - test_mmap.py is a hoot, esp. the Try opening a bad file descriptor... that causes a wine segfault. if anyone wants to play with this further, source is here: http://github.com/lkcl/pythonwine/tree/python_2.5.2_wine at some point - if i feel like taking this further, and if people offer some advice and hints on where to go (with e.g. setup.py) i'll continue. then once that's done i'll do python 2.6 as well. l. -- http://mail.python.org/mailman/listinfo/python-list
How to Delete a Cookie?
Hello - I managed to get a cookie set. Now I want to delete it but it is not working. Do I need to do another 'set-cookie' in the HTTP header? I tried (code below setting expires to 0) and it didn't work. c = Cookie.SimpleCookie(os.environ[HTTP_COOKIE]) c[mycook][expires] = 0 print c In case its useful, here is how I set my cookie: c = Cookie.SimpleCookie() c[mycook] = Tryg c[mycook][expires] = 60*60*24 c[mycook][comment] = c[mycook][path]= / c[mycook][domain] = c[mycook][secure] = print c Thanks Tryg -- http://mail.python.org/mailman/listinfo/python-list
Re: Generator metadata/attributes
On Thu, 08 Jan 2009 08:42:55 -0600, Rob Williscroft wrote: def mydecorator( f ): def decorated(self, *args): logging.debug( Created %s, self.__class__.__name__ ) for i in f(self, *args): yield i return decorated can optionally be written as: def mydecorator( f ): def decorated(self, *args): logging.debug( Created %s, self.__class__.__name__ ) return f(self, *args) return decorated -- http://mail.python.org/mailman/listinfo/python-list
Re: Work with Open Office
On Thu, Jan 8, 2009 at 10:07 AM, Dan Esch daniel.a.e...@gmail.com wrote: Okay, I'm currently stuck with VBA / Excel in work and the following paradigm: VB (6? .NET? not sure) == VBA == Excel 2003 and Access Where I'd like to be is this Python == X == Open Office / (MySQL or other) for some sufficiently useful value of X. Does it exist? Is it just a set of modules I need to be looking for? or something else? Did you google search first? This is the second result for Python OpenOffice. http://wiki.services.openoffice.org/wiki/Python -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for tips on how to implement ruby-style Domain Specific Language in Python
Jonathan Gardner jgard...@jonathangardner.net writes: On Jan 7, 9:16 am, Chris Mellon arka...@gmail.com wrote: The OP wants a Ruby-style DSL by which he means something that lets me write words instead of expressions. The ruby syntax is amenable to this, python (and lisp, for that matter) syntax is not and you can't implement that style of internal DSL in those languages. The answer to the OP is you can't - use Ruby or modify your requirements. As far as putting the code into Python, yeah, you can't put it in Python. The best you can do is store it in a string and then interpret the string with some function later on. That's what I'm saying. It seems we're defining DSL in two different ways. You can't write a DSL in Python because you can't change the syntax and you don't have macros. You can write a compiler in Python that will compile your DSL. As another poster mentioned, eventually PyPy will be done and then you'll get more of an in-Python DSL. -- http://mail.python.org/mailman/listinfo/python-list
Symposium “Image Processing and Visualization in S olid Mechanics Processes” within the ESMC2009 Conference – Announce Call for Papers
- (Apologies for cross-posting) Symposium on “Visualization and Human-Computer” 7th EUROMECH Solid Mechanics Conference (ESMC2009) Instituto Superior Técnico, Lisbon, PORTUGAL, September 7-11, 2009 http://www.dem.ist.utl.pt/esmc2009/ (We would appreciate if you could distribute this information by your colleagues and co-workers.) --- Dear Colleague, Within the 7th EUROMECH Solid Mechanics Conference (ESMC2009), to be held in Instituto Superior Técnico, Lisbon, Portugal, September 7-11, 2009, we are organizing the Symposium “Image Processing and Visualization in Solid Mechanics Processes”. Examples of some topics that will be considered are: Image Analysis; Image Restoration, Compression, Segmentation and Description; Object Tracking, Matching, Recognition, and Reconstruction; Visual Inspection; 3D Vision; Medical Imaging; Data Processing, Modeling and Analysis; Scientific Visualization; Enhanced Visualization; Human Computer Interaction; Virtual Reality; Simulation and Animation; Software Development for Image Processing and Visualization; Grid Computing in Image Processing and Visualization; Applications of Image Processing and Visualization. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium “Image Processing and Visualization in Solid Mechanics Processes”. For instructions and submission, please access to the conference website at: http://www.dem.ist.utl.pt/esmc2009/ Please note that, when submitting your work, you should select the Symposium MS-08 – “Image Processing and Visualization in Solid Mechanics Processes”. Important dates: - Abstract submission: January 31, 2009; - Notification of acceptance: March 15, 2009; - Conference Events: September 7-11, 2009. Kind regards, João Manuel R. S. Tavares (University of Porto, Portugal, tava...@fe.up.pt) Michel A. Audette (Kitware, USA, michel.aude...@kitware.com) (Symposium organizers) -- http://mail.python.org/mailman/listinfo/python-list
python -3 not working as expected
[Python 2.6.1] Hi, to test existing Python code, I ran python -3 (warn about Python 3.x incompatibilities) against a test file that only contains print 'test'. Unfortunately I saw no warnings about print becoming a function in Python 3 (print()). Where is the problem? Thorsten -- http://mail.python.org/mailman/listinfo/python-list
RE: Nubie question: how to not pass self in call to seek() function ?
Hi Mark, I think my open_file() - that is called in __init__ - assures that self.input_file is a regular text file, regardless if filename is a gz or a regular text file. My Python is Python 2.5.2. Bye, Ron. -Original Message- From: Mark Tolonen [mailto:metolone+gm...@gmail.com] Sent: Thursday, January 08, 2009 17:16 To: python-list@python.org Subject: Re: Nubie question: how to not pass self in call to seek() function ? Barak, Ron wrote in message news:7f0503cd69378f49be0dc30661c6ccf602494...@enbmail01.lsi.com... Hi, I am getting the error TypeError: seek() takes exactly 2 arguments (3 given), namely: $ ./_LogStream.py Traceback (most recent call last): File ./_LogStream.py, line 47, in module log_stream.last_line_loc_and_contents() File ./_LogStream.py, line 20, in last_line_loc_and_contents self.input_file.seek(-1, 2) # grab the last character TypeError: seek() takes exactly 2 arguments (3 given) When I run the below code. I understand that the extra argument is the self, but I don't know how to change my class to make the seek(-1,2) work. Could you help ? Perhaps the extra agrument is 2. You don't mention your Python version, but in Python 2.6.1 gzip files don't support seeking from the end. An older (your?) version of Python may not be providing as helpful an error message. f=gzip.GzipFile('blah.gz','r') f.seek(-1,2) Traceback (most recent call last): File stdin, line 1, in module File C:\dev\python\lib\gzip.py, line 368, in seek raise ValueError('Seek from end not supported') ValueError: Seek from end not supported -Mark Thanks, Ron. $ cat _LogStream.py #!/usr/bin/env python import gzip import sys from Debug import _line as line class LogStream(): def __init__(self, filename): self.filename = filename self.input_file = self.open_file(filename) self.index_increment = 10 self.last_line_offset = -1 def last_line_loc_and_contents(self, estimated_line_size=1024): assert estimated_line_size 0 file_size = len(self.input_file.read()) self.input_file.seek(-1, 2) # grab the last character if self.input_file.read(1) == '\n': # a proper text file file_size -= 1 def open_file(self, in_file): The gzip module checks if the input file is a gzipped file, only at the read stage. This is why the f.readline() is needed. try: f = gzip.GzipFile(in_file, r) f.readline() except IOError: f = open(in_file, r) f.readline() f.seek(0) return(f) if __name__ == __main__: filename = ../save_state/hp/save_state-ssp8400-0709R4_081126-121659/var/log\\sac.log.4.gz log_stream = LogStream(filename) log_stream.limit_ = 1000 log_stream.index_increment = 12 log_stream.last_line_loc_and_contents() -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: parallel and/or synchronous start/run/stop on multiple boxes
Shane wrote: Consider a network of 3 fully-connected boxes i.e. every box as a TCP- IP connection to every other box. Suppose you start a python program P on box A. Is there a Python mechanism for P to send a copy of itself to box B or C then start that program P on B or C by running a method p in P? Is there a way that P on A could wait for that result? Bottom line: we have a number of needs in which it'd very convienent to write a phython program, install and run it, so that it could automatically propogate itself to wherever the code needs to go and run itself so that there could be multiple copies of the code running on different boxes with synchrounous (maybe asychronous) communication. A sort of Pythonic virus? :-) -- http://mail.python.org/mailman/listinfo/python-list
ask a question about richtextctrl
I have countered a problem while using wx.RichTextCtrl. I want to do some check when user presss Ctrl+C to paste. But i found that i can not get the wx.EVT_CHAR event while Ctrl+C is pressed. And I have tried many methods but all failed. So anybody can tell me some tips?Thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: formatted 'time' data in calculations
Scott David Daniels wrote: Ross wrote: There seems to be no shortage of information around on how to use the time module, for example to use time.ctime() and push it into strftime and get something nice out the other side, but I haven't found anything helpful in going the other way. As to a paucity of conversion formatting, there is no magic way to take everyone's way of putting date and time information in text and convert it to unambiguous format, in part because there are too many different and contradictory formats. When I write dates, I know what I intended; when I read dates, I guess what the author intended. Have you read the entire time module document? If so, which functions in that module take strings as arguments? That is, given some formatted text describing times - is there something that makes it easy to calculate time differences, or do I have to index my way through the string pulling out characters, converting to integers etc... Data is formatted: t1 = 09:12:10 t2 = 11:22:14 I want to calculate tdiff = t2-t1 Do you do any work yourself? Show us your attempts. This looks like a trivial exercise. It seems that for less than four times the effort of asking your question you might have found the answer. Perhaps I am being too cranky this morning. --Scott David Daniels scott.dani...@acm.org Jeeze, you're quite an ass aren't you? -- http://mail.python.org/mailman/listinfo/python-list
Re: eval('07') works, eval('08') fails, why?
On 2009-01-08, Alex van der Spek am...@xs4all.nl wrote: Thanks much, that makes sense! Well, that's the correct explanation. Whether that feature makes sense or not is debatable. Even I'm not old-school enough that I ever use octal literals -- and I used Unix on a PDP-11 for years (actually had my own PDP-11 for while, but it never worked). Now that I think of it, my Heathkit Z80 stuff used octal notation too. -- Grant Edwards grante Yow! I represent a at sardine!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for tips on how to implement ruby-style Domain Specific Language in Python
On 8 Jan., 16:25, J Kenneth King ja...@agentultra.com wrote: As another poster mentioned, eventually PyPy will be done and then you'll get more of an in-Python DSL. May I ask why you consider it as important that the interpreter is written in Python? I see no connection between PyPy and syntactical Python extensions and the latter isn't an objective of PyPy. You can write Python extensions with virtually any Python aware parser. M.A.Lemburg already mentioned PLY and PLY is used for Cython. Then there is ANTLR which provides a Python grammar. I also know about two other Python aware parsers. One of them was written by myself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Work with Open Office
Have been browsing through this list and reading documentation and tutorials for python self-study. I have, apparently, teh stupid. Google is my friend. Off I go. Thanks. On 1/8/09, Benjamin Kaplan benjamin.kap...@case.edu wrote: On Thu, Jan 8, 2009 at 10:07 AM, Dan Esch daniel.a.e...@gmail.comwrote: Okay, I'm currently stuck with VBA / Excel in work and the following paradigm: VB (6? .NET? not sure) == VBA == Excel 2003 and Access Where I'd like to be is this Python == X == Open Office / (MySQL or other) for some sufficiently useful value of X. Does it exist? Is it just a set of modules I need to be looking for? or something else? Did you google search first? This is the second result for Python OpenOffice. http://wiki.services.openoffice.org/wiki/Python -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tree views - Best design practices
Filip Gruszczyński wrote: Hi! I have certain design problem, which I cannot solve elegantly. Maybe you know some good design patterns for this kind of tasks. Task: We have a model which has two kinds of objects: groups and elements. Groups can hold other groups (subgroups) and elements. It's a simple directory tree, for example. We would like to display it in a tree view (which sound good for this kind of model). What is more required, for groups and elements there are different sets of operations, which should be available under right click. For example for group, there should be operations: 'add element' and 'add group', and for element there should be 'change properties'. Do you know any smart way to achieve this? The simplest way is to ask for the class and display operations accordingly. But from the first day with OO programming I have heard, that asking for class is wrong. But I can hardly see any easy and more maintainable solution for this problem. Could you help me with this? You could ask the object what the operations are. Here's an example using strings: class Element(object): operations = Element operations class Group(object): operations = Group operations e = Element() g = Group() e.operations 'Element operations' g.operations 'Group operations' -- http://mail.python.org/mailman/listinfo/python-list
Re: When does python 3.1, 3.2 ve rsion out?
Hi! The mountain Python-3000 gave birth to a mouse Python-3. You must waiting for Python-4000... @+ MCI -- http://mail.python.org/mailman/listinfo/python-list
FTP example going through a FTP Proxy
Hi, I need to write a simple Python script that I can connect to a FTP server and download files from the server to my local box. I am required to go through a FTP Proxy and I don't see any examples on how to do this. The FTP proxy doesn't require username or password to connect but the FTP server that I am connecting to does. Any examples on how to do this would be greatly appreciated. I am limited to using Python version 2.4.3 on a Linux box. -- http://mail.python.org/mailman/listinfo/python-list
Re: ftp seems to get a delayed reaction.
On 2009-01-06, Jeremy.Chen you...@gmail.com wrote: ftp.storbinary(STOR ftp-tst/ftp-file\n, fl) -- I think the params after STOR should't be a path,should be splited. ftp.cwd(ftp-tst) ftp.storbinary(STOR ftp-file\n, fl) No that isn't the problem. The problem is the '\n' at the end of the string. Having removed it, all worked fine. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: If your were going to program a game...
On Tue, 06 Jan 2009 10:44:39 -0700, Joe Strout wrote: Not that I have anything against Flash; I've started learning it just last week, and apart from the nasty C-derived syntax, it's quite nice. It has a good IDE, good performance, great portability, and it's easy to use. It just surprises me that after all these years, the Python community hasn't done something similar. It's bad enough that every time I go to a website using Flash, my browser is running untrusted code in my browser, but at least Adobe has spent a bucket-load of time and money making it (almost) secure. I sure as hell don't want arbitrary Python code running in my browser. Oh, and even Adobe hasn't got it completely right: IBM research Mark Dowd has demonstrated an incredible vulnerability that allows a single Trojan to exploit Flash in either IE or Firefox while leaving the Flash runtime operating normally. And it can bypass Vista security. Although Dowd doesn't explicitly mention other OSes, I see no reason to believe the same technique wouldn't work on Linux. http://www.matasano.com/log/1032/this-new-vulnerability-dowds-inhuman- flash-exploit/ This is not your regular buffer overflow vulnerability. Read it and weep. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
How do you write to the printer ?
Can find nothing in the on-line docs or a book. Groping in the dark I attempted : script24 import io io.open('stdprn','w') # accepted stdprn.write('hello printer') # fails stdprn is not defined Thanks to all responders I'm inching up on the snake. Dave WB3DWE -- http://mail.python.org/mailman/listinfo/python-list
Re: formatted 'time' data in calculations
Thanks Chris and Diez for the quick pointers... Very helpful Ross. -- http://mail.python.org/mailman/listinfo/python-list
sftp with no password from python
Is it possible to use sftp without a password from python? -- http://mail.python.org/mailman/listinfo/python-list
Re: eval('07') works, eval('08') fails, why?
Thanks much, that makes sense! Alex van der Spek -- http://mail.python.org/mailman/listinfo/python-list
figuring week of the day....
Is there a module where you could figure week of the day, like where it starts and end. I need to do this for a whole year. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: #python IRC help - my internet provider is banned!
What? Sounds a bit unlikely unless its Virgin.. I'd imagine it might be that your isp needs to get itself off a black list. Brian -- My Hotmail Account mildew_spo...@hotmail.com simonh simonharrison...@googlemail.com wrote in message news:fd0bd7d3-ad1d-43c2-b8e5-642a95c21...@t26g2000prh.googlegroups.com... Hi. Not sure if anyone can help here, but I'm trying to access #python and have found out that my ISP has a blanket ban (for some reason). Does anyone know how I can contact an operator to join? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Generator metadata/attributes
You could look at something like the following to turn the class iteslf into a decorator (changed lines *-ed): class TaggedWrapper(): * def __init__(self, logMixin, stream): self.__tag = '%...@%s' % (logMixin.describe(), stream) logMixin._debug('Created %s' % self) def __next__(self): return next(self.__generator) def __str__(self): return self.__tag def __call__(self, generator): self.__generator = generator return self and then decorate your generator: @TaggedWrapper(mixin, stream) def myGen; for a in range(1,100): yield a (Disclaimer: Completely untested...) -- http://mail.python.org/mailman/listinfo/python-list
Re: figuring week of the day....
here are a few tuts that go into more detail http://effbot.org/librarybook/datetime.htm http://seehuhn.de/pages/pdate -- http://mail.python.org/mailman/listinfo/python-list
Re: Tree views - Best design practices
class Element(object): operations = Element operations class Group(object): operations = Group operations e = Element() g = Group() e.operations 'Element operations' g.operations 'Group operations' But this is the same as asking for a class, except for having to write a method giving some form of a class name and then basing on this classname display operations. I know this solution, but this is what I would like to evade. -- Filip Gruszczyński -- http://mail.python.org/mailman/listinfo/python-list
Re: compiling python2.5 on linux under wine
... nd, that means disabling setup.py or hacking it significantly to support a win32 build, e.g. to build pyexpat, detect which modules are left, etc. by examining the remaining vcproj files in PCbuild. ok - i'm done for now. if anyone wants to play with this further, source is here: http://github.com/lkcl/pythonwine/tree/python_2.5.2_wine patch is also here: http://bugs.python.org/issue4880 -- http://mail.python.org/mailman/listinfo/python-list
Re: python -3 not working as expected
On Thu, 08 Jan 2009 16:38:53 +0100, Thorsten Kampe wrote: [Python 2.6.1] Hi, to test existing Python code, I ran python -3 (warn about Python 3.x incompatibilities) against a test file that only contains print 'test'. Unfortunately I saw no warnings about print becoming a function in Python 3 (print()). Where is the problem? There is no problem. ``print``\s are handled fine by the 2to3.py script. The option warns about stuff that is not easily automatically converted. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Tree views - Best design practices
Filip Gruszczyński wrote: class Element(object): operations = Element operations class Group(object): operations = Group operations e = Element() g = Group() e.operations 'Element operations' g.operations 'Group operations' But this is the same as asking for a class, except for having to write a method giving some form of a class name and then basing on this classname display operations. I know this solution, but this is what I would like to evade. My point was that the 'operations' attribute could specify the operations for that kind of object. More explicitly: class Element(object): operations = [change_properties] class Group(object): operations = [add_element, add_group] and so on. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tree views - Best design practices
Filip Gruszczyński wrote: Hi! I have certain design problem, which I cannot solve elegantly. Maybe you know some good design patterns for this kind of tasks. Task: We have a model which has two kinds of objects: groups and elements. Groups can hold other groups (subgroups) and elements. It's a simple directory tree, for example. We would like to display it in a tree view (which sound good for this kind of model). What is more required, for groups and elements there are different sets of operations, which should be available under right click. For example for group, there should be operations: 'add element' and 'add group', and for element there should be 'change properties'. Do you know any smart way to achieve this? The simplest way is to ask for the class and display operations accordingly. But from the first day with OO programming I have heard, that asking for class is wrong. But I can hardly see any easy and more maintainable solution for this problem. Could you help me with this? You don't ask *for* the class. You ask the class itself (or better, the object you currently deal with) what operations it supports. Your treeview-code then gets a list of strings for example (or better, a list of tuples (action, menuentry) ) that it uses to build the context-menu. When a given entry is selected, you then ask the object again to perform the action on itself, by passing the action-name. Or invoking a method called that way, or some such. Thus your treeview-code is completely generic and easily extendable with new functionality. There are variations of this scheme, if you don't want to pollute your model-classes with view/controller-logic. Then you need some sort of ActionFactory or something like that, which eventually somewhere might resort to a hard-coded list of class-to-action-mappings. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP example going through a FTP Proxy
On Jan 7, 3:56 pm, jakecjacobson jakecjacob...@gmail.com wrote: On Jan 7, 2:11 pm, jakecjacobson jakecjacob...@gmail.com wrote: On Jan 7, 12:32 pm, jakecjacobson jakecjacob...@gmail.com wrote: Hi, I need to write a simple Python script that I can connect to a FTP server and download files from the server to my local box. I am required to go through a FTP Proxy and I don't see any examples on how to do this. The FTP proxy doesn't require username or password to connect but the FTP server that I am connecting to does. Any examples on how to do this would be greatly appreciated. I am limited to using Python version 2.4.3 on a Linux box. This is what I have tried so far, import urllib proxies = {'ftp':'ftp://proxy_server:21'} ftp_server = 'ftp.somecompany.com' ftp_port='21' username = '' password = 'secretPW' ftp_string='ftp://' + username + '@' + password + ftp_server + ':' + ftp_port data = urllib.urlopen(ftp_string, proxies=proxies) data=urllib.urlopen(req).read() print data I get the following error: Traceback (most recent call last): File ./ftptest.py, line 22, in ? data = urllib.urlopen(ftp_server, proxies=proxies) File /usr/lib/python2.4/urllib.py, line 82, in urlopen return opener.open(url) File /usr/lib/python2.4/urllib.py, line 190, in open return getattr(self, name)(url) File /usr/lib/python2.4/urllib.py, line 470, in open_ftp host, path = splithost(url) File /usr/lib/python2.4/urllib.py, line 949, in splithost match = _hostprog.match(url) TypeError: expected string or buffer I might be getting closer. Now I am getting I/O error(ftp error): (111, 'Connection refused') error with the following code: import urllib2 proxies = {'ftp':'ftp://proxy_server:21'} ftp_server = 'ftp.somecompany.com' ftp_port='21' username = '' password = 'secretPW' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() top_level_url = ftp_server password_mgr.add_password(None, top_level_url, username, password) proxy_support = urllib2.ProxyHandler(proxies) handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(proxy_support) opener = urllib2.build_opener(handler) a_url = 'ftp://' + ftp_server + ':' + ftp_port + '/' print a_url try: data = opener.open(a_url) print data except IOError, (errno, strerror): print I/O error(%s): %s % (errno, strerror) I tried the same code from a different box and got a different error message: I/O error(ftp error): 501 USER format: proxy-user:auth- met...@destination. Closing connection. My guess is that my original box couldn't connect with the firewall proxy so I was getting a connection refused error. Now it appears that the password mgr has an issue if I understand the error correctly. I really hope that someone out in the Python Community can give me a pointer. -- http://mail.python.org/mailman/listinfo/python-list
Re: linked list with cycle structure
David Hláčik wrote: Hi, so okay, i will create a helping set, where i will be adding elements ID, when element ID will be allready in my helping set i will stop and count number of elements in helping set. This is how long my cycled linked list is. But what if i have another condition , and that is *i can use only helping memory with constant size* ? This means i am not able to create any set and adding elements there. I need to have a constant size variables . This is complication a complication for me. This isn't to hard - think about what you are really interested in - knowing if *all* other elements are already counted, or a specific one? You can get away with only one, to detect the cycle and abort. Diez -- http://mail.python.org/mailman/listinfo/python-list
socket and thread
I'm writing a small program which uses different threads to monitor an IMAP mailbox and an RSS feed. If network is not available when the program starts, both threads will sleep for a while and try again. It seems that the first thread succeeds when the network becomes available will cause the other thread to always give a gaierror No address associated with hostname. The weird thing is that this only happens when the program starts with network unavailable. If network is available when the program starts, both threads work well, even if the network drops in the middle, the threads can recover properly when the network comes back alive. Is Python socket thread-unsafe or is it because of some other problems? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Delete a Cookie?
On Jan 8, 9:16 am, tryg.ol...@gmail.com wrote: Hello - I managed to get a cookie set. Now I want to delete it but it is not working. Do I need to do another 'set-cookie' in the HTTP header? I tried (code below setting expires to 0) and it didn't work. c = Cookie.SimpleCookie(os.environ[HTTP_COOKIE]) c[mycook][expires] = 0 print c In case its useful, here is how I set my cookie: c = Cookie.SimpleCookie() c[mycook] = Tryg c[mycook][expires] = 60*60*24 c[mycook][comment] = c[mycook][path] = / c[mycook][domain] = c[mycook][secure] = print c Thanks Tryg Well, if you know where the cookie file is stored, you should be able to do this: os.remove(path) Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: python -3 not working as expected
Thorsten Kampe wrote: [Python 2.6.1] Hi, to test existing Python code, I ran python -3 (warn about Python 3.x incompatibilities) against a test file that only contains print 'test'. Unfortunately I saw no warnings about print becoming a function in Python 3 (print()). Where is the problem? I *believe* that's not flagged because 2to3 will fix it automatically. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: formatted 'time' data in calculations
Ross wrote: Scott David Daniels wrote: Ross wrote: There seems to be no shortage of information around on how to use the time module, for example to use time.ctime() and push it into strftime and get something nice out the other side, but I haven't found anything helpful in going the other way. As to a paucity of conversion formatting, there is no magic way to take everyone's way of putting date and time information in text and convert it to unambiguous format, in part because there are too many different and contradictory formats. When I write dates, I know what I intended; when I read dates, I guess what the author intended. Have you read the entire time module document? If so, which functions in that module take strings as arguments? That is, given some formatted text describing times - is there something that makes it easy to calculate time differences, or do I have to index my way through the string pulling out characters, converting to integers etc... Data is formatted: t1 = 09:12:10 t2 = 11:22:14 I want to calculate tdiff = t2-t1 Do you do any work yourself? Show us your attempts. This looks like a trivial exercise. It seems that for less than four times the effort of asking your question you might have found the answer. Perhaps I am being too cranky this morning. Jeeze, you're quite an ass aren't you? And how did sending this message improve things? Let's keep it civil, guys. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Extending Python with C or C++
Nick Craig-Wood schrieb: Thomas Heller thel...@python.net wrote: Nick Craig-Wood schrieb: Interesting - I didn't know about h2xml and xml2py before and I've done lots of ctypes wrapping! Something to help with the initial drudge work of converting the structures would be very helpful. ( http://pypi.python.org/pypi/ctypeslib/ ) I gave it a quick go and it worked fine. I had to edit the XML in one place to make it acceptable (removing a u from a hex number). If you are using a recent version of gccxml, then you should use the ctypeslib-gccxml-0.9 branch of ctypeslib instead of the trunk. (I should really merge the gccxml-0.9 branch into the trunk;-) If you are already using the branch and the XML file is not accepted, then could you please provide a short C code snippet that reproduces the problem so that I can fix it? I'm using gccxml from debian testing 0.9.0+cvs20080525-1 which I guess doesn't have the code from the branch in. I meant the branch in the repository where ctypeslib lives in. Anyway, it doesn't matter anymore since I merged that branch into the ctypeslib trunk. Now the problem with the 'u' suffix that you mentioned should be fixed, and I also made a quick change so that the sized integer types from stdint.h are generated correctly. So, please update your ctypeslib installation and trey again;-) Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: #python IRC help - my internet provider is banned!
I am not a #python operator, but do note that #python is +r so you must be registered and identified to join the channel, see http://freenode.net/faq.shtml#userregistration . Otherwise, giving the exact ban that is affecting you or your hostmask would probably be helpful to the operators. On Wed, Jan 7, 2009 at 1:52 PM, simonh simonharrison...@googlemail.comwrote: On Jan 7, 6:30 pm, Mildew Spores mildew_spo...@hotmail.com wrote: What? Sounds a bit unlikely unless its Virgin.. I'd imagine it might be that your isp needs to get itself off a black list. Brian -- My Hotmail Account mildew_spo...@hotmail.com simonh simonharrison...@googlemail.com wrote in message news:fd0bd7d3-ad1d-43c2-b8e5-642a95c21...@t26g2000prh.googlegroups.com. .. Hi. Not sure if anyone can help here, but I'm trying to access #python and have found out that my ISP has a blanket ban (for some reason). Does anyone know how I can contact an operator to join? Thanks. ISP is bethere and client is Chatzilla. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Delete a Cookie?
tryg.ol...@gmail.com wrote: Hello - I managed to get a cookie set. Now I want to delete it but it is not working. Why struggle with this manually? Isn't it better to learn a bit of framework like Pylons and have it all done for you (e.g. in Pylons you have response.delete_cookie method)? Regards, mk -- http://mail.python.org/mailman/listinfo/python-list
Re: eval('07') works, eval('08') fails, why?
In article hnwdnzhtdblpgvvunz2dnuvz_vzin...@posted.visi, Unknown unkn...@unknown.invalid wrote: On 2009-01-08, Alex van der Spek am...@xs4all.nl wrote: Thanks much, that makes sense! Well, that's the correct explanation. Whether that feature makes sense or not is debatable. The debate is over! In Py 3.0, octal literals changed from 07 to 0o7; the old format gets an 'invalid token' parsing error. -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
ftplib - 226 message not received
I am trying to download a file within a very large zipfile. I need two partial downloads of the zipfile. The first to get the file byte offset, the second to get the file itself which I then inflate. I am implementing the partial downloads as follows: con = ftp.transfercmd('RETR ' + filename, rest_offset) # the data socket while True: block = con.recv(blocksize) # stop transfer while it isn't finished yet if bytes_recv = buf_length: break elif not block: break buf = ''.join([buf, block]) bytes_recv += len(block) con.close() My problem is that even though the socket is closed, I have no way to receive the 226 response from server so I can proceed with the next download. Of course I could close the ftp connection entirely and open a new one, but I am hoping to avoid doing so. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Delete a Cookie?
c[mycook][expires] = 0 Set [expires] using the following format to any time less than current (which causes the browser to delete the cookie). Here's a function I use to return a cookie expiry timestamp, negative values passed in result in cookie being deleted. def cookie_expiry_date(numdays): Returns a cookie expiry date in the required format. -ve value in = kill cookie. `expires` should be a string in the format Wdy, DD-Mon-YY HH:MM:SS GMT NOTE! Must use [expires] because earlier IE versions don't support [max-age]. from datetime import date, timedelta new = date.today() + timedelta(days = numdays) return new.strftime(%a, %d-%b-%Y 23:59:59 GMT) Usage: c[mycook][expires] = cookie_expiry_date(-10) # any negative value will remove cookie HTH, JC -- http://mail.python.org/mailman/listinfo/python-list
Re: del behavior 2
On Jan 7, 3:23 pm, Martin v. Löwis mar...@v.loewis.de wrote: Thanks for the responses. What I mean is when a python process is interrupted and does not get a chance to clean everything up then what is a good way to do so? For instance, I have a script that uses child ptys to facilitate ssh connections (I'm using pxssh). When I ^C the python process I am left with the child processes running and the ssh connections open. Naturally I run out of ttys if this happens too much, which I have had happen. So if python does not get a chance to take care of those, what is a good way to do so? Does a try/finally or a with statement address that? Thanks! That's strange. When the parent process terminates, the tty master should get closed, causing the slave to be closed as well, in addition to sending a SIGHUP signal to the child, which ssh should interpret as terminating. Perhaps the problem is that the master socket *doesn't* get closed? I see that pexpect closes all file descriptors in the child before invoking exec. Could it be that you are starting addition child processes which inherit the master socket? Regards, Martin Thanks. I'll look into that. -eric -- http://mail.python.org/mailman/listinfo/python-list
Re: del behavior 2
On Jan 7, 12:42 pm, Eric Snow es...@verio.net wrote: I was reading in the documentation about __del__ and have a couple of questions. Here is what I was looking at: http://docs.python.org/reference/datamodel.html#object.__del__ My second question is about the following: It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits. I understand that and have seen it too. That's fine. But how do any of you deal with things that are left open because you did not get a chance to close them? How do you clean up after the fact? Do you simply keep track externally the things that need to be cleaned up if __del__ doesn't get a chance? Any ideas? Thanks -eric So I see a couple of options here. Thanks for all the suggestions everyone. Here is what I have: - use try/finally to clean things up - set a handler using signal.signal to clean everything up There is also having try/except for more specific behvaior, like for KeyboardInterrupt, but I am not sure I need that much specificity. Again, thanks for all the great help. Really cleared things up for me. -eric -- http://mail.python.org/mailman/listinfo/python-list
Re: cPickle vs pickle discrepancy
Thanks for your patience waiting for me to isolate the problem. | Package --__init__.py -empty --Package.py -empty --Module.py import cPickle class C(object): pass def fail(): return cPickle.dumps(C(), -1) import Package.Module Package.Module.fail() The failure seems to happen because pickle correctly does an absolute import and cPickle incorrectly relatively imports Package.py and fails to find Module underneath. The package and the module named package was because in there was a main class defined with the same name as the package in that file and Module.py contained support code for the package. -Zac -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer (Digital Overlord) Zindagi Games On Tue, Jan 6, 2009 at 4:57 PM, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Mon, 05 Jan 2009 23:04:30 -0200, Zac Burns zac...@gmail.com escribió: I have a module that attempts to pickle classes defined in that module. I get an error of the form: PicklingError: Can't pickle class 'Module.SubModule.Class': import of module Module.SubModule failed when using cPickle (protocol -1, python version 2.5.1). The module has already been imported and is in sys.modules when the exception is raised. There is no thing as a submodule; very likely you have a package, and a module inside that package. - always import the submodules from the package, not directly (relative imports are safer) - in general, don't play with PYTHONPATH, sys.path, and such things. - don't directly execute a module inside a package (it's name is always __main__ and it doesn't even know it's part of a package). Using pickle instead of cPickle works, but the section of the code is performance critical. Could you provide a short example? I'd say that if you stick to the above rules you won't have the issue again, but anyway I'd like to know in which cases Pickle and cPickle differ. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: ftplib - 226 message not received
Okay, found it on my own. ftp.voidresp() is what is needed, and it does _not_ seem to be in the Python documentation for ftplib. On Jan 8, 1:58 pm, Brendan brendandetra...@yahoo.com wrote: I am trying to download a file within a very large zipfile. I need two partial downloads of the zipfile. The first to get the file byte offset, the second to get the file itself which I then inflate. I am implementing the partial downloads as follows: con = ftp.transfercmd('RETR ' + filename, rest_offset) # the data socket while True: block = con.recv(blocksize) # stop transfer while it isn't finished yet if bytes_recv = buf_length: break elif not block: break buf = ''.join([buf, block]) bytes_recv += len(block) con.close() My problem is that even though the socket is closed, I have no way to receive the 226 response from server so I can proceed with the next download. Of course I could close the ftp connection entirely and open a new one, but I am hoping to avoid doing so. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Delete a Cookie?
On Jan 8, 1:16 pm, Jose C houdinihoun...@gmail.com wrote: c[mycook][expires] = 0 Set [expires] using the following format to any time less than current (which causes the browser to delete the cookie). Here's a function I use to return a cookie expiry timestamp, negative values passed in result in cookie being deleted. def cookie_expiry_date(numdays): Returns a cookie expiry date in the required format. -ve value in = kill cookie. `expires` should be a string in the format Wdy, DD-Mon-YY HH:MM:SS GMT NOTE! Must use [expires] because earlier IE versions don't support [max-age]. from datetime import date, timedelta new = date.today() + timedelta(days = numdays) return new.strftime(%a, %d-%b-%Y 23:59:59 GMT) Usage: c[mycook][expires] = cookie_expiry_date(-10) # any negative value will remove cookie HTH, JC Jose C's piece of code works to delete the cookie as does setting [expires]=0 but ONLY as long as I also set the path. Why is this? So what would be the best way to do this. I tried reading in the existing cookie (b), creating a new cookie (c) with all the same values except for the expires but this did not get my cookie deleted. b = Cookie.SimpleCookie(os.environ[HTTP_COOKIE]) c = Cookie.SimpleCookie() c[cookieName] = b[cookieName].value c[cookieName][expires] = 0 c[cookieName][path]= b[cookieName][path] print c -- http://mail.python.org/mailman/listinfo/python-list
Re: Replying to list messages
Ben Finney wrote: Paul McNett p...@ulmcnett.com writes: But arguing about this here isn't going to change anything: opinions differ just like tabs/spaces and bottom-post/top-post. In cases like this, one side can simply be wrong :-) Best of luck getting your programs behaving as you want them to! BTW, I agree with you that in an ideal, pure world mailing lists wouldn't munge the reply-to field, but when 80% of the people use email clients that don't support reply-list, the practical thing to do as a list admin that wants to avoid having to explain over and over again that your client software is broken is to simply swallow some pride and munge the reply-to. Now, 99% of the users are happy, and the remaining 1% are elite enough to understand how to get around any problems this caused. Happy is good. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: python -3 not working as expected
Steve Holden steve at holdenweb.com writes: Thorsten Kampe wrote: Unfortunately I saw no warnings about print becoming a function in Python 3 (print()). Where is the problem? I *believe* that's not flagged because 2to3 will fix it automatically. This is correct; there's not much point to adding py3k warning for things that 2to3 can fix easily. -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
[Steven's message hasn't reached my server, so I'll reply to it here. Sorry if this is confusing.] Aaron Brady castiro...@gmail.com wrote: On Jan 8, 1:45 am, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Wed, 07 Jan 2009 10:17:55 +, Mark Wooding wrote: The `they're just objects' model is very simple, but gets tied up in knots explaining things. The `it's all references' model is only a little more complicated, but explains everything. But it *over* explains, because it implies things that everybody knows about references in other languages that aren't true for Python. I addressed this elsewhere. Summary: `pass-by-reference' is a different thing to `all you manipulate are references': Python does pass-by-value, but the things it passes -- by value -- are references. (The `pass-by-*' notions are confusingly named anyway. Pass-by-name doesn't actually involve names at all.) Of course it's not literally true that everybody knows that you can use references to implement a swap(x, y) procedure. But people coming from a C or Pascal background tend to assume that everything is like C/Pascal, and there are a lot of them. If C was a rare, unfamiliar language, my opposition to using the term reference would be a lot milder. Maybe in another five years? I agree with the comment about Pascal, but C is actually pretty similar to Python here. C only does pass-by-value. If you want a function to modify your variable, you have to pass a pointer value which points to it. Python has no pointer values, so you need a different hack. The hack usually involves lists. (Though it's easier in the main to return compound data objects like tuples. I don't suppose that a proposal for true multiple return values would go down well here. No, didn't think so...) Okay, the abstraction has leaked again... are the paperweights references to the objects, or the names we've bound objects to? I'm confused... They're the references to the objects. You don't bind names to objects. You bind names slots in which you store references. This discussion -- I'd call it an argument, but that might give the wrong impression, because I think we're being remarkably civil and constructive by the standards of Usenet arguments! -- hasn't started on the topic of variable bindings or environments yet. How do we deal with anonymous objects in your model? -- Steven Mark, hi, Steven, pleasure as always. Hello. ;-) Neither side is perfect or wild; (Do admit it); It's true. How do we decide what is best for newcomers to Python, depending on background? That I really don't know. I'm not good at teaching total beginners (does it show?) because I'm too enmired in the theory. (It doesn't help that I go off on tangents about how language X does something similar but subtly different all the time, though my rich background comes in very useful all over the place and that's something I think is worth sharing.) It probably doesn't help that I came to Python with a thorough understanding of Scheme (among many others) under my belt, because many Scheme concepts carry over directly, including the data model (it's all references) and the variable model (nested, mutable, lexical environments with closures). What I am pretty sure of is that references are going to have to enter the picture at some point, because other models get too complicated. Oh, while I remember: the `distributed Python' model, with auto-updating copies, only works for sharing. Circular structures still require actual references or a Tardis. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it ok to type check a boolean argument?
On Jan 7, 6:21 pm, Scott David Daniels scott.dani...@acm.org wrote: Adal Chiriliuc wrote: On Jan 7, 10:15 pm, Bruno Desthuilliers bdesth.quelquech...@free.quelquepart.fr wrote: ... I'd either keep the argument as a boolean but rename it ascending ... Well, I lied a bit :-p But what if we can't solve it as elegantly, and we need to ... Should we typecheck in this case to ensure that if we pass a string for fast_mode we will raise an exception? Why are you concerned only with type errors on inputs? Even if you could do exhaustive checking of input parameters to make sure they are the only acceptable values, what prevents your user from providing the wrong valid value? What made you pick on type errors in the first place? If it turns out that an argument of 422 is a typo for 42, why is that less of a problem? Just because you are used to systems where one kind of error is always caught does not really make you invulnerable. You'll have no problem telling your users that the 422 is their fault. Why do you have such certainty that passing in nonsense as a boolean is a failure you need to deal with? I'm going to play Devil's Advocate here. The motivation here is not we want type safety but our unit tests can't register this deliberate error because it passes silently. Presumably if they had a function that accepted integers, and 442 was an invalid value, and the function failed silently in a unit test, they would also consider whether it should instead fail loudly. It's always a judgment call how much to screen for bad input, but type errors aren't different from any other error in this regard. Sometimes it's appropriate (note: not, IMHO, in this case), just like it's sometimes appropriate to check for 442. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list