Re: why doesn't pop/clear call __delitem__ on a dict?
On Wed, Dec 10, 2008 at 11:53 PM, Daniel Fetchinson [EMAIL PROTECTED] wrote: I just found out that if I want to have a custom dict it's not enough to overload __getitem__, __setitem__ and __delitem__ because, for example, pop and clear don't call __delitem__. I.e. an instance of the following will not print 'deleted' upon instance.pop( 'key' ): class mydict( dict ): def __setitem__( self, key, value ): print 'set' super( mydict, self ).__setitem__( key, value ) def __getitem__( self, key ): print 'get' super( mydict, self ).__getitem__( key ) def __delitem__( self, key ): print 'deleted' super( mydict, self ).__delitem__( key ) Why is this? For optimization purposes essentially, so that the built-in dict can be as fast as possible as it is used pervasively in Python. what other methods do I have to overload so that I get what I expect for all dict operations? You might consider just subclassing UserDict.DictMixin instead: http://docs.python.org/library/userdict.html#UserDict.DictMixin It implements the complete dict interface all in terms of provided __getitem__(), __setitem__(), __delitem__(), and keys() methods. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com Cheers, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
On Wed, 10 Dec 2008 17:58:49 -0500, Luis Zarrabeitia wrote: On Sunday 07 December 2008 09:21:18 pm Robert Kern wrote: The deficiency is in the feature of rich comparisons, not numpy's implementation of it. __eq__() is allowed to return non-booleans; however, there are some parts of Python's implementation like list.__contains__() that still expect the return value of __eq__() to be meaningfully cast to a boolean. list.__contains__, tuple.__contains__, the 'if' keyword... How do can you suggest to fix the list.__contains__ implementation? I suggest you don't, because I don't think it's broken. I think it's working as designed. It doesn't succeed with arbitrary data types which may be broken, buggy or incompatible with __contain__'s design, but that's okay, it's not supposed to. Should I wrap all my ifs with this?: if isinstance(a, numpy.array) or isisntance(b,numpy.array): res = compare_numpy(a,b) elif isinstance(a,some_otherclass) or isinstance(b,someotherclass): res = compare_someotherclass(a,b) ... else: res = (a == b) if res: # do whatever No, inlining that code everywhere you have an if would be stupid. What you should do is write a single function equals(x, y) that does precisely what you want it to do, in whatever way you want, and then call it: if equals(a, b): Or, put your data inside a wrapper. If you read back over my earlier posts in this thread, I suggested a lightweight wrapper class you could use. You could make it even more useful by using delegation to make the wrapped class behave *exactly* like the original, except for __eq__. You don't even need to wrap every single item: def wrap_or_not(obj): if obj in list_of_bad_types_i_know_about: return EqualityWrapper(obj) return obj data = [1, 2, 3, BadData, 4] data = map(wrap_or_not, data) It isn't really that hard to deal with these things, once you give up the illusion that your code should automatically work with arbitrarily wacky data types that you don't control. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: if expression source format
Lambert, David W (ST) [EMAIL PROTECTED] wrote: The if expression leads to long statements. Please offer suggestions to beautify this function. For this example use maximum line length marked by the 's. Thank you. ## def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, mph')-'dF': ''' http://www.erh.noaa.gov/er/iln/tables.htm#heat index ''' return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T 40 else T If the expression is too long for your liking then just don't use the an if expression: if T 40: return whatever else: return T is probably easier to read. -- http://mail.python.org/mailman/listinfo/python-list
Re: if expression source format
On Thu, 11 Dec 2008 02:07:54 -0500, Lambert, David W (ST) wrote: The if expression leads to long statements. Please offer suggestions to beautify this function. For this example use maximum line length marked by the 's. Thank you. ## def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, mph')-'dF': ''' http://www.erh.noaa.gov/er/iln/tables.htm#heat index ''' return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T 40 else T Firstly, you don't need compute. Every function computes. Secondly, fix the spelling of temperature. Thirdly, we can make it easier to read by spreading it out. ## def wind_chill_temperature( T:'Temperature, dF',s:'Wind speed, mph')-'dF': 'http://www.erh.noaa.gov/er/iln/tables.htm#heat index' if T 40: return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) else: return T There is no shortage of newlines. They are a renewable resource, don't be afraid to use a couple of extra lines to make your code more readable. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Why optimization mode is slower than normal mode?
Hi all, I'm using python 2.6 in a windows xp box, when I try pystone, I get: C:\Python26\Lib\testpython pystone.py 50 Pystone(1.1) time for 50 passes = 5.93632 This machine benchmarks at 84227.3 pystones/second C:\Python26\Lib\testpython -OO pystone.py 50 Pystone(1.1) time for 50 passes = 6.00515 This machine benchmarks at 83261.8 pystones/second I tried many times, and get the same result. Why optimization mode is slower than normal mode? -- Best Regards, Leo Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: why doesn't pop/clear call __delitem__ on a dict?
I just found out that if I want to have a custom dict it's not enough to overload __getitem__, __setitem__ and __delitem__ because, for example, pop and clear don't call __delitem__. I.e. an instance of the following will not print 'deleted' upon instance.pop( 'key' ): class mydict( dict ): def __setitem__( self, key, value ): print 'set' super( mydict, self ).__setitem__( key, value ) def __getitem__( self, key ): print 'get' super( mydict, self ).__getitem__( key ) def __delitem__( self, key ): print 'deleted' super( mydict, self ).__delitem__( key ) Why is this? For optimization purposes essentially, so that the built-in dict can be as fast as possible as it is used pervasively in Python. what other methods do I have to overload so that I get what I expect for all dict operations? You might consider just subclassing UserDict.DictMixin instead: http://docs.python.org/library/userdict.html#UserDict.DictMixin It implements the complete dict interface all in terms of provided __getitem__(), __setitem__(), __delitem__(), and keys() methods. Thanks a lot! -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
Xah Lee wrote: On Dec 10, 2:47 pm, John W Kennedy [EMAIL PROTECTED] wrote: Xah Lee wrote: In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. [...] Thanks to various replies. I've now gather code solutions in ruby, python, C, Java, here: • A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html now lacking is perl, elisp, which i can do well in a condensed way. It'd be interesting also to have javascript... mmm, stone soup... javascript: var map = function(fn, a) { var b = new Array(a.length); for (i = 0; i a.length; i++) { b[i] = fn(a[i]); } return b }; var reduce = function(fn, a, init) { var s = init; for (i = 0; i a.length; i++) { s = fn(s, a[i]); } return s }; var sum = function(a) { return reduce(function(x, y) { return x + y }, a, 0.0) }; var norm = function(a) { var pow = Math.pow; return Math.sqrt(sum(map(function(x) { return pow(x, 2) }, a))) }; var Unit = function(a) { var N = norm(a); return map(function(x) { return x/N }, a) }; -- http://mail.python.org/mailman/listinfo/python-list
Re: SequenceMatcher bug ?
Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 10 Dec 2008 15:14:20 -0200, eliben [EMAIL PROTECTED] escribió: What ? This can't be. 1. Go to http://try-python.mired.org/ 2. Type import difflib 3. Type difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() Don't you get 0 as the answer ? Ah, but that isn't the same expression you posted originally: SequenceMatcher(None, [4] + [10] * 500 + [5], [10] * 500 + [5]).ratio() Using *that* expression I got near 1.0 always. But leaving out the [5] at the end, it's true, it gives the wrong answer. ... I've updated the tracker item. Your assessment that it is the same problem as #1528074 is correct. It's the popularity optimization. The key here is that the second sequence consists of more than 200 identical items. For example, all of the following give the same bad result: difflib.SequenceMatcher(None, [4] + [5] * 200, [5] * 200).ratio() difflib.SequenceMatcher(None, [4] + [5] , [5] * 200).ratio() difflib.SequenceMatcher(None, [4], [5] * 200).ratio() If you print get_matching_blocks(), you'll see that there are none, because the b sequence is optimized completely away. The #1528074 calls it working by designed and suggests updating the doc. However, I would argue that it's worth checking for this. -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory leak when using a C++ module for Python
Jaume Bonet wrote: When I test the code from C++ each time I delete a vector the consumed memory decreases, but it does not happen when the module is called from python. What is a vector for you? Do you mean std::vector? A vector allocated using malloc()? A vector allocated using new? Just provide a simple piece of C++ and Python example code that demonstrates the problem and you will probably get help immediatel. I've read that the even when you delete the content of the vectors the memory is not freed when you are working with python. Is that so? There are things like that, but without context it's pretty hard to tell what's going on. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
if expression source format
The if expression leads to long statements. Please offer suggestions to beautify this function. For this example use maximum line length marked by the 's. Thank you. ## def compute_wind_chill_temperture(T:'Temperature, dF',s:'Wind speed, mph')-dF: ''' http://www.erh.noaa.gov/er/iln/tables.htm#heat index ''' return 35.74 + 0.6215*T + s**0.16*(T*0.4275-35.75) if T 40 else T -- http://mail.python.org/mailman/listinfo/python-list
Re: trace module and doctest
On Nov 22 2007, 4:31 pm, [EMAIL PROTECTED] (John J. Lee) wrote: [EMAIL PROTECTED] writes: I am trying to use thetracemodulewith the --count flag to test for statement coverage in my doctests. Thetracecoverage listing is very weird, marking many statements as unexecuted which were clearly executed during the run (I can see their output on the screen). Is this some known interaction between thetraceanddoctestmodules? Yes: http://python-nose.googlecode.com/svn/trunk/nose/plugins/doctests.py http://svn.zope.org/Zope3/trunk/src/zope/testing/doctest.py?rev=28679... John Interesting. Is this problem caused or ascerbated by the fact that sys.settrace() is this sort of global? I've been looking at redoing pdb from scratch, from the bottom up. As Obama might say in a different context, line by line. I sort of don't like the global-ness of pdb, or for that matter the sys.settrace's trace hook. So as a start, I wrote a tracer module (http://code.google.com/p/pytracer/ and on Pypi) which just a wrapper around the global trace hook to allow different applications to register trace events and not clobber one-another. Possibly in an Ideal world, Python would itself have done the trace hook chaining. (I believe that the case in Ruby ;-) But Python 2.6 does now allow you *query* to find out if a trace hook has been installed, chaining so it is now possible, even though tracer doesn't use the 2.6 sy.gettrace () to allow it chain outside of routines that use it directly. But as I wonder if this kind of problem would have been avoided if there had been a wrapper to allow settrace chaining? (And if that is s -- unlikely as it is to happen -- various applications like tracer, doctest and pdb could be rewritten to use tracer.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of 'wget' for python?
Hi Please excuse my OOP but is my understanding correct urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) is urllib ---Static Class on which the method urlretrieve method is invoked ? In that case what does the python 3.0 version mean import urllib.request urllib.request.urlretrieve(url, local_file_name) urllib --static class request --method urlretrieve-- what is this then ? regards Hrishy --- On Mon, 8/12/08, Jerry Hill [EMAIL PROTECTED] wrote: From: Jerry Hill [EMAIL PROTECTED] Subject: Re: Equivalent of 'wget' for python? To: python-list@python.org Date: Monday, 8 December, 2008, 5:54 PM On Mon, Dec 8, 2008 at 11:53 AM, r0g [EMAIL PROTECTED] wrote: urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem). In python 3.0, that appears to be: import urllib.request urllib.request.urlretrieve(url, local_file_name) -- Jerry -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Deeper tracebacks?
brooklineTom [EMAIL PROTECTED] writes: I want my exception handler to report the method that originally raised an exception, at the deepest level in the call-tree. Let give an example. import sys, traceback class SomeClass: def error(self): Raises an AttributeError exception. int(3).zork() def perform_(self, aSelector): try: aMethod = getattr(self, aSelector, None) answer = apply(aMethod, [], {}) except: AttributeError, anAttributeErrorException: aRawStack = traceback.extract_stack() answer = None When I call perform_ (... SomeClass().perform_('error')), I want to collect and report the location *within the method (error) that failed*. The above code reports the location of perform_, and no deeper in the call tree. Anybody know how to accomplish this? extract_stack() without any arguments is getting this from the *current frame* which as you noted doesn't have the last exception info included which has been popped; variable sys.last_traceback has the frames at the time of the exception, I think. So in your code try changing: aRawStack = traceback.extract_stack() to aRawStack = traceback.extract_stack(sys.last_traceback) -- http://mail.python.org/mailman/listinfo/python-list
Py_GetPath() C API in python 3
Hi all, I want to build a new, requires total control, python interpreter. So I implement my own version of Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix() and Py_GetProgramFullPath(). When compiling, I always get error messages, for each API function, look like followings: /opt/python-3.0/lib/python3.0/config/libpython3.0.a(getpath.o)(.text +0x211c): In function `Py_GetPath': ./Modules/getpath.c:739: multiple definition of `Py_GetPath' myApp.o(.text+0x0):/home/alex/workspace/develop/src/myApp.c:11: first defined here /usr/bin/ld: Warning: size of symbol `Py_GetPath' changed from 126 in system.o to 32 in /opt/python-3.0/lib/python3.0/config/libpython3.0.a (getpath.o) collect2: ld returned 1 exit status If I compile my application with python 2.x, everything's just okay and my application as well. Any ideas on how to get this working for python 3? -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of 'wget' for python?
On Dec 11, 7:36 pm, hrishy [EMAIL PROTECTED] wrote: urllib --static class request --method urlretrieve-- what is this then ? The easiest way is to check for yourself, using type(). So 'type(urllib)' should give you 'type 'module'' (assuming the same types as 2.5, I don't have an install of 3.0 handy atm). My guess is 'type(urllib.request)' will be the same, and 'type (urllib.request.urlretrieve)' will be 'type 'function''. 'urllib' is a module, or most likely in this case a package, which is a folder that can be treated as a module. It contains another module, 'request', which has inside the function 'urlretrieve'. Modules packages are a handy language feature for placing functionality into namespaces. The documentation is worth checking out: http://docs.python.org/3.0/tutorial/modules.html -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.settrace 'call' event behavior
On Jun 21, 8:47 am, Michal Kwiatkowski [EMAIL PROTECTED] wrote: I'm building a tool to trace all function calls usingsys.settrace function from the standard library. One of the awkward behaviors of this facility is that the class definitions are reported as 'call' events.[1] Since I don't want to catch class definitions, only function calls, I'm looking for a way to differentiate between those two. So far I have only vague clues about how to do that. At the bottom of this mail is a simple script that prints all attributes (except for the bytecode) of the traced code. In the sample code Bar class is defined and foo function is called after that. The following trace output is reported: Bar, 0, 0, (), (), (), (None,), ('__name__', '__module__', 'None'), foo.py, 21, , 1, 66 foo, 0, 0, (), (), (), (None,), (), foo.py, 25, , 1, 67 Class definition and functioncalldiffers on four attributes. Two of them, co_name and co_firstlineno are not very helpful. Other two are co_names and co_flags. The latter differs only by the CO_OPTIMIZED flag, which is for internal use only[2]. So we're left with co_names, which is a tuple containing the names used by the bytecode. Is that helpful in distinguishing between class definitions and function calls? Do you have any other ideas on how to tell them apart? Source of the sample script I used follows. def trace(frame,event, arg): ifevent== 'call': print ', '.join(map(str, [frame.f_code.co_name, frame.f_code.co_argcount, frame.f_code.co_nlocals, frame.f_code.co_varnames, frame.f_code.co_cellvars, frame.f_code.co_freevars, frame.f_code.co_consts, frame.f_code.co_names, frame.f_code.co_filename, frame.f_code.co_firstlineno, frame.f_code.co_lnotab, frame.f_code.co_stacksize, frame.f_code.co_flags])) return trace import syssys.settrace(trace) class Bar(object): None pass def foo(): pass foo() [1] It is strange for me, but documented properly.http://docs.python.org/lib/debugger-hooks.htmlsays thatcallevent happens when a function is called (or some other code block entered). [2]http://docs.python.org/ref/types.html#l2h-145 Cheers, mk Perhaps you could filter based on the type of the frame.f_code.co_name ? e.g. or type(eval(frame.f_code.co_name)) (Sorry for the delayed reply - I don't generally read the newsgroup and stumbled across this looking for something else. But I noticed no replies, so...) -- http://mail.python.org/mailman/listinfo/python-list
Custom debugger trace hooks
A colleague recently asked this: Is there a cleaner way to dump a trace/track of running a python script. With Pydb I made work-around with import pydb pydb.debugger(dbg_cmds=['bt', 'l', 's']*300 + ['c']) So now I have a dump of 300 steps with backtraces, so I can easily compare two executions of the same script to find where they diverged. I think it is a really nice feature. pydb and pdb inherit from the cmd module which does allow pre- and post-command hooks. Neither pdb nor pydb make it easy to add one's own hook. However If there's something you want to run before stepping you can do that by monkey-patching Pdb.precmd: snip import pydb def myprecmd(obj, debug_cmd): Custom Hook method executed before issuing a debugger command. global _pydb_trace obj.do_list('') obj.do_where('10') # limit stack to at most 10 entries return obj.old_precmd(debug_cmd) # is always string 's' in example below _pydb_trace = pydb.Pdb() pydb.Pdb.old_precmd = pydb.Pdb.precmd pydb.Pdb.precmd = myprecmd pydb.debugger(dbg_cmds=['s'] * 30) # I believe the same is applicable to pdb, although I haven't investigated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of 'wget' for python?
On Dec 11, 2:36 pm, hrishy [EMAIL PROTECTED] wrote: Hi Please excuse my OOP but is my understanding correct urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) is urllib ---Static Class on which the method urlretrieve method is invoked ? No urllib is a method. Use type(obj) to find out what python thinks the type of that object is. Note that object here is not meant in the same sense as the OOP definition. In that case what does the python 3.0 version mean import urllib.request urllib.request.urlretrieve(url, local_file_name) urllib --static class request --method urlretrieve-- what is this then ? A 'function'. urllib.request.urlretrieve is the fully qualified name of the function urlretrieve. In other words urlretrieve lives in the urllib.request namespace. -srp regards Hrishy --- On Mon, 8/12/08, Jerry Hill [EMAIL PROTECTED] wrote: From: Jerry Hill [EMAIL PROTECTED] Subject: Re: Equivalent of 'wget' for python? To: [EMAIL PROTECTED] Date: Monday, 8 December, 2008, 5:54 PM On Mon, Dec 8, 2008 at 11:53 AM, r0g [EMAIL PROTECTED] wrote: urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem). In python 3.0, that appears to be: import urllib.request urllib.request.urlretrieve(url, local_file_name) -- Jerry -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of 'wget' for python?
On Dec 11, 3:36 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: On Dec 11, 2:36 pm, hrishy [EMAIL PROTECTED] wrote: Hi Please excuse my OOP but is my understanding correct urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) is urllib ---Static Class on which the method urlretrieve method is invoked ? No urllib is a method. Use type(obj) to find out what python thinks typo c/method/module the type of that object is. Note that object here is not meant in the same sense as the OOP definition. In that case what does the python 3.0 version mean import urllib.request urllib.request.urlretrieve(url, local_file_name) urllib --static class request --method urlretrieve-- what is this then ? A 'function'. urllib.request.urlretrieve is the fully qualified name of the function urlretrieve. In other words urlretrieve lives in the urllib.request namespace. -srp regards Hrishy --- On Mon, 8/12/08, Jerry Hill [EMAIL PROTECTED] wrote: From: Jerry Hill [EMAIL PROTECTED] Subject: Re: Equivalent of 'wget' for python? To: [EMAIL PROTECTED] Date: Monday, 8 December, 2008, 5:54 PM On Mon, Dec 8, 2008 at 11:53 AM, r0g [EMAIL PROTECTED] wrote: urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem). In python 3.0, that appears to be: import urllib.request urllib.request.urlretrieve(url, local_file_name) -- Jerry -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of 'wget' for python?
Hi Saju Thanks for helping the oop challenged regards Hrishy --- On Thu, 11/12/08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: From: [EMAIL PROTECTED] [EMAIL PROTECTED] Subject: Re: Equivalent of 'wget' for python? To: python-list@python.org Date: Thursday, 11 December, 2008, 10:41 AM On Dec 11, 3:36 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: On Dec 11, 2:36 pm, hrishy [EMAIL PROTECTED] wrote: Hi Please excuse my OOP but is my understanding correct urllib.urlretrieve(url_of_zip_file,destination_on_local_filesystem) is urllib ---Static Class on which the method urlretrieve method is invoked ? No urllib is a method. Use type(obj) to find out what python thinks typo c/method/module the type of that object is. Note that object here is not meant in the same sense as the OOP definition. In that case what does the python 3.0 version mean import urllib.request urllib.request.urlretrieve(url, local_file_name) urllib --static class request --method urlretrieve-- what is this then ? A 'function'. urllib.request.urlretrieve is the fully qualified name of the function urlretrieve. In other words urlretrieve lives in the urllib.request namespace. -srp regards Hrishy --- On Mon, 8/12/08, Jerry Hill [EMAIL PROTECTED] wrote: From: Jerry Hill [EMAIL PROTECTED] Subject: Re: Equivalent of 'wget' for python? To: [EMAIL PROTECTED] Date: Monday, 8 December, 2008, 5:54 PM On Mon, Dec 8, 2008 at 11:53 AM, r0g [EMAIL PROTECTED] wrote: urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem). In python 3.0, that appears to be: import urllib.request urllib.request.urlretrieve(url, local_file_name) -- Jerry -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of 'wget' for python?
On Tue, Dec 9, 2008 at 12:22 AM, Robert Dailey [EMAIL PROTECTED] wrote: Hi, I'm looking for a portable way to download ZIP files on the internet through Python. I don't want to do os.system() to invoke 'wget', since this isn't portable on Windows. I'm hoping the core python library has a library for this. Note that I'll be using Python 3.0. You can get Wget for Windows here: http://gnuwin32.sourceforge.net/packages/wget.htm -- Best Regards, Leo Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
John W Kennedy wrote: Xah Lee wrote: In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. Java: static float[] normal(final float[] x) { float sum = 0.0f; for (int i = 0; i x.length; ++i) sum += x[i] * x[i]; final float divisor = (float) Math.sqrt(sum); float[] a = new float[x.length]; for (int i = 0; i x.length; ++i) a[i] = x[i]/divisor; return a; } We don't need no stinkin' loops! SpiderMonkey Javascript: function normal( ary ) { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) return ary.map(function(x) x/div) } -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
William James wrote: John W Kennedy wrote: Xah Lee wrote: In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. Java: static float[] normal(final float[] x) { float sum = 0.0f; for (int i = 0; i x.length; ++i) sum += x[i] * x[i]; final float divisor = (float) Math.sqrt(sum); float[] a = new float[x.length]; for (int i = 0; i x.length; ++i) a[i] = x[i]/divisor; return a; } We don't need no stinkin' loops! SpiderMonkey Javascript: function normal( ary ) { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) return ary.map(function(x) x/div) } The variable div shouldn't be global. function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } -- http://mail.python.org/mailman/listinfo/python-list
Re: broken ncurses on python 3.0
icarus wrote: OS: win32, python 3.0 I've been trying to run some curses demos and I get this: C:\Python\Lib\cursespython textpad.py Traceback (most recent call last): File textpad.py, line 3, in module import curses File C:\Python\lib\curses\__init__.py, line 15, in module from _curses import * ImportError: No module named _curses The C:\Python\include does not have the curses.h header. Reinstalling from the x86 msi binary doesn't do it. Any ideas on how to get this working? maybe it's just the w32 version that missed ncurses The Windows binaries doesn't have and never had an ncurses extension. The extension doesn't suport ncurses on Windows at all - in all versions of Python. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Dec 10, 3:42 pm, cm_gui [EMAIL PROTECTED] wrote: http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... I fully agree with Krzysztof Kowalczyk . Can't they build a faster VM for Python since they love the language so much? Python is SLOW. And I am not comparing it with compiled languages like C. Python is even slower than PHP! Just go to any Python website and you will know. An example is:http://www2.ljworld.com/ And this site is created by the creators of Django! And it is not just this Python site that is slow. There are many many Python sites which are very slow. And please don’t say that it could be the web hosting or the server which is slow — because when so many Python sites are slower than PHP sites, it couldn’t be the web hosting. Also, Zope/Plone is even slower. Python is slow. Very slow. Now seriously, just to finish your idiotic rant, check the Pypy project: http://codespeak.net/pypy http://morepypy.blogspot.com And if you still think this is not enough, why don't you help these guys to make it faster? Luis -- http://mail.python.org/mailman/listinfo/python-list
Converting c header file to a python file
Hello, I am looking for a tool/utility by which can convert c header file to a python file. A typical header file that I want convert looks like: #ifndef __VAR1 #define __VAR1 #define VAR2 Rev 2 #define VAR3 2L typedef struct { } #if defined(__cplusplus) || defined(__cplusplus__) extern C { #endif And also function declarations Thanks, Tarun -- http://mail.python.org/mailman/listinfo/python-list
ctypes and misaligned doubles
Dear python experts, How can I change the alignment of types in the ctypes package? I have a library that was built with gcc using the -malign-double option. I also have python code that can create ctypes wrapper code from the include files for that library. The problem is that structs that contain fields of type double are not correctly wrapped half of the time. This is because ctypes assumes an alignment of 4 (on a 32-bit platform) for the double type, while the library I'm wrapping uses an alignment of 8 for these doubles. Is there a way to change the alignment of a ctypes type without recompiling the whole ctypes package? If I can't change it, is there a way to define my own type based on c_double but with a different alignment? Regards, Jan -- http://mail.python.org/mailman/listinfo/python-list
Python, threading
Hy. I have a problem! I'm making multi thread application (client, server) using wxPython for GUI, and threading.Thread for threding. Clients connect and when they are connected (evry thread handles one connection) threads change main window. I neded tip how to make communication between threeds. -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes and misaligned doubles
Jan Roelens schrieb: Dear python experts, How can I change the alignment of types in the ctypes package? I have a library that was built with gcc using the -malign-double option. I also have python code that can create ctypes wrapper code from the include files for that library. The problem is that structs that contain fields of type double are not correctly wrapped half of the time. This is because ctypes assumes an alignment of 4 (on a 32-bit platform) for the double type, while the library I'm wrapping uses an alignment of 8 for these doubles. To force an alignment that is smaller than the native alignment, you can use the _pack_ attribute in your Structure definitions. http://docs.python.org/library/ctypes.html?highlight=_pack_#ctypes.Structure._pack_ To force an alignment that is larger than the native alignment, you must use padding. Is there a way to change the alignment of a ctypes type without recompiling the whole ctypes package? If I can't change it, is there a way to define my own type based on c_double but with a different alignment? No. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: var or inout parm?
Joe Strout a écrit : On Dec 10, 2008, at 4:29 PM, J. Clifford Dyer wrote: [EMAIL PROTECTED] wrote: How can I make a var parm, where the called function can modify the value of the parameter in the caller? See Also: the earlier heated debate thread over what evaluation strategy Python uses (Survey says!: call-by-object). Oh dear God. PLEASE don't see also that thread. That way lies madness. Just google for call-by-object, and ignore the hell out of that thread. Agreed on that point! Anyway, to the OP, see http://www.strout.net/info/coding/valref/ Do you really want to start a new flame war, Joe ?-) -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I manually uninstall setuptools (installed by egg)?
David Cournapeau [EMAIL PROTECTED] wrote: On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert [EMAIL PROTECTED] wrote: On Tue, Dec 9, 2008 at 6:49 PM, [EMAIL PROTECTED] wrote: On Ubuntu, I accidentally manually installed setuptools http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file as a shell script via sudo), and now realize I should just be using apt to take care of my system Python packages. Really, why? setuptools has more Python packages/programs available and updates faster than Debian. It's also likely that some of the Debian Python packages are installed using setuptools anyway. So, why do you think apt and not setuptools is The Right Way(tm)? Setuptools is certainly not the right way to install packages system-wide on debian, it is very likely to break the whole thing. It wouldn't be too difficult to make a .deb target which would collect all the files that did get installed into a package. It would be a rather rough and ready package but would do the job. The .deb would then be uninstallable in the usual (dpkg --purge) way. Did anyone think about that? There is a bdist_rpm target for distutils which I often use then use alien to turn into a .deb. easy_install is a lot easier though! dpkg is a real package installer, with uninstallation feature, correct dependency handling: if you start installing things with setuptools there, dpkg cannot know anymore how to manage your system. Agreed. That's why it is generally a very bad idea to install things which are not managed by dpkg in /usr - be it python or something else BTW. It is a much better practice to install from source into /usr/local, or your $HOME, etc... Anywhere which is not /usr. easy_install can do that I think... I find it odd that easy_install doesn't have a) a list what you installed with easy_install b) uninstall in an otherwise excellent program. -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: looking up function's doc in emacs
Xah Lee wrote: in programing elisp in emacs, i can press “Ctrl+h f” to lookup the doc for the function under cursor. is there such facility when coding in perl, python, php? (i'm interested in particular python. In perl, i can work around with “perldoc -f functionName”, and in php it's php.net/functionName. Both of which i have a elisp command with a shortcut that let me jump to the doc) Thanks. Xah ∑ http://xahlee.org/ ☄ python help(FUNCTIONNAME) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, threading
On Dec 11, 6:06 pm, SMALLp [EMAIL PROTECTED] wrote: Hy. I have a problem! I'm making multi thread application (client, server) using wxPython for GUI, and threading.Thread for threding. Clients connect and when they are connected (evry thread handles one connection) threads change main window. I neded tip how to make communication between threeds. Threads already share data your problem would likely be to synchronize the threads - threading.Sempahore threading.Lock will help Maybe you want some threads to wait while other thread(s) do some work ? - threading.Event threading.Condition The documentation on threading module is where you should start. -srp -- http://saju.net.in -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ]
On Dec 11, 4:45 am, John Machin [EMAIL PROTECTED] wrote: On Dec 11, 9:49 am, Explore_Imagination [EMAIL PROTECTED] wrote: Hi all I am new to C and python ... I want to convert C data type uint64 variable into the Python 32bit Object. I am currently using Python 2.2 [ It is necessary to use it ] Kindly give your suggestion how and in which way I can achieve this task. I'm not sure what you mean by the Python 32bit Object. A Python int object holds a signed 32-bit integer. A Python long object holds a signed integer of arbitrary size. You will need to convert your uint64 into a Python long; then, if necessary, check that the result will fit in an int (result = sys.maxint). If the C variable is in an 8-byte string that you have read from a file, the unpack function in the struct module will do the job. Assuming your computer is little-endian: maxu64 = '\xff' * 8 # example input string import struct result = struct.unpack('Q', maxu64)[0] result 18446744073709551615L 2 ** 64 - 1 18446744073709551615L If however you mean that in C code you need to build a Python object to pass over to Python code: According to the Python/C API Reference Manual (http://www.python.org/doc/2.2.3/api/longObjects.html): PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) Return value: New reference. Returns a new PyLongObject object from a C unsigned long long, or NULL on failure. If however you mean something else, HTH, John Thanks for your feedback ... Actually I want to pass unit64 variable in C to python but at the same time I want to have a generic code which should work on both little-endian and big endian architectures Any suggestions ? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert uint64 in C into Python 32bit Object [ I am using Python2.2 ]
On Dec 11, 6:45 pm, Explore_Imagination [EMAIL PROTECTED] wrote: On Dec 11, 4:45 am, John Machin [EMAIL PROTECTED] wrote: On Dec 11, 9:49 am, Explore_Imagination [EMAIL PROTECTED] wrote: Hi all I am new to C and python ... I want to convert C data type uint64 variable into the Python 32bit Object. I am currently using Python 2.2 [ It is necessary to use it ] Kindly give your suggestion how and in which way I can achieve this task. I'm not sure what you mean by the Python 32bit Object. A Python int object holds a signed 32-bit integer. A Python long object holds a signed integer of arbitrary size. You will need to convert your uint64 into a Python long; then, if necessary, check that the result will fit in an int (result = sys.maxint). If the C variable is in an 8-byte string that you have read from a file, the unpack function in the struct module will do the job. Assuming your computer is little-endian: maxu64 = '\xff' * 8 # example input string import struct result = struct.unpack('Q', maxu64)[0] result 18446744073709551615L 2 ** 64 - 1 18446744073709551615L If however you mean that in C code you need to build a Python object to pass over to Python code: According to the Python/C API Reference Manual (http://www.python.org/doc/2.2.3/api/longObjects.html): PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) Return value: New reference. Returns a new PyLongObject object from a C unsigned long long, or NULL on failure. If however you mean something else, HTH, John Thanks for your feedback ... Actually I want to pass unit64 variable in C to python but at the same time I want to have a generic code which should work on both little-endian and big endian architectures Any suggestions ? I am not sure if endianness comes into the picture. As long as sizeof (uint64) == sizeof(unsigned long long) on your platform, python should have no problem accepting the return value of PyLong_FromUnsignedLongLong(uint64_var); srp -- http://saju.net.in -- http://mail.python.org/mailman/listinfo/python-list
just got the g1
Hi Just got the G1, is their any way to get python running on the andriod platform ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, threading
SMALLp wrote: Hy. I have a problem! I'm making multi thread application (client, server) using wxPython for GUI, and threading.Thread for threding. Clients connect and when they are connected (evry thread handles one connection) threads change main window. I neded tip how to make communication between threeds. Are you aware that mixing multi-threading and GUIs usually not works the naive way? Read up on your toolkits documentation how to deal with multi-threading. Diez -- http://mail.python.org/mailman/listinfo/python-list
How can I understan the for here?
Hello all, look at the following sentence: params = {server:mpilgrim, database:master, uid:sa, pwd:secret} [%s=%s % (k, v) for k, v in params.items()] ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] I can't understand the second sentence because of the for ... in. I consider that the syntactics of for should be: for k,v in params.items(): .. But there's no a colon here, why it can work? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I understan the for here?
Kermit I can't understand the second sentence because of the for Kermit ... in. Google for python list comprehensions. -- Skip Montanaro - [EMAIL PROTECTED] - http://smontanaro.dyndns.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I understan the for here?
On Fri, Dec 12, 2008 at 12:44 AM, Kermit Mei [EMAIL PROTECTED] wrote: I can't understand the second sentence because of the for ... in. I consider that the syntactics of for should be: for k,v in params.items(): .. But there's no a colon here, why it can work? It's called a list comprehension. The for x in y construct becomes an expression. Simple example: Build a list of integers divisible by 3: [x for x in xrange(10) if not x % 3] [0, 3, 6, 9] cheers James -- -- -- Problems are solved by method -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
On Dec 11, 4:53 pm, William James [EMAIL PROTECTED] wrote: William James wrote: John W Kennedy wrote: Xah Lee wrote: In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. Java: static float[] normal(final float[] x) { float sum = 0.0f; for (int i = 0; i x.length; ++i) sum += x[i] * x[i]; final float divisor = (float) Math.sqrt(sum); float[] a = new float[x.length]; for (int i = 0; i x.length; ++i) a[i] = x[i]/divisor; return a; } We don't need no stinkin' loops! SpiderMonkey Javascript: function normal( ary ) { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) return ary.map(function(x) x/div) } The variable div shouldn't be global. function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } Chicken Scheme: (require 'srfi-1) (define (norm vec) (map (cute / (sqrt (reduce + 0 (map (cute expt 2) vec vec)) Cute huh? ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to pass out the result from iterated function
On Dec 10, 2:25 pm, eric [EMAIL PROTECTED] wrote: On Dec 10, 9:16 pm, JD [EMAIL PROTECTED] wrote: I got a iterated function like this: def iterSomething(list): has_something = False for cell in list: if something in cell: has_something = True output = something if has_something: iterSomething(output) else: final_out = outupt The problem is how can I read this final_out outside of the function. I tried the global statement, it seems not work. Any idea? JD Thanks, I tried to return the last result. It's not working. Your code works, thanks why don't you just return it ? def iterSomething(list): has_something = False for cell in list: if something in cell: has_something = True output = something if has_something: return iterSomething(output) else: return output ? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I understan the for here?
On Thu, 11 Dec 2008 22:44:20 +0800 Kermit Mei [EMAIL PROTECTED] wrote: [%s=%s % (k, v) for k, v in params.items()] ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] I can't understand the second sentence because of the for ... in. I consider that the syntactics of for should be: for k,v in params.items(): I think you are binding ':' here too tightly to the 'for' construct in your mind. The for construct is for variable(s) in sequence which can be used as block construct:statement(s) in block constructs. The above is not a block construct but a list comprehension so it follows different rules. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
On Dec 11, 7:50 pm, [EMAIL PROTECTED] wrote: On Dec 11, 4:53 pm, William James [EMAIL PROTECTED] wrote: William James wrote: John W Kennedy wrote: Xah Lee wrote: In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. Java: static float[] normal(final float[] x) { float sum = 0.0f; for (int i = 0; i x.length; ++i) sum += x[i] * x[i]; final float divisor = (float) Math.sqrt(sum); float[] a = new float[x.length]; for (int i = 0; i x.length; ++i) a[i] = x[i]/divisor; return a; } We don't need no stinkin' loops! SpiderMonkey Javascript: function normal( ary ) { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) return ary.map(function(x) x/div) } The variable div shouldn't be global. function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } Chicken Scheme: (require 'srfi-1) (define (norm vec) (map (cute / (sqrt (reduce + 0 (map (cute expt 2) vec vec)) Cute huh? ;-) Haskell looks the best though: norm v = map (/ (sqrt (sum (map (^2) v v -- http://mail.python.org/mailman/listinfo/python-list
Re: Call by reference in SWIG?
On Dec 10, 2008, at 10:19 PM, Nok wrote: I can't get call-by-reference functions to work in SWIG... Python doesn't have any call-by-reference support at all [1], so I'm not surprised that a straight translation of the call-by-reference C function doesn't work. Unfortunately I don't know enough about SWIG to suggest a work- around. Hopefully someone more versed in SWIG will have a bright idea. If you don't find anything in the Python space, you might try poking around in Java references, since Java has the same call semantics as Python. Best wishes, - Joe [1] http://www.strout.net/info/coding/valref/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On Dec 11, 7:06 am, Luis M. González [EMAIL PROTECTED] wrote: On Dec 10, 3:42 pm, cm_gui [EMAIL PROTECTED] wrote: http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-... I fully agree with Krzysztof Kowalczyk . Can't they build a faster VM for Python since they love the language so much? Python is SLOW.And I am not comparing it with compiled languages like C. Python is even slower than PHP! Just go to any Python website and you will know. An example is:http://www2.ljworld.com/ And this site is created by the creators of Django! And it is not just this Python site that is slow. There are many many Python sites which are very slow. And please don’t say that it could be the web hosting or the server which is slow — because when so many Python sites are slower than PHP sites, it couldn’t be the web hosting. Also, Zope/Plone is even slower. Python is slow. Very slow. Now seriously, just to finish your idiotic rant, check the Pypy project: http://codespeak.net/pypyhttp://morepypy.blogspot.com And if you still think this is not enough, why don't you help these guys to make it faster? Luis PyPy looks pretty sweet. I'm glad this discussion was started. There always seems to be this buzz about python being slow. So what if it's not as fast as C? I make that up by cutting down development time. I figured if I ever ran into something being too slow, that I'd just have to learn c extensions and replace the bottle necks. In 2007 I wrote a system in python that communicated to an autopilot on an autonomously flying aircraft at real-time. We never had any speed issues. I have not played with django much and I do not typically develop web apps, but the slowness really must be bloated algorithms in the libraries you are using. Programming in other languages (java, c, c++, c# etc) is not an issue for me, but next to python it's like writing with a feather and ink instead of a ball point pen. I have to put more time into working with the tools I'm using than actually getting the job done. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
William James wrote: John W Kennedy wrote: Xah Lee wrote: In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. Java: static float[] normal(final float[] x) { float sum = 0.0f; for (int i = 0; i x.length; ++i) sum += x[i] * x[i]; final float divisor = (float) Math.sqrt(sum); float[] a = new float[x.length]; for (int i = 0; i x.length; ++i) a[i] = x[i]/divisor; return a; } We don't need no stinkin' loops! SpiderMonkey Javascript: function normal( ary ) { div=Math.sqrt(ary.map(function(x) x*x).reduce(function(a,b) a+b)) return ary.map(function(x) x/div) } The variable div shouldn't be global. function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
On 2008-12-10 23:21, Luis Zarrabeitia wrote: On Wednesday 10 December 2008 02:44:45 pm you wrote: Even in statically typed languages, when you override the equality operator/function you can choose not to return a valid answer (raise an exception). And it would break all the cases mentioned above (element in list, etc). But that isn't the right thing to do. The language doesn't/can't prohibit you from breaking the equality test, but that shouldn't be considered a feature. (a==b).all() makes no sense. Perhaps not in your application, but it does make sense in other numeric applications, e.g. ones that work on vectors or matrixes. I'd suggest you simply wrap the comparison in a function and then have that apply the necessary conversion to a boolean. I do numeric work... I'm finishing my MSc in applied math and I'm programing mostly with python. And I'd rather have a.compare_with(b), or a.elementwise_compare(b), or whatever name, rather than (a==b).all(). In fact, I'd very much like to have an a.compare_with(b, epsilon=e).all() (to account for rounding errors), and with python2.5, all(a.compare_with(b)). Yes, I could create an element_compare(a,b) function. But I still can't use a==b and have a meaningful result. Ok, I can (and do) ignore that, it's just one library, I'll keep track of the types before asking for equality (already an ugly thing to do in python), but the a==b behaviour breaks the lists (a in ll, ll.indexof(a)) even for elements not in numpy. ¿Should I also ignore lists? You should perhaps reconsider your use of lists. Lists with elements of different types can be tricky at times, so perhaps you either need a different data type which doesn't scan all elements or a separate search function that knows about your type setup. The fact that comparisons can raise exceptions is not new to Python, so this problem can pop up in other areas as well, esp. when using 3rd party extensions. Regarding the other issues like new methods you should really talk to the numpy developers, since they are the ones who could fix this. The concept of equality between two arrays is very well defined, as it is also very well defined the element-by-element comparison. There is a need to test for both - then the way to test for equality should be the equality test. I'm certain that something could be worked out. A quick paragraph that took me just a few minutes to type shouldn't be construed as a PEP that will solve all the problems :D. As always: the Devil is in the details :-) Of course... -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 11 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ 2008-12-02: Released mxODBC.Connect 1.0.0 http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Preventing execution of a method
Sorry if I'm a bit thick here... can any of the esteemed participant in this noble newsgroup confirm that is not possible to prevent a python module's code from executing the methods of another module? I.e. if I have a class with two methods, doSomethingSafe() and doSomethingDangerous(), is there a way to prevent another module from executing doSomethingDangerous() but allow the execution of doSomethingSafe()? My understanding is that in python this is not possible. Can you confirm? Manu -- http://mail.python.org/mailman/listinfo/python-list
pexpect and inconsistent exit codes
I don't seem to be able to figure out how to get the exit values of commands executed with pexpect reliably. Here's first with regular shell: [EMAIL PROTECTED]:~$ true; echo $? 0 Let's try with pexpect. Below is the program: ---CLIP--- import sys, pexpect cmd = true print 'cmd=', cmd child = pexpect.spawn(cmd, logfile=sys.stdout) child.close() print 'child exitstatus=', child.exitstatus print 'child signalstatus=', child.signalstatus print 'child status=', child.status ---CLIP--- The output: (fabexp)[EMAIL PROTECTED]:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 1 child signalstatus= None child status= 256 (fabexp)[EMAIL PROTECTED]:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= 0 child signalstatus= None child status= 0 (fabexp)[EMAIL PROTECTED]:~/python_virtualenvs/fabexp$ python dep.py cmd= true child exitstatus= None child signalstatus= 1 child status= 1 I have tried various other commands, and I just can't seem to be able to get reliable exit codes from commands I execute. Any ideas what is going on? -- Heikki Toivonen - http://heikkitoivonen.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Preventing execution of a method
On Dec 12, 2:07 am, Emanuele D'Arrigo [EMAIL PROTECTED] wrote: I.e. if I have a class with two methods, doSomethingSafe() and doSomethingDangerous(), is there a way to prevent another module from executing doSomethingDangerous() but allow the execution of doSomethingSafe()? My understanding is that in python this is not possible. Can you confirm? Your understanding is correct. The Python convention is to prefix non-public methods/classes etc with an underscore, as in _doSomethingDangerous(). This is meant to indicate to anyone using your module that they shouldn't use this function, at least not without having a good understanding of what it does. -- http://mail.python.org/mailman/listinfo/python-list
HGE and Python (again)
Good day. I've been trying to port HGE (http://hge.relishgames.com) to Python for more than 4 months now... HGE is a hardware accelerated 2D game engine. It comes with the source and examples. In the folder include, you can find hge.h, the file that i am talking about in all the post. # I tried to load the DLL functions with Python Ctypes like this : [code] from ctypes import * HGE = cdll.LoadLibrary(C:/hge181/hge) HGE.hgeCreate(0x180) [/code] But i get this error : Procedure called with not enough arguments (4 bytes missing) or wrong calling convention. The call should be done with hgeCreate(HGE_VERSION) and the constant is defined as #define HGE_VERSION 0x180... Number 0x180 means 384 in Python. I don't mean what it means in C. So i am stuck. I also tried to modify the hge.h file on line 408, and export the rest of the classes... [code] __declspec (dllexport) hgeVertex; __declspec (dllexport) hgeTriple; __declspec (dllexport) hgeQuad; __declspec (dllexport) hgeInputEvent; [/code] But after compilation, i am not able to access them from Python ctypes. They seem to remain invisible. Perhaps i am not doing it right?... # I tried Cython. I tried to load hge.h in Cython and use the structures. The first error i get is at line 173: typedef bool (*hgeCallback) ();. I am not that good in C/C++ to understand what it means. So i commented it... The second big error is at line 408: extern C { EXPORT HGE * CALL hgeCreate(int ver); }. This should be the DLL export. I comented that too... I used this code in Cython, loading from hge.h: [code] # file HGE.pyx cdef extern from windows.h: pass cdef extern from hge.h: pass [/code] And i get this errors: [code] ..\hge.h(215) : error C2061: syntax error : identifier 'hgeVertex' ..\hge.h(218) : error C2059: syntax error : '}' ..\hge.h(226) : error C2061: syntax error : identifier 'hgeVertex' ..\hge.h(229) : error C2059: syntax error : '}' ..\hge.h(274) : error C2061: syntax error : identifier 'HGE' ..\hge.h(274) : error C2059: syntax error : ';' ..\hge.h(275) : error C2449: found '{' at file scope (missing function header?) ..\hge.h(407) : error C2059: syntax error : '}' [/code] Then i tried to define hgeVertex in Cython like: [code] struct hgeVertex: float x, y # screen position float z # Z-buffer depth 0..1 DWORD col # color float tx, ty # texture coordinates [/code] But i get the exact same errors. If i comment all the structures hgeVertex and Triple and Quad and the HGE class, the Cython file compiles !... But it's not useful at all. My Cython is okay, i compiled a few programs before, so that's not a problem... # Then i tried Swig (and it worked with the examples )... But the problems with hge,h seem to be somewhat similar. I call swig like this : swig -c++ -python hge.i And the file hge.i contains: [code] /* File : hge.i */ %module hge %{ #include hge.h %} /* Let's just grab the original header file here */ %include hge.h [/code] And the error i get after commenting the HGE callback and DLL export is this : hge.h(276): Error: Syntax error in input(3). Line 276 is exactly the first call of HGE class : virtual void CALL Release() = 0;. # I tried Boost.Python (and it works with embedding and extending examples), but i could't compile hge.h even after commenting the structures and classes. I have to write some wrapper code in hge.h and i am probably doing it completely wrong. [code] BOOST_PYTHON_MODULE(hge) { using namespace boost::python; class_hgeVertex base(hgeVertex); } [/code] So i am stuck again... I am not that good in neither C or Python. Can anyone suggest any ideas? Please? I really really really want to port HGE in Python. It's the greatest game engine i have ever seen. The particle engine is EXCELLENT and i need it. Thank you in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: if var1 == var2:
At 2008-11-29T04:02:11Z, Mel [EMAIL PROTECTED] writes: You could try for item in fname: item = item.strip() This is one case where I really miss Perl's chomp function. It removes a trailing newline and nothing else, so you don't have to worry about losing leading or trailing spaces if those are important to you. -- Kirk Strauser The Day Companies -- http://mail.python.org/mailman/listinfo/python-list
Re: Why optimization mode is slower than normal mode?
Not-optimised: Pystone(1.1) time for 100 passes = 12.8366 This machine benchmarks at 77902 pystones/second Optimised: Pystone(1.1) time for 100 passes = 13.0574 This machine benchmarks at 76584.8 pystones/second It is probably the way it should be. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Preventing execution of a method
On Thu, 11 Dec 2008 at 08:16, alex23 wrote: On Dec 12, 2:07?am, Emanuele D'Arrigo [EMAIL PROTECTED] wrote: I.e. if I have a class with two methods, doSomethingSafe() and doSomethingDangerous(), is there a way to prevent another module from executing doSomethingDangerous() but allow the execution of doSomethingSafe()? My understanding is that in python this is not possible. Can you confirm? Your understanding is correct. The Python convention is to prefix non-public methods/classes etc with an underscore, as in _doSomethingDangerous(). This is meant to indicate to anyone using your module that they shouldn't use this function, at least not without having a good understanding of what it does. There is, however, also the possibility of prefixing the method name with '__'. The invokes 'name mangling', which makes it more difficult (though not impossible, the idea is to avoid accidents) for the method to be called from outside the class. http://www.python.org/doc/2.5.2/tut/node11.html#SECTION001160. --RDM-- http://mail.python.org/mailman/listinfo/python-list
Re: Preventing execution of a method
alex23 wrote: On Dec 12, 2:07 am, Emanuele D'Arrigo [EMAIL PROTECTED] wrote: I.e. if I have a class with two methods, doSomethingSafe() and doSomethingDangerous(), is there a way to prevent another module from executing doSomethingDangerous() but allow the execution of doSomethingSafe()? My understanding is that in python this is not possible. Can you confirm? Your understanding is correct. The Python convention is to prefix non-public methods/classes etc with an underscore, as in _doSomethingDangerous(). This is meant to indicate to anyone using your module that they shouldn't use this function, at least not without having a good understanding of what it does. You could add a little bit of protection by always passing a certain object into _doSomethingDangerous(). _guard = object() def _doSomethingDangerous(g): if g is not _guard: raise Exception(Don't do that!) That would at least stop accidental calls. -- http://mail.python.org/mailman/listinfo/python-list
Re: Do more imported objects affect performance
At 2008-12-01T11:30:44Z, Nick Craig-Wood [EMAIL PROTECTED] writes: Importing the module is actualy slower... If you import the name into your namespace then there is only one lookup to do. If you import the module there are two. Note that if you're importing the entire module but want to call a function that many times, you can do something like: import timeit Timer = timeit.Timer for _ in xrange(100): Timer -- Kirk Strauser The Day Companies -- http://mail.python.org/mailman/listinfo/python-list
Re: pydb 1.24
[EMAIL PROTECTED] (R. Bernstein) writes: This release is to clear out some old issues. It contains some bugfixes, document corrections, and enhancements. Tests were revised for Python 2.6 and Python without readline installed. A bug involving invoking from ipython was fixed. The frame command is a little more like gdb's. Exceptions are now caught in runcall(). This is the last release contemplated before a major rewrite. download: https://sourceforge.net/project/showfiles.php?group_id=61395package_id=175827 bug reports: https://sourceforge.net/tracker/?group_id=61395atid=497159 I watched the demo video, look forward to working with it. Any links to that emacs front-end being used in the video? Cheers and thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, threading
On 2008-12-11, SMALLp [EMAIL PROTECTED] wrote: Hy. I have a problem! I'm making multi thread application (client, server) using wxPython for GUI, and threading.Thread for threding. Clients connect and when they are connected (evry thread handles one connection) threads change main window. I neded tip how to make communication between threeds. All window manipulation must be done in the main thread. Your worker threads can schedule work to be done by the main thread by using wx.CallAfter() http://wiki.wxpython.org/CallAfter -- Grant Edwards grante Yow! This is a NO-FRILLS at flight -- hold th' CANADIAN visi.comBACON!! -- http://mail.python.org/mailman/listinfo/python-list
Re: if expression source format
Consider following snippets: # must examine code carefully to see that result has a value if condition: result = expression1 else: result = another_expression return result # result has a value but difficult to understand how it comes about result = expression1 if condition else another_expression return result # must examine code carefully to ensure that it always # returns a computed value if condition: return true_expression else: return false_expression # Ahh! I do use this idiom quite often. if condition: return true_expression return default_expression Actually, I was simply wondering if there is yet a preferred way to write the python ternary expression. Samples: # break expression near convenient max line length A) true_expression if condition else (fa lse_expression) # break expression near convenient max line length B) # (Humans be damned! form.) true_expr \ ession if cond \ ition else \ false_e \ xpressi \ on # ternary nature of expression extremely visible (true_expression if condition else false_expression) # I use this form but not happily, # providing functions as necessary to make it fit onto two lines # loosely guided by the KR admonition (or maybe it was KP) that # a conditional expression is too complicated if you can't read # it to your mother over the phone or something like that. (true_expression if condition else false_expression) -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
On Thu, 11 Dec 2008 05:40:45 + Paul Rudin [EMAIL PROTECTED] wrote: Dotan Cohen [EMAIL PROTECTED] writes: 2008/12/10 [EMAIL PROTECTED]: Ruby: def norm a s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) a.map{|x| x/s} end If someone doesn't counter with a Python one-liner then I'm going to port that to brainfuck. from numpy.linalg import norm :) This is one line of Python code alright, but it's not a one-liner in the computes the a normalized vector-sense (which was the original challenge, if there ever was one). If anything, you are now ready to compute the *norm* of a vector in a subseqent line. (Or, if you must, after a semicolon on the same line.) :) /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
dictionary idiom needed
Hi all, I have a series of lists in format ['word', 'tagA', 'tagB']. I have converted this to a few dicts, such as one in which keys are tuples of ('word', 'tagB'), and the values are the number of times that key was found. I need an dictionary idiom whereby I can find all instances of a given 'word' with any 'tagB', and then subdivide into all instances of a given 'tagB'. In both cases I would want the value as a count of all instances found. Can this be done with dictionaries? Or should I back up and do this with lists? All of the nested for loops I have tried return replicated results, so I can't trust those values. Thanks for any pointers, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: if var1 == var2:
On Thu, 11 Dec 2008 at 10:24, Kirk Strauser wrote: At 2008-11-29T04:02:11Z, Mel [EMAIL PROTECTED] writes: You could try for item in fname: item = item.strip() This is one case where I really miss Perl's chomp function. It removes a trailing newline and nothing else, so you don't have to worry about losing leading or trailing spaces if those are important to you. ' ab c \r\n'.rstrip('\r\n') ' ab c ' ' ab c \n'.rstrip('\r\n') ' ab c ' ' ab c '.rstrip('\r\n') ' ab c ' --RDM -- http://mail.python.org/mailman/listinfo/python-list
Re: Preventing execution of a method
On Dec 12, 2:35 am, [EMAIL PROTECTED] wrote: There is, however, also the possibility of prefixing the method name with '__'. The invokes 'name mangling', which makes it more difficult (though not impossible, the idea is to avoid accidents) for the method to be called from outside the class. That only works for methods, it has no effect on functions or classes within modules: module.py: def __f(): pass class __F(object): def __f(): pass import module as m m.__f function __f at 0x00B80FB0 m.__F class 'module.__F' f = m.__F() f.__f Traceback (most recent call last): File stdin, line 1, in module AttributeError: '__F' object has no attribute '__f' f._F__f bound method __F.__f of module.__F object at 0x00B89B30 -- http://mail.python.org/mailman/listinfo/python-list
Re: internal circular class references
Carl Banks wrote: On Dec 10, 5:26 pm, Ethan Furman [EMAIL PROTECTED] wrote: Greetings List! I'm writing a wrapper to the datetime.date module to support having no date. Its intended use is to hold a date value from a dbf file, which can be empty. The class is functional at this point, but there is one thing I would like to change -- datetime.date.max and datetime.date.min are class attributes of datetime.date, and hold datetime.date values. At this point I have to have two lines outside the actual class definition to do the same thing, e.g.: trimmed down class code class NullDate(object): adds null capable DateTime.Date constructs __slots__ = ['_date'] def __new__(cls, date='', month=0, day=0): nulldate = object.__new__(cls) nulldate._date = . . . return nulldate snip NullDate.max = NullDate(dt.date.max) NullDate.min = NullDate(dt.date.min) /trimmed down class code How can I move those last two lines into the class definition so that: 1) they are class attributes (not instance), and 2) they are NullDate type objects? It can't be done by any straightforward method I know of. I advise you not to worry about it, and just define them afterwards, perhaps with an apologetic comment saying you would have put them inside the class definition if you could have. If the out-of-scope issue bothers you that much, you could use some metaclass hackery to run a method that defines the class attributes after the class is created, at the unrecommendable cost of confusing most readers. Here is a very simple example: def make_class_and_run_postcreate(name,bases,clsdict): cls = type.__new__(type,name,bases,clsdict) cls.__postcreate__() return cls class A(object): __metaclass__ = make_class_and_run_postcreate @classmethod def __postcreate__(cls): cls.internal_circular_class_ref = cls() Well, since Practicality beats purity ;) , I'll stick with having the two assignment statements just outside the class. Not to mention my metaclass skills are nonexistent at this point. BTW, if you don't mind some criticism of your code, the code you posted seems to be much too complex for the job you're describing. Critiques always welcome. First of all, do you even need to wrap the datetime.date class? With Python's duck typing ability, you could have a separate NullDate class to go alongside the datetime.date, and use a regular datetime.date object when the date is present, and NullDate when it's absent. If necessary you can subclass datetime.date to add any new methods it would have to have. Use a factory function to return either NullDate or a datetime.date depending on whether the dbf cell is empty. class ValidDate(datetime.date): def is_valid(self): return True class NullDate(object): # implement any necessary methods of datetime.date interface here def is_valid(self): return False def create_date_from_dbf_cell(dbf_cell): if dbf_cell.empty(): return NullDate() return ValidDate(dbf_cell.value) If you do this, you don't have to muck around with __getattr__ or __new__ or snooping to datetime.date's class dict anything like that. Carl Banks Good question. My goal with NullDate is to have a date object that I can treat the same regardless of whether or not it actually holds a date. NullDates with no value should sort before any NullDates with a value, should be comparable to dates as well as NullDates, and should support all the same methods. In other words, I don't want to have to worry about whether my date object has an actual date under most circumstances (printing, using as dictionary keys, comparing, etc.). Does my design make more sense given these expanded requirements, or could it still be done simpler? For that matter, do my requirements make sense? ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Preventing execution of a method
On Dec 12, 3:22 am, alex23 [EMAIL PROTECTED] wrote: On Dec 12, 2:35 am, [EMAIL PROTECTED] wrote: There is, however, also the possibility of prefixing the method name with '__'. The invokes 'name mangling', which makes it more difficult (though not impossible, the idea is to avoid accidents) for the method to be called from outside the class. That only works for methods, it has no effect on functions or classes within modules: And of course -now- I realise that the OP was asking for protecting methods. Please disregard my last post :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Deeper tracebacks?
BINGO! Give that man a CIGAR! The specifics don't seem to be quite right (there is no sys.last_traceback), but R.Bernstein put me directly on the correct track. I misunderstood the traceback module documentation. OK, I just plain didn't read it correctly, it's right there (extract_stack(): Extract the raw traceback from the current stack frame.). The answer is to use traceback.extract_tb (), called with sys.exc_info()[3] (the stackframe that raised the exception). Another sterling example of the benefits of reading the fine manual -- for comprehension this time. Instead of: aRawStack = traceback.extract_stack() do this: aRawStack = traceback.extract_tb(sys.exc_info()[2]) With this change, aRawStack contains the following: aRawStack[0][3] 'answer = apply(aMethod, [], {})' aRawStack[1][3] 'int(3).zork()' This is *exactly* what I was seeking. I appreciate all the responses, and especially appreciate the pointer from R.Bernstein. Thx, Tom On Dec 11, 4:49 am, [EMAIL PROTECTED] (R. Bernstein) wrote: brooklineTom [EMAIL PROTECTED] writes: I want my exception handler to report the method that originally raised an exception, at the deepest level in the call-tree. Let give an example. import sys, traceback class SomeClass: def error(self): Raises an AttributeError exception. int(3).zork() def perform_(self, aSelector): try: aMethod = getattr(self, aSelector, None) answer = apply(aMethod, [], {}) except: AttributeError, anAttributeErrorException: aRawStack = traceback.extract_stack() answer = None When I call perform_ (... SomeClass().perform_('error')), I want to collect and report the location *within the method (error) that failed*. The above code reports the location of perform_, and no deeper in the call tree. Anybody know how to accomplish this? extract_stack() without any arguments is getting this from the *current frame* which as you noted doesn't have the last exception info included which has been popped; variable sys.last_traceback has the frames at the time of the exception, I think. So in your code try changing: aRawStack = traceback.extract_stack() to aRawStack = traceback.extract_stack(sys.last_traceback) -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle issues
On Dec 10, 9:48 am, huw_at1 [EMAIL PROTECTED] wrote: Hey all. When using cx_Oracle to run a procedure like: cursor.execute(select (obj.function(value)) from table where id=blah) I am getting the following error: ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at line 1 Looking at cursor.description I get: [('(obj.function(value))', type 'cx_Oracle.STRING', 4000, 4000, 0, 0, 1)] Any tips - i have never seen this error before but am guessing that the value being returned is too big for the buffer size set for the cursor. the procedure fetches data from a LOB. Any suggestions/confirmations? Many thanks This error is a problem with the PL/SQL, not cx_Oracle. You need to debug obj.function to see what kind of data is being accessed and then a data analysis of that data to understand why this error occurs. I can tell you the function is most likely expecting characters from a column that are numeric [0 .. 9] and is getting alpha characters. -- Ron Reidy Sr. Oracle DBA -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory leak when using a C++ module for Python
Sure, sorry... This is the function that is visible from python and the one that the python code calls: static PyObject * IMFind (PyObject *self, PyObject *args, PyObject *kwargs) { //Array for the detection of the parameters coming from Python static char *kwlist[] = {shareInt,root,prefix,lowerLimit,NULL}; //Root protein code char *root; //Pefix for the output file char *prefix; //Incoming Python object PyObject *shareIntPy; //Number of proteins at level two from the root, that will appear in the iMotifs' proteins int *pSize = new int; //Maximum number of common interactors int *max = new int; //Set relating each protein (integer) with their interactors... setunsigned int** shareInt; //Lower limit for iMotif search int lowLim; //Vector for the seed iMotifs from an specific threshold vectoriMotif IMseed; //Vector of all the working iMotifs during the identification process vectoriMotif IMarray; //Receiving data from python if (!PyArg_ParseTupleAndKeywords(args, kwargs, Ossi, kwlist, shareIntPy, root, prefix,lowLim)) { cerr Error in parameter transference from python to iMotif C++ moduleendl; return Py_BuildValue(); } //The position of the name in the vector corresponds to the number by which it is represented //Here we take the info coming from python and transform it into a vector (will allow us to work with numbers instead of // strings) and shareInt which is an array of sets (form std::set) vectorstring translator = string2int (shareIntPy,root,shareInt,pSize,max); //Loop for iMotif search at threshold thr till the specified lower limit for (int thr = *max; thr = lowLim; thr--) { cout Checking threshold thr endl; //Specifying the output file name stringstream filename; filename prefix . thr; //Getting the seed iMotifs for this threshold IMseed = getSeedIM(shareInt,*pSize,thr); //Adding the new seeds (if any) to those obtained from previous rounds... if (!IMseed.size()) { IMseed.clear(); vectoriMotif().swap(IMseed); //This is how I try to free them now, size capacity gets to 0, but the // memory is not freed... } else { IMarray.insert(IMarray.end(),IMseed.begin(),IMseed.end()); IMseed.clear(); vectoriMotif().swap(IMseed); } //Fuse those iMotifs sharing thr interactors // It also deletes the IMarray before giving it the new data in the same way as I use here for IMseed processIMVector(IMarray,thr); writeIMVector(IMarray,translator,filename.str()); } return Py_BuildValue(); } The object iMotif used here is composed by 2 sets and 3 strings just like this: (the access is done by setters and getters) class iMotif { private: //Set of the proteins that shares the iMotif with the root setunsigned int proteins; //Set of the proteins to which the iMotifs interacts setunsigned int interactors; //iMotifs interactors signature string MD5Interactor; //iMotifs proteins signature string MD5Proteins; //Real MD5 according to the sequences names string signature; ... } and I specified the destructor as: iMotif::~iMotif() { this-proteins.clear(); setunsigned int().swap(this-proteins); this-interactors.clear(); setunsigned int().swap(this-proteins); } The call to the function from python goes like this: iMotifs.IMFind(shareInt=intersections_dict, root=options.protein_problem, prefix=prefixOutFile, lowerLimit=1); where intersections_dict is a dictionary and options.protein_problem and prefixOutFile are strings. There is nothing to return from C++ to python, the result is directly printed into several files. Thanks, J -- http://mail.python.org/mailman/listinfo/python-list
Re: Preventing execution of a method
And of course -now- I realise that the OP was asking for protecting methods. Please disregard my last post :) Alex23, Are you telling me that you do not know how to YANK your own post? I find that hard to believe. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: get todays files
Tim Chase wrote: This looks very good and I have tested successfully, but is there a way I can set the today to automatically become todays date in that format? Yes...see the python datetime module[1]...particularly the strftime() call on date/datetime objects. -tkc [1] http://docs.python.org/library/datetime.html I know this will sound like I am being very cheeky, but is there a way you can make this for where the ftp server is actually windows server? The script runs and it shows the date the file was modified, but still downloads them, I have attached the script I am now using with your code in. import os from ftplib import FTP import subprocess from datetime import datetime from time import gmtime, strftime curr_date = strftime(%d %B %Y, gmtime()) # config ftp_uname = '' ftp_pwd = '' ftp_server = '' # end of config fileroot = 'DBBackup_' os.chdir('c:/') files = [] logfile = open('c:/dbbackup/getmdbackups.log','a+') def makelist(line): if (line.startswith(fileroot)): fs = [line] files.append(fs) def log(line): ll = str(datetime.now()) + ' : ' + str(line) print ll logfile.write(ll + '\n') def fileexists(ff, size): if (os.path.exists(ff)): stat = os.stat(ff) if (stat.st_size == size): return True return False try: # first connect using ftp to get a list of valid backup failes available log('Connecting to ftp server') ftp = FTP(ftp_server) ftp.set_pasv(False) #ftp.set_debuglevel(2) resp = ftp.login(ftp_uname,ftp_pwd) log(resp) ftp.retrlines('NLST',makelist) log(str(files)) ftp.quit() # fetch files in a loop using wget. for ff in files: ftp = FTP(ftp_server) ftp.set_pasv(False) resp = ftp.login(ftp_uname,ftp_pwd) log(resp) size = ftp.size(ff[0]) log('Size of server file = ' + str(size)) #ftp.quit() try: if (not fileexists(ff[0],size)): results = ftp.sendcmd(MDTM %s % ff[0]) code, stamp = results.split(None, 1) assert code == 213, Unexpected result print %s was modified on %s % (ff[0], stamp) today = curr_date if stamp[:8] == today: log('Transferring: ' + ff[0]) # make parameters to wget the backup file params = ' ftp://' + ftp_server + '/' + ff[0] rcode = subprocess.call('c:/wget.exe ' + params) log('Return code from wget = ' + str(rcode)) if (rcode == 0): ff[1] = 1 else: log('File ' + ff[0] + ' already exists locally, not transferring') ff[1] = 1 except Exception, e: log(str(e)) log('Transfer complete') # delete the server files that have been transferred or are already here with the right filesize. for ff in files: if (ff[1] == 1): log('delete ' + ff[0]) except Exception,e: log(str(e)) # clean up temp files log('Finished.') logfile.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I understan the for here?
D'Arcy J.M. Cain wrote: On Thu, 11 Dec 2008 22:44:20 +0800 Kermit Mei [EMAIL PROTECTED] wrote: [%s=%s % (k, v) for k, v in params.items()] ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] I can't understand the second sentence because of the for ... in. I consider that the syntactics of for should be: for k,v in params.items(): I think you are binding ':' here too tightly to the 'for' construct in your mind. The for construct is for variable(s) in sequence which can be used as block construct:statement(s) in block constructs. The above is not a block construct but a list comprehension so it follows different rules. Yes, I see. Thanks you all. -- http://mail.python.org/mailman/listinfo/python-list
Python to open command script file
Hello all I would like to know how to do the following. I'd like to have a generic python program that the user will open a command-script file to do actions. So, my python program will get a list of servers, enumerate them within a checklistbox in wxpython. Then I want to open a command-file that will run against each selected server that will look like this: ---SAMPLE copy abc.xyz from c:\source to u:\target copy all from c:\source to u:\target unload netshld from server1 -END SAMPLE-- (where I have a class serverfuncs, where I can: s = serverfuncs() s.unload('module', 'server') Really, I can do all the actions, but I don't know how to trigger them from an independent script file. Thanks! -Dave -- http://mail.python.org/mailman/listinfo/python-list
How to know when it's possible to bind a socket on an unprivileged port?
Hi, For a purpose of testing I need a function which could tell me whether it is possible to bind sockets on privileged ports or not. I wrote down this simple function. It seems reasonably working to me but I'd like to hear your opinion first. Thanks in advance. import socket, errno def bind_on_privileged_ports(port=21): Return True if it is possible to bind sockets on privileged ports ( 1024). try: s = socket.socket() s.bind((, port)) except socket.error, err: if err[0] == errno.EACCES: return False s.close() return True --- Giampaolo http://code.google.com/p/pyftpdlib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
Andreas Waldenburger wrote: On Thu, 11 Dec 2008 05:40:45 + Paul Rudin [EMAIL PROTECTED] wrote: Dotan Cohen [EMAIL PROTECTED] writes: 2008/12/10 [EMAIL PROTECTED]: Ruby: def norm a s = Math.sqrt(a.map{|x|x*x}.inject{|x,y|x+y}) a.map{|x| x/s} end If someone doesn't counter with a Python one-liner then I'm going to port that to brainfuck. from numpy.linalg import norm :) This is one line of Python code alright, but it's not a one-liner in the computes the a normalized vector-sense (which was the original challenge, if there ever was one). If anything, you are now ready to compute the *norm* of a vector in a subseqent line. (Or, if you must, after a semicolon on the same line.) Couldn't we assume that when you doing these kinds of math, there's always import numpy or from numpy import * is always at the start of the program, so it doesn't belong to the functional code ? And for those who use VPython (and thus needs from visual import * ) can simply do a = norm ( v ) cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: Is 3.0 worth breaking backward compatibility?
On Dec 7, 12:35 pm, Andreas Waldenburger [EMAIL PROTECTED] wrote: Plze. Python 3 is shipping now, and so is 2.x, where x 5. Python 2 is going to be around for quite some time. What is everybody's problem? A possible, potential, problem, could arise if you were using python 2.x, but some other code, that you wanted to include, was writen in python 3.x. It always surprises me that so many python developers never consider the possibility that you may not always be working with your own code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
On Dec 11, 12:32 am, Gerard flanagan [EMAIL PROTECTED] wrote: Xah Lee wrote: On Dec 10, 2:47 pm, John W Kennedy [EMAIL PROTECTED] wrote: Xah Lee wrote: In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. [...] Thanks to various replies. I've now gather code solutions in ruby, python, C, Java, here: • A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html now lacking is perl, elisp, which i can do well in a condensed way. It'd be interesting also to have javascript... mmm, stone soup... javascript: var map = function(fn, a) { var b = new Array(a.length); for (i = 0; i a.length; i++) { b[i] = fn(a[i]); } return b }; var reduce = function(fn, a, init) { var s = init; for (i = 0; i a.length; i++) { s = fn(s, a[i]); } return s }; var sum = function(a) { return reduce(function(x, y) { return x + y }, a, 0.0) }; var norm = function(a) { var pow = Math.pow; return Math.sqrt(sum(map(function(x) { return pow(x, 2) }, a))) }; var Unit = function(a) { var N = norm(a); return map(function(x) { return x/N }, a) }; thats about 15 lines. I'm pretty sure JavaScript doesn't need that many? Xah ∑ http://xahlee.org/ ☄ -- http://mail.python.org/mailman/listinfo/python-list
Re: Deeper tracebacks?
En Thu, 11 Dec 2008 07:49:42 -0200, R. Bernstein ro...@panix.com escribió: brooklineTom brookline...@gmail.com writes: I want my exception handler to report the method that originally raised an exception, at the deepest level in the call-tree. Let give an example. extract_stack() without any arguments is getting this from the *current frame* which as you noted doesn't have the last exception info included which has been popped; variable sys.last_traceback has the frames at the time of the exception, I think. So in your code try changing: aRawStack = traceback.extract_stack() to aRawStack = traceback.extract_stack(sys.last_traceback) No, last_traceback is the last *printed* traceback in the interactive interpreter. Use the third element in sys.exc_info() instead: import sys, traceback class SomeClass: def error(self): Raises an AttributeError exception. int(3).zork() def perform_(self, aSelector): try: aMethod = getattr(self, aSelector) answer = aMethod() except AttributeError: tb = sys.exc_info()[2] try: print Using traceback.print_tb: traceback.print_tb(tb) print Using traceback.print_exception: traceback.print_exception(*sys.exc_info()) print Using traceback.extract_tb: print traceback.extract_tb(tb) finally: del tb SomeClass().perform_(error) output: Using traceback.print_tb: File test_tb.py, line 11, in perform_ answer = aMethod() File test_tb.py, line 6, in error int(3).zork() Using traceback.print_exception: Traceback (most recent call last): File test_tb.py, line 11, in perform_ answer = aMethod() File test_tb.py, line 6, in error int(3).zork() AttributeError: 'int' object has no attribute 'zork' Using traceback.extract_tb: [('test_tb.py', 11, 'perform_', 'answer = aMethod()'), ('test_tb.py', 6, 'error' , 'int(3).zork()')] (The 3-name form of the except clause that I menctioned previously only exists in my imagination :) ) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Is 3.0 worth breaking backward compatibility?
On Thu, Dec 11, 2008 at 12:21 PM, walterbyrd walterb...@iname.com wrote: On Dec 7, 12:35 pm, Andreas Waldenburger geekm...@usenot.de wrote: Plze. Python 3 is shipping now, and so is 2.x, where x 5. Python 2 is going to be around for quite some time. What is everybody's problem? A possible, potential, problem, could arise if you were using python 2.x, but some other code, that you wanted to include, was writen in python 3.x. A possible, potential, problem, could arise if you were using [Java], but some other code, that you wanted to include, was writen in [Pascal]. Surely the software industry is doomed? -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary idiom needed
Brandon: I need an dictionary idiom whereby I can find all instances of a given 'word' with any 'tagB', and then subdivide into all instances of a given 'tagB'. In both cases I would want the value as a count of all instances found. If I have understood you well enough, I think you can do with a dict that has the tuple ('word', 'tagB') as key, and as value has a collections.defaultdict(int) that maps 'tagB' to its count. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
Xah Lee wrote: • A Example of Mathematica's Expressiveness http://xahlee.org/UnixResource_dir/writ/Mathematica_expressiveness.html On Dec 11, 3:53 am, William James w_a_x_...@yahoo.com wrote: function normal( ary ) { var div = Math.sqrt( ary.map(function(x) x*x).reduce(function(a,b) a+b) ) return ary.map(function(x) x/div) } I run your code in SpiderMonkey: // SpiderMonkey javascript. By William James. function normal(v) { var div=Math.sqrt(v.map(function(x) x*x).reduce(function(a,b) a+b)) return v.map(function(x) x/div) } print normal [3,4]; i got: /Users/xah/Documents/temp/xx.js:3: SyntaxError: missing { before function body: /Users/xah/Documents/temp/xx.js:3: var div=Math.sqrt(v.map(function(x) x*x).reduce(function(a,b) a+b)) /Users/xah/Documents/temp/xx.js: 3: ^ Xah ∑ http://xahlee.org/ ☄ -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary idiom needed
bearophile: you can do with a dict that has the tuple ('word', 'tagB') as key, and as value has a collections.defaultdict(int) that maps 'tagB' to its count. Where's 'tagA'? Probably I haven't understood your problem well enough. I need a better example of your data and what you need... Sorry, bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Is 3.0 worth breaking backward compatibility?
On Thu, 11 Dec 2008 10:21:55 -0800 (PST) walterbyrd walterb...@iname.com wrote: On Dec 7, 12:35 pm, Andreas Waldenburger geekm...@usenot.de wrote: Plze. Python 3 is shipping now, and so is 2.x, where x 5. Python 2 is going to be around for quite some time. What is everybody's problem? A possible, potential, problem, could arise if you were using python 2.x, but some other code, that you wanted to include, was writen in python 3.x. Yes, that would be a problem, of course. But I fail to see how that is not a problem with python 2.x as well. New Style Classes? Generators? The with statement? I use those all the time. Why aren't as many people complaining about them with the same argument? /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
On Dec 10, 2:47 pm, John W Kennedy jwke...@attglobal.net wrote: Xah Lee wrote: In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java, you'll have 50 or hundreds lines. C: #include stdlib.h #include math.h void normal(int dim, float* x, float* a) { float sum = 0.0f; int i; float divisor; for (i = 0; i dim; ++i) sum += x[i] * x[i]; divisor = sqrt(sum); for (i = 0; i dim; ++i) a[i] = x[i]/divisor; } i don't have experience coding C. The code above doesn't seems to satisfy the spec. The input should be just a vector, array, list, or whatever the lang supports. The output is the same datatype of the same dimension. Xah ∑ http://xahlee.org/ ☄ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to open command script file
On Dec 11, 12:04 pm, dave rose s_david_r...@hotmail.com wrote: Hello all I would like to know how to do the following. I'd like to have a generic python program that the user will open a command-script file to do actions. So, my python program will get a list of servers, enumerate them within a checklistbox in wxpython. Then I want to open a command-file that will run against each selected server that will look like this: ---SAMPLE copy abc.xyz from c:\source to u:\target copy all from c:\source to u:\target unload netshld from server1 -END SAMPLE-- (where I have a class serverfuncs, where I can: s = serverfuncs() s.unload('module', 'server') Really, I can do all the actions, but I don't know how to trigger them from an independent script file. Thanks! -Dave I usually use python's included shutil module for copying files and directories. I think that would be a little more cross-platform friendly. However, if you want to execute those commands above, try using the subprocess module or os.system. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: How to know when it's possible to bind a socket on an unprivileged port?
On 11 Dic, 19:09, Giampaolo Rodola' gne...@gmail.com wrote: Hi, For a purpose of testing I need a function which could tell me whether it is possible to bind sockets on privileged ports or not. I wrote down this simple function. It seems reasonably working to me but I'd like to hear your opinion first. Thanks in advance. import socket, errno def bind_on_privileged_ports(port=21): Return True if it is possible to bind sockets on privileged ports ( 1024). try: s = socket.socket() s.bind((, port)) except socket.error, err: if err[0] == errno.EACCES: return False s.close() return True Just to clarify: I don't really care *which* port to use for binding the socket. I just need to try to bind a socket on a free random privileged port and return True if that has been possible. --- Giampaolo http://code.google.com/p/pyftpdlib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: get todays files
I know this will sound like I am being very cheeky, but is there a way you can make this for where the ftp server is actually windows server? For Windows Server, I don't have a Windows FTP server to test with -- I've got the company Linux server, and the previous testing site I used (I think I used ftp.mozilla.org) which also likely runs some flavor of Linux. Neither supports the NLST from my testing. curr_date = strftime(%d %B %Y, gmtime()) The first thing I noticed was that your strftime formating needs to match the format of the date that comes back from the FTP site. In my test, that was MMDD. As such, your %d %B %Y would likely need to be %Y%m%d. ftp.retrlines('NLST',makelist) The servers I tried didn't support the NLST command so I can't exactly follow along here. However assuming that it correctly populates the list of files here for ff in files: correctly, that's immaterial to me. ftp = FTP(ftp_server) ftp.set_pasv(False) resp = ftp.login(ftp_uname,ftp_pwd) Just curious why you're logging into the server each pass through the loop -- I'd just connect once at the beginning of the loop, pull the files, and then disconnect at the end of the loop. assert code == 213, Unexpected result Does this assert fail at any point? if stamp[:8] == today: Given the above date-formatting, this should fail *every* time unless your FTP server is returning the date in some format other than MMDDhhmmss It's hard to pinpoint actual problems as this block of code has been modified, or doesn't run...there's some bogus indentation in your post: log('Transferring: ' + ff[0]) # make parameters to wget the backup file params = ' ftp://' + ftp_server + '/' + ff[0] rcode = subprocess.call('c:/wget.exe ' + params) log('Return code from wget = ' + str(rcode)) if (rcode == 0): ff[1] = 1 else: log('File ' + ff[0] + ' already exists locally, not transferring') because this else is hanging oddly. Additionally, the FTP object has methods for downloading the content of a file, so I'd not bother shelling out to wget as an additional dependency. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: internal circular class references
On Dec 11, 11:33 am, Ethan Furman et...@stoneleaf.us wrote: Good question. My goal with NullDate is to have a date object that I can treat the same regardless of whether or not it actually holds a date. NullDates with no value should sort before any NullDates with a value, should be comparable to dates as well as NullDates, and should support all the same methods. In other words, I don't want to have to worry about whether my date object has an actual date under most circumstances (printing, using as dictionary keys, comparing, etc.). Does my design make more sense given these expanded requirements, or could it still be done simpler? For that matter, do my requirements make sense? Your requirements make sense, but I think your approach is overkill. In particular, I think you are unnecessarily constraining yourself by forcing the dates and non-dates to be of the same data type. There's usually no reason for that. Python's duck typing allows you to write code that supports multiple types, as long as each type provides the same methods and operations and such. For instance, say you have a function like this that works for ordinary datetime.date objects: def print_date(date): print date.strftime() Now you want to be able to pass it a particular object that indicates no date was specified. Just define the class, like so: class NullDate(object): def strftime(self): print no date specified Now you could pass either a regular datetime.date object, or a NullDate object, like so: print_date(datetime.date(1976,10,6)) print_date(NullDate()) So, to (almost) get what you want, you need to just define a NullDate class that implements all the methods of datetime.date. Then the only thing you have to do is, when you're extracting the date from your dbf file, instead of always creating a datetime.date, create a datetime.date object when the date is specified, and a NullDate object when it's not. You could write a factory function to do it, for instance: def create_date_or_not(dbf_cell): if dbf_cell.contents: return datetime.date.fromordinal(dbf_cell.contents) return NullDate() Now, you did throw one little curveball into the requirements above: that NullDate needs to be comparable with datetime.date objects. I'd handle this by subclassing datetime.date to allow comparisons with NullDates. class ValidDate(datetime.date): def __eq__(self,other): if isinstance(other,NullDate): return False return super(ValidDate,self).__eq__(other) # and so on class NullDate(object): def __eq__(self,other): if isinstance(other,NullDate): return True return False # note: in Python 3.0 you would want to throw exceptions # for unexpected types Then use ValidDate instead of datetime.date when the date is specified. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: get todays files
Tim Chase wrote: I know this will sound like I am being very cheeky, but is there a way you can make this for where the ftp server is actually windows server? For Windows Server, I don't have a Windows FTP server to test with -- I've got the company Linux server, and the previous testing site I used (I think I used ftp.mozilla.org) which also likely runs some flavor of Linux. Neither supports the NLST from my testing. curr_date = strftime(%d %B %Y, gmtime()) The first thing I noticed was that your strftime formating needs to match the format of the date that comes back from the FTP site. In my test, that was MMDD. As such, your %d %B %Y would likely need to be %Y%m%d. ftp.retrlines('NLST',makelist) The servers I tried didn't support the NLST command so I can't exactly follow along here. However assuming that it correctly populates the list of files here for ff in files: correctly, that's immaterial to me. ftp = FTP(ftp_server) ftp.set_pasv(False) resp = ftp.login(ftp_uname,ftp_pwd) Just curious why you're logging into the server each pass through the loop -- I'd just connect once at the beginning of the loop, pull the files, and then disconnect at the end of the loop. I support it would be somewhat better to download in a 'bulk' download rather that a file at a time, this script was not written by me, I am just the developer who has to make a new or modify the old one. assert code == 213, Unexpected result Does this assert fail at any point? Nope, nothing shows up in my logs or on screen. if stamp[:8] == today: Given the above date-formatting, this should fail *every* time unless your FTP server is returning the date in some format other than MMDDhhmmss This line appears to just get missed in the code, I think it might be one of the problems when it downloads all the files. It's hard to pinpoint actual problems as this block of code has been modified, or doesn't run...there's some bogus indentation in your post: log('Transferring: ' + ff[0]) # make parameters to wget the backup file params = ' ftp://' + ftp_server + '/' + ff[0] rcode = subprocess.call('c:/wget.exe ' + params) log('Return code from wget = ' + str(rcode)) if (rcode == 0): ff[1] = 1 else: log('File ' + ff[0] + ' already exists locally, not transferring') because this else is hanging oddly. Additionally, the FTP object has methods for downloading the content of a file, so I'd not bother shelling out to wget as an additional dependency I am running kubuntu 8.04 and have edited the code in kate, It seemed to indent on every line, so I just 'pulled' it back a little. . -tkc Thanks for you comments, I think I will try and start from scratch and see what I get. Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Find Files in a Folder Between 2 Dates
On Dec 5, 3:14 pm, John Machin sjmac...@lexicon.net wrote: On Dec 6, 9:41 am, GregoryPlantainegamersu...@gmail.com wrote: That worked perfectly! Thanks Tim! Since we can print the files, does that mean the list of files is in a tuple, or something? Would there be a way to further split up the file names? For example, now that the files are processed into the list, we want to look through that list to find different filetypes. files C:\Folder\File_200812051439.111 C:\Folder\File_200812051539.222 *DANGER* It looks like you are interested in the timestamps that are embedded in the names of the files. Tim's code assumes [reasonably given that your problem description was ambiguous and had no examples of good and bad results] that you are interested in the last modification time of the file. You may say same thing. Yes, same thing, until somebody sucks a file into a text editor, messes with it, and saves it again. No, Murphy's Law has not been repealed. Can we split up .111 files? Actually, where would I look something like this up? In the Library Reference Manual ... there are all sorts of goodies in the os and os.path modules e.g. like those used by Tim; make sure you read the docs on the methods Tim used so that you understand what's happening. HTH, John Thanks for the advice John! I was going though the Manual, but I'm having some trouble figuring out how to iterate through each line. So from the same example, we've already created a list called lists. Now how do I iterate through each line? For eachline in lists Find all .111 files. -- http://mail.python.org/mailman/listinfo/python-list
Re: Preventing execution of a method
Thank you all for the confirmation and the suggestions (including the tangential ones: I didn't know one could remove your his own posts!). As much as I really like Python (which I've been using full-time only for the past two months) I really wish it did have regular private/ protected/public methods. I'm building an application that can be extended by the users and I really wish there was a solid way to prevent them from accessing parts of the application that they shouldn't access or to provide read-only access. I.e. right now I'm working on the graphical client which potentially could be rewritten entirely by the users. It is necessary and perfectly reasonable for the client module to access some of the objects to be represented graphically, but those objects shouldn't be modifiable by it. I now wonder, would developing the graphical client as an entirely separate application, communicating with the server via the localhost network interface and messages, solve the problem? Would it keep the objects of the two applications (server/client) entirely separate? Manu -- http://mail.python.org/mailman/listinfo/python-list
Re: internal circular class references
On Thu, 11 Dec 2008 at 09:33, Ethan Furman wrote: Carl Banks wrote: On Dec 10, 5:26 pm, Ethan Furman et...@stoneleaf.us wrote: First of all, do you even need to wrap the datetime.date class? With Python's duck typing ability, you could have a separate NullDate class to go alongside the datetime.date, and use a regular datetime.date object when the date is present, and NullDate when it's absent. If necessary you can subclass datetime.date to add any new methods it would have to have. Use a factory function to return either NullDate or a datetime.date depending on whether the dbf cell is empty. class ValidDate(datetime.date): def is_valid(self): return True class NullDate(object): # implement any necessary methods of datetime.date interface here def is_valid(self): return False def create_date_from_dbf_cell(dbf_cell): if dbf_cell.empty(): return NullDate() return ValidDate(dbf_cell.value) If you do this, you don't have to muck around with __getattr__ or __new__ or snooping to datetime.date's class dict anything like that. Carl Banks Good question. My goal with NullDate is to have a date object that I can treat the same regardless of whether or not it actually holds a date. NullDates with no value should sort before any NullDates with a value, should be comparable to dates as well as NullDates, and should support all the same methods. In other words, I don't want to have to worry about whether my date object has an actual date under most circumstances (printing, using as dictionary keys, comparing, etc.). Does my design make more sense given these expanded requirements, or could it still be done simpler? For that matter, do my requirements make sense? What Carl is saying is that since python uses duck typing (if it quacks like a duck, it is a duck), all you need to do is make your NullDate object quack enough like a date to handle your use cases, and then you can freely mix dates and NullDates _without having to care which one a given object is_ (python won't care). (Until you do care, at which point you can use isinstance to find out if it is a NullDate). As far as I can see, your requirements as you've outlined them can be met by mixing date objects and appropriately implemented NullDate objects. And that way NullDates will _only_ represent null dates, thus making its name more meaningful :). To do this you just need to implement on NullDate those methods that are going to give NullDate the behavior you need: the rich comparison operators, __str__, __hash__, etc. Or it might be easier to subclass date and override some of the methods. Unless I'm misunderstanding your requirements, of course :) --RDM -- http://mail.python.org/mailman/listinfo/python-list
Re: Call by reference in SWIG?
On Thu, Dec 11, 2008 at 9:43 AM, Joe Strout j...@strout.net wrote: On Dec 10, 2008, at 10:19 PM, Nok wrote: I can't get call-by-reference functions to work in SWIG... Python doesn't have any call-by-reference support at all [1], so I'm not surprised that a straight translation of the call-by-reference C function doesn't work. Unfortunately I don't know enough about SWIG to suggest a work-around. Hopefully someone more versed in SWIG will have a bright idea. If you don't find anything in the Python space, you might try poking around in Java references, since Java has the same call semantics as Python. I'm not sure if SWIG has tools to do this for you or if you need to do the mapping by hand, but the usual idiom is to translate them into return values (keeping the original arg if the passed in value matters also). -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
On Dec 11, 6:50 am, the.brown.dragon.b...@gmail.com wrote: ;; Chicken Scheme. By the.brown.dragon...@gmail.com (require 'srfi-1) (define (normalize vec) (map (cute / (sqrt (reduce + 0 (map (cute expt 2) vec vec)) Is it possible to make it work in scsh? (i'm running scsh 0.6.4, and don't know Scheme lisp well) Xah ∑ http://xahlee.org/ ☄ -- http://mail.python.org/mailman/listinfo/python-list
Re: just got the g1
garywood wrote: Hi Just got the G1, is their any way to get python running on the andriod platform ? Nope. But some day when other languages are supported, Python will be high on the list. In the meantime, Android is java only. And no you can't use Jython because Android statically compiles normal java byte code to the special bytecode their own VM uses. Jython being a dynamic language does not emit static java classes. From what I understand, porting Jython to work on this special VM is not trivial. -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of 'wget' for python?
On Mon, Dec 8, 2008 at 8:22 AM, Robert Dailey rcdai...@gmail.com wrote: Hi, I'm looking for a portable way to download ZIP files on the internet through Python. I don't want to do os.system() to invoke 'wget', since this isn't portable on Windows. I'm hoping the core python library has a library for this. Note that I'll be using Python 3.0. Thanks. -- http://mail.python.org/mailman/listinfo/python-list This module might be of interest: http://linux.duke.edu/projects/urlgrabber/ -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: if var1 == var2:
Kirk Strauser wrote: At 2008-11-29T04:02:11Z, Mel mwil...@the-wire.com writes: You could try for item in fname: item = item.strip() This is one case where I really miss Perl's chomp function. It removes a trailing newline and nothing else, so you don't have to worry about losing leading or trailing spaces if those are important to you. ... and it's so hard to write item = item[:-1] 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: newbie question: if var1 == var2:
At 2008-12-11T17:24:44Z, rdmur...@bitdance.com writes: ' ab c \r\n'.rstrip('\r\n') ' ab c ' ' ab c \n'.rstrip('\r\n') ' ab c ' ' ab c '.rstrip('\r\n') ' ab c ' I didn't say it couldn't be done. I just like the Perl version better. -- Kirk Strauser The Day Companies -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, threading
SMALLp wrote: ... I need a tip on how to communicat4 between threads. Typically inter-thread communication is done via Queue.Queue. Look up the Queue module in your docs. a Simple example: import Queue shared_work = Queue.Queue() combined_replies = Queue.Queue() ... [distributor] in loop: shared_work.put(something_to_do) ... for n in range(workers): shared_work.put(None) # tell everybody to stop for thread in workers: thread.join(worker) # wait til they all finish combined_replies.put(None) # tell service to stop thread.join(writer)# wait til it is done. ... [workers] ... for work in iter(shared_work.get, None): do work combined_replies.put('whatever') ... ... [writer] for results in iter(combined_results.get, None): use results --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary idiom needed
Brandon wrote: I have a series of lists in format ['word', 'tagA', 'tagB']. I have converted this to a few dicts, such as one in which keys are tuples of ('word', 'tagB'), and the values are the number of times that key was found. Smells like homework without a particular application. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list