Add vs in-place add of str to list
Hi I'm trying to understand why it is that I can do >>> a = [] >>> a += 'stuff' >>> a ['s', 't', 'u', 'f', 'f'] but not >>> a = [] >>> a = a + 'stuff' Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate list (not "str") to list Can someone explain the logic? Why is the in-place add not a type error but the usual add is? (This applies to both Python 2.6rc1 and 3.0b2) Thanks Roman -- http://mail.python.org/mailman/listinfo/python-list
Re: How to read a jpg bytearray from a Flash AS3 file
[EMAIL PROTECTED] wrote: > >Thanks! I'm using form = cgi.FieldStorage(). When I print out the >contents of form, I get this: > >FieldStorage(None, None, '\xff\xd8\xff\xe0\x00\x10JFIF >\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb >\x00\x84\x00\x05\x03\x04\x04\x04\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0c >\x08\x07\x07\x07\x07\x0f\x0b\x0b\t\x0c\x11\x0f\x12\x12\x11\x0f >\x11\x11\x13\x16\x1c\x17\x13\x14\x1a\x15\x11\x11\x18!\x18\x1a\x1d\x1d >\x1f\x1f\x1f\x13\x17"$"\x1e$\x1c\x1e\x1f\x1e >\x01\x05\x05\x05\x07\x06\x07\x0e\x08\x08\x0e\x1e\x14\x11\x14\x1e\x1e >\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e >\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e >\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\xff\. > >Which is obviously the binary data of the image I want. How do I >access this data? I'm used to getting it like this: > >name = form['name'].value > >But I don't think this will work in this case. TIA. What led you to ask that here, instead of taking 60 seconds to load cgi.py in an editor and search for the FieldStorage class? -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Add vs in-place add of str to list
rs387 wrote: I'm trying to understand why it is that I can do a = [] a += 'stuff' a ['s', 't', 'u', 'f', 'f'] but not a = [] a = a + 'stuff' Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate list (not "str") to list Can someone explain the logic? Why is the in-place add not a type error but the usual add is? (This applies to both Python 2.6rc1 and 3.0b2) It's because the `+=` operator is doing the equivalent of calling the `extend` method, which treats its argument as a generic sequence, and doesn't enforce type. The same thing happens with any other sequence type as the right-hand operand; for instance, tuples: >>> a = [] >>> a += (1, 2, 3) >>> a [1, 2, 3] >>> a = [] >>> a = a + (1, 2, 3) Traceback (most recent call last): File "", line 1, in ? TypeError: can only concatenate list (not "tuple") to list -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Man is a hating rather than a loving animal. -- Rebecca West -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make smtplib.SMTP('localhost') work on window xp
zxo102 <[EMAIL PROTECTED]> wrote: > >In my case, I implement an application with python to accomplish >collecting real time data from a serial port: com1 which is connected >to some xbee hardwares. >The python logging module is used to save the information generated at >runtime into a log file. Since the site is far away from my office, I >try to >use a smtp server with the python smtplib module to send the log file >into my email account regularly so that I can check it from anywhere. It's quite likely that the correct solution is for you to use the SMTP server for the Internet provider at the remote site. When you run your own SMTP server, it is WAY too easy to leave your configuration open for spammers to abuse. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: I built a nice html templater!
Derick van Niekerk <[EMAIL PROTECTED]> wrote: > >Ok - so it's not really an awesome achievement and only handles basic >templating needs (no loops and other programming constructs) but maybe >someone will find it useful. Sure, that's what the world needed. We didn't have enough Python HTML templaters already. Did you take even 3 minutes to look for a solution before you wrote this? There is even a nearly identical solution in the Python cookbook. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Event-driven framework (other than Twisted)?
On Oct 2, 1:32 am, "James Mills" <[EMAIL PROTECTED]> wrote: > http://hg.shortcircuit.net.au/index.wsgi/pymills/file/b7498cd4c6a4/ex... Thanks for the example, but its not loading. -- http://mail.python.org/mailman/listinfo/python-list
Re: Event-driven framework (other than Twisted)?
On Oct 2, 1:28 am, "James Mills" <[EMAIL PROTECTED]> wrote: > Phillip, I have been developing a rather unique > event-driven and component architecture library > for quite some time that is (not twisted). Actually > it's nothing like twisted, but based on 2 core > concepts: > * Everything is a Component > * Everything is an Event > > It's currently called pymills.event > Let me know if you're interested, I probably > plan to re-package and re-branch this library > (the event library) at some point. I'd be very interested in seeing this. Component-based programming is something which interests me also. -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: can't pickle HASH objects?
On Oct 2, 1:51 pm, "James Mills" <[EMAIL PROTECTED]> wrote: > On Thu, Oct 2, 2008 at 3:34 PM, est <[EMAIL PROTECTED]> wrote: > > wow. It's giga-size file. I need stream reading it, md5 it. It may > > break for a while. > > So use generators and consume the stream ? > > --JamesMills > > -- > -- > -- "Problems are solved by method" no, I need to serialize half-finished digest, not file stream. Anyone got solution? -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6 final
Hmm, I was looking forward to trying this out, but the Windows installer link (http://www.python.org/ftp/python/2.6/python-2.6.msi) is presently broken (as is the link for the 64-bit Windows version). While I'm at it, I might also point out that http://www.python.org/download/windows/ is quite out-of-date. I don't really think it is worth promoting version 1.5.2 of Python (even if it is Python CE) if Python 3.0 is about to come out... -- http://mail.python.org/mailman/listinfo/python-list
Re: pyhton or json, list or array?
Hi, * bruce [2008-09-30 13:01]: > > i was told > that it's json, but i have no idea how to convert it/manipulate it.. See http://json.org/ for a list of available JSON parsers for Python. I personally used python-simplejson, and I was happy with it. :-) Regards, Bernhard -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd Errors
On Oct 2, 12:52 am, Lawrence D'Oliveiro <[EMAIL PROTECTED] central.gen.new_zealand> wrote: > In message <[EMAIL PROTECTED]>, Steven > > D'Aprano wrote: > > On Wed, 01 Oct 2008 22:14:49 +1300, Lawrence D'Oliveiro wrote: > > >> In message > >> <[EMAIL PROTECTED]>, > >> Aaron "Castironpi" Brady wrote: > > >>> Do you ever want to scream from the rooftops, "'append' operates by > >>> side-effect!"? > > >> No. It's an effect, not a side-effect. > > > "Side-effect" has the technical meaning in functional languages of any > > change of state that isn't the creation and return of a function result. > > "Side" means that it happens as the by-product of returning a function > result. ".append" isn't a function, it's a procedure. Hence the > modification of the list is the primary effect, not a side effect. I was using the technical definition from functional languages, not the literal "per word" definition. Maybe the FL crowd chose their words poorly, who knows? -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: can't pickle HASH objects?
On Oct 2, 2:44 am, est <[EMAIL PROTECTED]> wrote: > On Oct 2, 1:51 pm, "James Mills" <[EMAIL PROTECTED]> wrote: > > > On Thu, Oct 2, 2008 at 3:34 PM, est <[EMAIL PROTECTED]> wrote: > > > wow. It's giga-size file. I need stream reading it, md5 it. It may > > > break for a while. > > > So use generators and consume the stream ? > > > --JamesMills > > > -- > > -- > > -- "Problems are solved by method" > > no, I need to serialize half-finished digest, not file stream. > > Anyone got solution? I am looking at '_hashopenssl.c'. If you can find the implementation of EVP_DigestUpdate, I'll give it a shot to help you write a ctypes hack to store and write its state. -- http://mail.python.org/mailman/listinfo/python-list
Re: what does "python -i" use as input stream (stdin)?
> > I did not understand completely what you want, and rereading previous posts > I got even more confused... > Could you provide a complete description of what you want to do? > Is it a single process, or two separate processes? Running on the same > machine or remotely? All python or there is another program involved? Hehe, sory for that... I have two seperate processes on the same (windows) machine, which are both python. One is a wx GUI (a simple IDE), and the other should function as a python interpreter. The latter is a subprocess of the former, created using wx.Execute / wx.Process, and there are three pipes between the two. I wanted to start the interpreter process as "python -i my_startup_script.py". In the startup script I create a "connection thread" that reads the original standard input (a pipe to the wx GUI), and will most of the time write the read-result to a pseudofile. (In this setup, I can do special requests from the GUI, that the "connection thread" will process, for example interrupt the main thread or get introspection information.) When python finishes processing my startup script, it goes into "interpreter mode" because of the -i flag. What I want is that it will use the pseudofile as it's stdin. The result should be a python interpreter with some extra control, plus I am now able to "hijack" the tk mainloop, and this way have interactive behaviour in matplotlib. I hope it is more clear now... I wonder if this can be done, but it's no big problem if it cannot; as I said before, I already have this setup working with an interpreter inherited from code.InteractiveConsole. Which means I do not use -i, but at the end of the startup script I create an instance of that interpreter and call .interact(). Thanks again, Almar -- http://mail.python.org/mailman/listinfo/python-list
Re: ssh keepalive
<> def command ( self , command ) : """ process requested command through ssh """ print command if not self._connected : return False , "No SSH connection available" try : stdin , stdout , stderr = self._ssh.exec_command( command ) remoteStdOutContent = stdout.readlines() remoteStdErrContent = stderr.readlines() if remoteStdErrContent != [] : return False , '\n'.join(remoteStdErrContent) return True , '\n'.join(remoteStdOutContent) except paramiko.SSHException , e : # provide socket error reason back return False , str(e) -- http://mail.python.org/mailman/listinfo/python-list
Re: Database GUI generation from schema
Eric Wertman a écrit : Sorry if this is misplaced, but I could have sworn I saw a link on this list to a package that would auto-generate data entry type forms from a database schema, similar to django's auto-admin interface. Does anyone recall a package like that? I did some searching, but I've only found documentation describing such a system in the generic. Perhaps are you talking about dabo ? http://www.dabodev.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Peek inside iterator (is there a PEP about this?)
Luis Zarrabeitia wrote: > On Wednesday 01 October 2008 01:14:14 pm Peter Otten wrote: >> Luis Zarrabeitia wrote: >> > a = iter([1,2,3,4,5]) # assume you got the iterator from a function and >> > b = iter([1,2,3]) # these two are just examples. >> >> Can you provide a concrete use case? > > I'd like to... but I've refactored away all the examples I had, as soon as > I realized that I didn't know which one was the shortest sequence to put > it first. > > But, it went something like this: > > === > def do_stuff(tasks, params): > params = iter(params) > for task in tasks: > for partial_task, param in zip(task, params): > pass #blah blah, do stuff here. > print "task completed" > === > > Unfortunately that's not the real example (as it is, it shows very bad > programming), but imagine if params and/or tasks were streams beyond your > control (a data stream and a control stream). Note that I wouldn't like a > task or param to be wasted. This remains a bit foggy to me. Maybe you are better off with deques than iterators? > I didn't like the idea of changing both the 'iter' and the 'zip' (changing > only one of them wouldn't have worked). > >> > Will this iterator yield any value? Like with most iterables, a >> > construct >> > >> > if iterator: >> ># do something >> >> I don't think this has a chance. By adding a __len__ to some iterators R. >> Hettinger once managed to break GvR's code. The BDFL was not amused. > > Ouch :D > But, no no no. Adding a __len__ to iterators makes little sense (specially > in my example), and adding an optional __len__ that some iterators have > and some don't (the one that can't know their own lengths) would break too > many things, and still, wouldn't solve the problem of knowing if there is > a next element. A __nonzero__() that would move the iterator forward and > cache the result, with a next() that would check the cache before > advancing, would be closer to what I'd like. The problem was that __len__() acts as a fallback for __nonzero__(), see http://mail.python.org/pipermail/python-dev/2005-September/056649.html >> > if any(iterator): >> ># do something ... but the first true value was already consumed and >> ># cannot be reused. "Any" cannot peek inside the iterator without >> ># consuming the value. >> >> for item in iflter(bool, iterator): >># do something >>break > > It is not, but (feel free to consider this silly) I don't like breaks. In > this case, you would have to read until the end of the block to know that > what you wanted was an if (if you are lucky you may figure out that you > wanted to simulate an if test). Ok, make it for item in islice(ifilter(bool, iterator), 1): # do something then ;) > (Well, I use breaks sometimes, but most of them are because I need to test > if an iterator is empty or not) > >> Personally I think that Python's choice of EAFP over LBYL is a good one, >> but one that cannot easily be reconciled with having peekable iterators. >> If I were in charge I'd rather simplify the iterator protocol (scrap >> send() and yield expressions) than making it more complex. > > Oh, I defend EAFP strongly. On my university LBYL is preferred, so > whenever I teach python, I have to give strong examples of why I like > EAFP. > > When the iterator is empty means that there is something wrong, I wouldn't > think of using "if iterator:". That would be masquerading what should be > an exception. However, if "iterator is empty" is meaningful, that case > should go in an "else" clause, rather than "except". Consider if you need > to find the first non-empty iterator from a list (and then sending it to > another function - can't test for emptiness with a "for" there, or one > could lose the first element) You can do it def non_empty(iterators): for iterator in iterators: it = iter(iterator) try: yield chain([it.next()], it) except StopIteration: pass for it in non_empty(iterators): return process(it) but with iterators as they currently are in Python you better rewrite process() to handle empty iterators and then write for it in iterators: try: return process(it) except NothingToProcess: # made up pass That's how I understand EAFP. Assume one normal program flow and deal with problems as they occur. > But that's one of the cases where one should know what is doing. Both C# > and Java have iterators that let you know if they are finished before > consuming the item. (I didn't mean to compare, and I like java's more than > C#, as java's iterator also promote the 'use once' design). I think that may be the core of your problem. Good code built on Python's iterators will not resemble the typical Java approach. Peter -- http://mail.python.org/mailman/listinfo/python-list
docs.python.org inaccessible
Been getting 403 errors all afternoon. At one time I used to assiduously download PDF files of all the documentation I wanted to refer to. These days I've grown accustomed to just having a bunch of Web browser windows semi-permanently open. Until a rude shock like this happens to hit me. Maybe I should get back into the PDF habit again... -- http://mail.python.org/mailman/listinfo/python-list
using SSh problem!
I want to connect form a windows machine to a Linux one using SSH (I use Paramiko) and simply copy a file to Linux machine. Would you please help me how should I start? Is there any useful code? -- View this message in context: http://www.nabble.com/using-SSh-problem%21-tp19775680p19775680.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: can't pickle HASH objects?
On Oct 2, 4:22 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> wrote: > On Oct 2, 2:44 am, est <[EMAIL PROTECTED]> wrote: > > > > > > > On Oct 2, 1:51 pm, "James Mills" <[EMAIL PROTECTED]> wrote: > > > > On Thu, Oct 2, 2008 at 3:34 PM, est <[EMAIL PROTECTED]> wrote: > > > > wow. It's giga-size file. I need stream reading it, md5 it. It may > > > > break for a while. > > > > So use generators and consume the stream ? > > > > --JamesMills > > > > -- > > > -- > > > -- "Problems are solved by method" > > > no, I need to serialize half-finished digest, not file stream. > > > Anyone got solution? > > I am looking at '_hashopenssl.c'. If you can find the implementation > of EVP_DigestUpdate, I'll give it a shot to help you write a ctypes > hack to store and write its state.- Hide quoted text - > > - Show quoted text - http://cvs.openssl.org/fileview?f=openssl/crypto/evp/digest.c int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t count) { #ifdef OPENSSL_FIPS FIPS_selftest_check(); #endif return ctx->digest->update(ctx,data,count); } is this one? -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: can't pickle HASH objects?
En Wed, 01 Oct 2008 16:50:05 -0300, est <[EMAIL PROTECTED]> escribió: import md5 a=md5.md5() import pickle pickle.dumps(a) Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\pickle.py", line 1366, in dumps Pickler(file, protocol).dump(obj) File "C:\Python25\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Python25\lib\pickle.py", line 306, in save rv = reduce(self.proto) File "C:\Python25\lib\copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle HASH objects Why can't I pickle a md5 object? Is it because md5 algorithm needs to read 512-bits at a time? I need to md5() some stream, pause(python.exe quits), and resume later. It seems that the md5 and hashlib in std module could not be serialized? Yep, they're implemented in C and have no provision for serializing. If you can use the old _md5 module, it is far simpler to serialize; a md5object just contains a small struct with 6 integers and 64 chars, no pointers. With some help from ctypes (and a lot of black magic!) one can extract the desired state, and restore it afterwards: --- begin code --- import _md5 import ctypes assert _md5.MD5Type.__basicsize__==96 def get_md5_state(m): if type(m) is not _md5.MD5Type: raise TypeError, 'not a _md5.MD5Type instance' return ctypes.string_at(id(m)+8, 88) def set_md5_state(m, state): if type(m) is not _md5.MD5Type: raise TypeError, 'not a _md5.MD5Type instance' if not isinstance(state,str): raise TypeError, 'state must be str' if len(state)!=88: raise ValueError, 'len(state) must be 88' a88 = ctypes.c_char*88 pstate = a88(*list(state)) ctypes.memmove(id(m)+8, ctypes.byref(pstate), 88) --- end code --- py> m1 = _md5.new() py> m1.update("this is a ") py> s = get_md5_state(m1) py> del m1 py> py> m2 = _md5.new() py> set_md5_state(m2, s) py> m2.update("short test") py> print m2.hexdigest() 95ad1986e9a9f19615cea00b7a44b912 py> print _md5.new("this is a short test").hexdigest() 95ad1986e9a9f19615cea00b7a44b912 The code above was only tested with Python 2.5.2 on Windows, not more than you can see. It might or might not work with other versions or platforms. It may even create a (small) black hole and eat your whole town. Use at your own risk. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6 final
Chris> Also, the docs currently seem broken. Known problem. The elves are working on it. -- Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/ -- http://mail.python.org/mailman/listinfo/python-list
how best to use a dictionary in this function?
Ok, here is some code: def calc_profit(std_clicks, vip_clicks, ad_rate=200, upline_status=None): payout = {} payout_std = std_clicks * rates['std'].per_click payout_vip = vip_clicks * rates['vip'].per_click ... now note that std_clicks and vip_clicks are passed to the function. Now, I improved this function this way: def calc_profit(std_clicks, vip_clicks, ad_rate=200, upline_status=None): clicks = {} clicks['std'] = std_clicks clicks['vip'] = vip_clicks payout = {} for member_type in rates: payout[member_type] = clicks[member_type] * rates[member_type].per_click But it seems wasteful to have to re-bind the passed-in function args to a dictionary in the function. I think there must be some way to improve this code and get the dictionary built without me manually doing it... I know there is something like *args, or **args, but since docs.python.org is down, I cant check. -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: can't pickle HASH objects?
On Oct 2, 4:03 am, est <[EMAIL PROTECTED]> wrote: > On Oct 2, 4:22 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> > wrote: > > > > > On Oct 2, 2:44 am, est <[EMAIL PROTECTED]> wrote: > > > > On Oct 2, 1:51 pm, "James Mills" <[EMAIL PROTECTED]> wrote: > > > > > On Thu, Oct 2, 2008 at 3:34 PM, est <[EMAIL PROTECTED]> wrote: > > > > > wow. It's giga-size file. I need stream reading it, md5 it. It may > > > > > break for a while. > > > > > So use generators and consume the stream ? > > > > > --JamesMills > > > > > -- > > > > -- > > > > -- "Problems are solved by method" > > > > no, I need to serialize half-finished digest, not file stream. > > > > Anyone got solution? > > > I am looking at '_hashopenssl.c'. If you can find the implementation > > of EVP_DigestUpdate, I'll give it a shot to help you write a ctypes > > hack to store and write its state.- Hide quoted text - > > > - Show quoted text - > > http://cvs.openssl.org/fileview?f=openssl/crypto/evp/digest.c > > int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, > size_t count) > { > #ifdef OPENSSL_FIPS > FIPS_selftest_check(); > #endif > return ctx->digest->update(ctx,data,count); > } > > is this one? Oops, I needed 'EVP_MD_CTX'. I went Googling and found it. http://www.google.com/codesearch?hl=en&q=struct+EVP_MD_CTX+show:mV3VBLQ3bJg:LiPTUi2tojQ:CERf4Pk7bsY&sa=N&cd=5&ct=rc&cs_p=http://freshmeat.net/redir/cyassl/67102/url_zip/cyassl-0.6.2.zip&cs_f=cyassl-0.8.5/include/openssl/evp.h#l51 But does Gabriel's work for you? -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6 final
nneonneo> Hmm, I was looking forward to trying this out, but the Windows nneonneo> installer link nneonneo> (http://www.python.org/ftp/python/2.6/python-2.6.msi) is nneonneo> presently broken (as is the link for the 64-bit Windows nneonneo> version). We are aware of it. Because of the timing of the release the person who normally creates the Windows binaries was already asleep. They should be up a bit later today. -- Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how best to use a dictionary in this function?
On Oct 2, 4:18 am, Terrence Brannon <[EMAIL PROTECTED]> wrote: > Ok, here is some code: > > def calc_profit(std_clicks, vip_clicks, ad_rate=200, > upline_status=None): > payout = {} > payout_std = std_clicks * rates['std'].per_click > payout_vip = vip_clicks * rates['vip'].per_click > > ... now note that std_clicks and vip_clicks are passed to the > function. > > Now, I improved this function this way: > > def calc_profit(std_clicks, vip_clicks, ad_rate=200, > upline_status=None): > clicks = {} > clicks['std'] = std_clicks > clicks['vip'] = vip_clicks > > payout = {} > for member_type in rates: > payout[member_type] = clicks[member_type] * > rates[member_type].per_click > > But it seems wasteful to have to re-bind the passed-in function args > to a dictionary in the function. I think there must be some way to > improve this code and get the dictionary built without me manually > doing it... > > I know there is something like *args, or **args, but since > docs.python.org is down, I cant check. *args is for variable-length parameters, **args is for keyword parameters. >>> def f( **kwar ): ... print kwar ... >>> f( a=2, b=3 ) {'a': 2, 'b': 3} >>> f( 123 ) Traceback (most recent call last): File "", line 1, in TypeError: f() takes exactly 0 arguments (1 given) >>> f( a='abc' ) {'a': 'abc'} -- http://mail.python.org/mailman/listinfo/python-list
Re: using SSh problem!
In message <[EMAIL PROTECTED]>, sa6113 wrote: > I want to connect form a windows machine to a Linux one using SSH (I use > Paramiko) and simply copy a file to Linux machine. Do you want to be able to connect without having to enter a password? You'll need to set up a public/private key pair for that. -- http://mail.python.org/mailman/listinfo/python-list
docs.python.org access should be working again
Sorry for the problem with docs.python.org. Python 2.6 includes a complete rework of the Python documentation suite. There were problems with the installation location which should be resolved now. If you visit http://docs.python.org/ and still see the 2.5.2 doc page, force a page reload in your browser. -- Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/ -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6 final
On Thu, Oct 2, 2008 at 11:23 AM, <[EMAIL PROTECTED]> wrote: > >nneonneo> Hmm, I was looking forward to trying this out, but the Windows >nneonneo> installer link >nneonneo> (http://www.python.org/ftp/python/2.6/python-2.6.msi) is >nneonneo> presently broken (as is the link for the 64-bit Windows >nneonneo> version). > > We are aware of it. Because of the timing of the release the person who > normally creates the Windows binaries was already asleep. They should be up > a bit later today. > Surely you're joking! Everybody knows that python developers never sleep :-) Congratulations for the final release! Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: ssh keepalive
En Thu, 02 Oct 2008 05:26:25 -0300, loial <[EMAIL PROTECTED]> escribió: <> Still not enough. From your first post, the error was: 'NoneType' object has no attribute 'exec_command' def command ( self , command ) : """ process requested command through ssh """ print command if not self._connected : return False , "No SSH connection available" try : stdin , stdout , stderr = self._ssh.exec_command( command ) So you'll have to analyze how (and when) self._ssh might become None. This function just *uses* self._ssh - look for some other places where self._ssh is assigned to (or perhaps, deleted, if there is a class attributes set to None). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Database GUI generation from schema
En Wed, 01 Oct 2008 19:36:08 -0300, Eric Wertman <[EMAIL PROTECTED]> escribió: Sorry if this is misplaced, but I could have sworn I saw a link on this list to a package that would auto-generate data entry type forms from a database schema, similar to django's auto-admin interface. Does anyone recall a package like that? I did some searching, but I've only found documentation describing such a system in the generic. Rum? http://toscawidgets.org/documentation/rum/ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd Errors
In message <[EMAIL PROTECTED]>, Aaron "Castironpi" Brady wrote: > On Oct 2, 12:52 am, Lawrence D'Oliveiro <[EMAIL PROTECTED] > central.gen.new_zealand> wrote: > >> In message <[EMAIL PROTECTED]>, >> Steven >> >> D'Aprano wrote: >> > On Wed, 01 Oct 2008 22:14:49 +1300, Lawrence D'Oliveiro wrote: >> >> >> In message >> >> <[EMAIL PROTECTED]>, >> >> Aaron "Castironpi" Brady wrote: >> >> >>> Do you ever want to scream from the rooftops, "'append' operates by >> >>> side-effect!"? >> >> >> No. It's an effect, not a side-effect. >> >> > "Side-effect" has the technical meaning in functional languages of any >> > change of state that isn't the creation and return of a function >> > result. >> >> "Side" means that it happens as the by-product of returning a function >> result. ".append" isn't a function, it's a procedure. Hence the >> modification of the list is the primary effect, not a side effect. > > I was using the technical definition from functional languages ... Which is where the use of "side" would make sense, given that functional languages are full of functions, not procedures. -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: can't pickle HASH objects?
On Oct 2, 5:07 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Wed, 01 Oct 2008 16:50:05 -0300, est <[EMAIL PROTECTED]> escribió: > > > > > > import md5 > a=md5.md5() > import pickle > pickle.dumps(a) > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\Python25\lib\pickle.py", line 1366, in dumps > > Pickler(file, protocol).dump(obj) > > File "C:\Python25\lib\pickle.py", line 224, in dump > > self.save(obj) > > File "C:\Python25\lib\pickle.py", line 306, in save > > rv = reduce(self.proto) > > File "C:\Python25\lib\copy_reg.py", line 69, in _reduce_ex > > raise TypeError, "can't pickle %s objects" % base.__name__ > > TypeError: can't pickle HASH objects > > > Why can't I pickle a md5 object? Is it because md5 algorithm needs to > > read 512-bits at a time? > > > I need to md5() some stream, pause(python.exe quits), and resume > > later. It seems that the md5 and hashlib in std module could not be > > serialized? > > Yep, they're implemented in C and have no provision for serializing. > If you can use the old _md5 module, it is far simpler to serialize; a > md5object just contains a small struct with 6 integers and 64 chars, no > pointers. > > With some help from ctypes (and a lot of black magic!) one can extract the > desired state, and restore it afterwards: > > --- begin code --- > import _md5 > import ctypes > > assert _md5.MD5Type.__basicsize__==96 > > def get_md5_state(m): > if type(m) is not _md5.MD5Type: > raise TypeError, 'not a _md5.MD5Type instance' > return ctypes.string_at(id(m)+8, 88) > > def set_md5_state(m, state): > if type(m) is not _md5.MD5Type: > raise TypeError, 'not a _md5.MD5Type instance' > if not isinstance(state,str): > raise TypeError, 'state must be str' > if len(state)!=88: > raise ValueError, 'len(state) must be 88' > a88 = ctypes.c_char*88 > pstate = a88(*list(state)) > ctypes.memmove(id(m)+8, ctypes.byref(pstate), 88) > > --- end code --- > > py> m1 = _md5.new() > py> m1.update("this is a ") > py> s = get_md5_state(m1) > py> del m1 > py> > py> m2 = _md5.new() > py> set_md5_state(m2, s) > py> m2.update("short test") > py> print m2.hexdigest() > 95ad1986e9a9f19615cea00b7a44b912 > py> print _md5.new("this is a short test").hexdigest() > 95ad1986e9a9f19615cea00b7a44b912 > > The code above was only tested with Python 2.5.2 on Windows, not more than > you can see. It might or might not work with other versions or platforms. > It may even create a (small) black hole and eat your whole town. Use at > your own risk. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - WOW! I never expected python could be coded like that! Thanks a lot! On Oct 2, 5:19 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> wrote: > On Oct 2, 4:03 am, est <[EMAIL PROTECTED]> wrote: > > > > > > > On Oct 2, 4:22 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> > > wrote: > > > > On Oct 2, 2:44 am, est <[EMAIL PROTECTED]> wrote: > > > > > On Oct 2, 1:51 pm, "James Mills" <[EMAIL PROTECTED]> wrote: > > > > > > On Thu, Oct 2, 2008 at 3:34 PM, est <[EMAIL PROTECTED]> wrote: > > > > > > wow. It's giga-size file. I need stream reading it, md5 it. It may > > > > > > break for a while. > > > > > > So use generators and consume the stream ? > > > > > > --JamesMills > > > > > > -- > > > > > -- > > > > > -- "Problems are solved by method" > > > > > no, I need to serialize half-finished digest, not file stream. > > > > > Anyone got solution? > > > > I am looking at '_hashopenssl.c'. If you can find the implementation > > > of EVP_DigestUpdate, I'll give it a shot to help you write a ctypes > > > hack to store and write its state.- Hide quoted text - > > > > - Show quoted text - > > >http://cvs.openssl.org/fileview?f=openssl/crypto/evp/digest.c > > > int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, > > size_t count) > > { > > #ifdef OPENSSL_FIPS > > FIPS_selftest_check(); > > #endif > > return ctx->digest->update(ctx,data,count); > > } > > > is this one? > > Oops, I needed 'EVP_MD_CTX'. I went Googling and found it. > > http://www.google.com/codesearch?hl=en&q=struct+EVP_MD_CTX+show:mV3VB... > > But does Gabriel's work for you?- Hide quoted text - > > - Show quoted text - Still need some hack with py2.5 on linux. Maybe I just need soft link / usr/lib/python2.4/lib-dynload/md5.so to py2.5 :-) py2.4 is pre-installed on most of the servers, I think. -- http://mail.python.org/mailman/listinfo/python-list
Re: using SSh problem!
No, my problem isn't entering password or not ? I want to know what should I do to connect between different platform and copy a file . Lawrence D'Oliveiro wrote: > > In message <[EMAIL PROTECTED]>, sa6113 > wrote: > >> I want to connect form a windows machine to a Linux one using SSH (I use >> Paramiko) and simply copy a file to Linux machine. > > Do you want to be able to connect without having to enter a password? > You'll > need to set up a public/private key pair for that. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/using-SSh-problem%21-tp19775680p19776775.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: using SSh problem!
sa6113 wrote: No, my problem isn't entering password or not ? I want to know what should I do to connect between different platform and copy a file . Did you try searching? This looks hopeful: http://commandline.org.uk/python/2008/may/28/sftp-python/ TJG -- http://mail.python.org/mailman/listinfo/python-list
Nice websites here123
http://retube.u.yuku.com/ retube http://urporntube.u.yuku.com/ urporntube http://porhub.u.yuku.com/ porhub http://pornhubevideo.u.yuku.com/ pornhubevideo http://megarotic.u.yuku.com/ megarotic http://megaroticcom.u.yuku.com/ megarotic com -- http://mail.python.org/mailman/listinfo/python-list
Nice websites here123
http://pornhubevideo.u.yuku.com/ pornhubevideo http://retube.u.yuku.com/ retube http://megarotic.u.yuku.com/ megarotic http://megaroticcom.u.yuku.com/ megarotic com http://urporntube.u.yuku.com/ urporntube http://porhub.u.yuku.com/ porhub Если Вы выберете несколько доменов, то DNS адреса сменятся для всех выбраных доменов. -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6 final
> Surely you're joking! > Everybody knows that python developers never sleep :-) Wrong! All my collegues are Java developers and I'm the only one who sleep (and like a log). Congratulations, by the way. Olivier. -- http://mail.python.org/mailman/listinfo/python-list
Re: using SSh problem!
sa6113 wrote: > I want to connect form a windows machine to a Linux one using SSH (I use > Paramiko) and simply copy a file to Linux machine. > Would you please help me how should I start? For starters, I'd take a look at 'scp'. Other than that, what does the question you asked have to do with Python? Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
Re: using SSh problem!
One of the Python implementations of SSH is called Paramiko. Ulrich Eckhardt wrote: > > sa6113 wrote: >> I want to connect form a windows machine to a Linux one using SSH (I use >> Paramiko) and simply copy a file to Linux machine. >> Would you please help me how should I start? > > For starters, I'd take a look at 'scp'. Other than that, what does the > question you asked have to do with Python? > > Uli > > -- > Sator Laser GmbH > Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 > > -- > http://mail.python.org/mailman/listinfo/python-list > -- View this message in context: http://www.nabble.com/using-SSh-problem%21-tp19775680p19777590.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on JavaScript VM's (such as V8)?
On Sep 3, 10:02 pm, [EMAIL PROTECTED] wrote: > Berco Beute: > > > I wonder what it would take to implement Python in JavaScript so it it's been done. http://pyjamas.sf.net > > can run on those fancy new JavaScript VM's such as Chrome's V8 or that's been done, too. http://advogato.org/article/985.html > > Firefox' tracemonkey. Much the same as Python implementations in C# > > (IronPython) and Java (Jython). It would certainly bring back the fun > > in web application development. it's great :) been using it just for fun, for about 18 months. http://lkcl.net/site_code and for a personal project http://partyliveonline.com and for a commercial project which i'm sorry i can't refer you to the development site right now. > Is there anything done in that direction? yup. quite a lot. see http://groups.google.com/groups/pyjamas-dev > The mythical beast pypy is supposed able to translate Python to > Javascript too, I think. From some of my benchmarks Chrome's V8 is a > little slower than Psyco... so the matter is how much efficiently can > be Python translated in JS. well, the llpamies pyjamas branch from sep 2007 has some definite improvements in the _features_ provided (python-wise) but some time after that, one too many interoperability features were added (proper support for **kwargs) and it just... blew up, got too complicated for luiz and he abandoned the effort. i've outlined on pyjamas-dev what work needs to be done to satisfy both goals of remaining efficient and also providing support for **kwargs. one _much_ more important requirement - over-and-above "efficiency" (which isn't that bad anyway in pyjs.py) is readability. remember you have to _debug_ these ing programs in javascript, not python (which is why i did pyjamas-desktop - http://pyjd.sf.net so you could keep on using the standard python interpreter and _then_ run the same app through pyjs.py to convert it to javascript). l. -- http://mail.python.org/mailman/listinfo/python-list
Python on Javascript VMs (such as V8)
[folks, my apologies for the double-post via comp.lang.python whilst my tiny brain works backwards and notices - eventually - that comp.lang.python is mirrored from python-list duh] On Sep 3, 10:02 pm, [EMAIL PROTECTED] wrote: > Berco Beute: > > I wonder what it would take to implement Python in JavaScript so it 1200 lines of code for the compiler, and about... 800 for a basic suite of builtin types (Dict, List, set, string). http://pyjamas.sf.net so it's been done. > > can run on those fancy new JavaScript VM's such as Chrome's V8 or that's been done, too. http://advogato.org/article/985.html > > Firefox' tracemonkey. Much the same as Python implementations in C# > > (IronPython) and Java (Jython). It would certainly bring back the fun > > in web application development. it's great :) been using it just for fun, for about 18 months. http://lkcl.net/site_code and for a personal project http://partyliveonline.com and for a commercial project which i'm sorry i can't refer you to the development site right now. > Is there anything done in that direction? yup. quite a lot. see http://groups.google.com/groups/pyjamas-dev > The mythical beast pypy is supposed able to translate Python to > Javascript too, I think. From some of my benchmarks Chrome's V8 is a > little slower than Psyco... so the matter is how much efficiently can > be Python translated in JS. well, the llpamies pyjamas branch from sep 2007 has some definite improvements in the _features_ provided (python-wise) but some time after that, one too many interoperability features were added (proper support for **kwargs) and it just... blew up, got too complicated for luiz and he abandoned the effort. i've outlined on pyjamas-dev what work needs to be done to satisfy both goals of remaining efficient and also providing support for **kwargs. one _much_ more important requirement - over-and-above "efficiency" (which isn't that bad anyway in pyjs.py) is readability. remember you have to _debug_ these ing programs in javascript, not python (which is why i did pyjamas-desktop - http://pyjd.sf.net so you could keep on using the standard python interpreter and _then_ run the same app through pyjs.py to convert it to javascript). l. -- http://mail.python.org/mailman/listinfo/python-list
Determine minimum required version for a script
Can somebody remind how to check script compatibility with old Python versions? I can remember PHP_CompatInfo class for PHP that parses a script or directory to find out the minimum version and extensions required for them to run, and I wonder if there was anything like this for Python? -- --anatoly t. -- http://mail.python.org/mailman/listinfo/python-list
Re: Add vs in-place add of str to list
On Oct 2, 8:11 am, Erik Max Francis <[EMAIL PROTECTED]> wrote: > It's because the `+=` operator is doing the equivalent of calling the > `extend` method, which treats its argument as a generic sequence, and > doesn't enforce type. I see. Do you know whether this is seen as a problem with the language design? If so, this could be fixed by changing list.__add__ to call .extend on the left argument if it's a list... Or, by changing __iadd__ to throw a TypeError, whichever way around is seen as more correct/desirable. -- http://mail.python.org/mailman/listinfo/python-list
Ctypes behave differenty on windows 2000 and windows XP
Hi, Im facing a strange problem with ctypes module on windows 2000. I did not face this problem with the windows Xp. The problem is this code and specifically "c_long" which behave differently on win2000 and winxp from ctypes import * h = windll.LoadLibrary("C:\\Windows\\System32\\myDll.dll") print h ver = getattr(h, "myDll_GetVersion") versionArr = c_long * 4 version = versionArr(0, 0, 0, 0) print ver(version) dllVersionStr = "v%d.%d.%d.%d" % tuple(version) print dllVersionStr The same code appears to work on windows xp with dllVersionStr printing as v1.3.5.0 But on wIindows 2000 it prints v0.0.0.0 Please suggest why does it happen. Thanks and regards, Rajat -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE doesn't run on OSX 10.3.9
Just installed TclTkAquaBI-8.4.9.0.dmg from http://tcltkaqua.sourceforge.net/...still have no IDLE startup... Please let me know other ideas...thanks. -Tom On Oct 1, 9:22 am, Kevin Walzer <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Just did a new install of Tcl/tk from activestate.com and IDLE still > > not working... > > > -Tom > > Did you install Tcl/Tk 8.5? It won't work with the build of Python from > python.org (it looks for 8.4). > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Sample code required to validate a xml file against XSD
Hi Does anybody have a python xample program to validate a xml file against a XSD. regards Hrisy -- http://mail.python.org/mailman/listinfo/python-list
python-2.6
Hi all. I've installed on may MacOS X 10.4.11 (PPC) Python-2.5.2, numpy and scipy. Now I'm interested to insall Python-2.6. My question is: What will happen to may scientific modules if now I jump fro 2.5.2 to 2.6? I've to reinstall numpy and scipy? Thanks in advance for any answer. Luca -- Email.it, the professional e-mail, gratis per te: http://www.email.it/f Sponsor: Scopri i games più scaricati su cellulare! Gioca la tua partita! Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=8272&d=20081002 -- http://mail.python.org/mailman/listinfo/python-list
Re: Peek inside iterator (is there a PEP about this?)
On Wed, 01 Oct 2008 16:14:09 -0400, Terry Reedy wrote: > Iterators are intended for 'iterate through once and discard' usages. Also for reading files, which are often seekable. I don't disagree with the rest of your post, I thought I'd just make an observation that if the data you are iterating over supports random access, it's possible to write an iterator that also supports random access. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: python-2.6
On Oct 2, 8:33 am, [EMAIL PROTECTED] wrote: > Hi all. > > I've installed on may MacOS X 10.4.11 (PPC) Python-2.5.2, numpy and scipy. > Now I'm interested to insall Python-2.6. My question is: What will happen to > may scientific modules if now I jump fro 2.5.2 to 2.6? I've to reinstall > numpy and scipy? > > Thanks in advance for any answer. > > Luca > -- Yes. You'll need to reinstall those modules for 2.6. You can try copying and pasting their folders from your 2.5 installation, but I doubt it will work. Mike -- http://mail.python.org/mailman/listinfo/python-list
Pyjamas 0.3 Release: python-to-javascript compiler and AJAX library
Pyjamas 0.3 --- Pyjamas is a python-to-javascript compiler and an AJAX-based Widget toolkit for Web Development (for the sister project, running pyjamas-based apps on the desktop, see http://pyjd.sf.net which is based on http://webkit.org). Pyjamas Applications are written in python, yet run in all major web browsers - as javascript. Specifically, the 0.3 release adds support for IE7. Pyjamas is a port of Google Web Toolkit to python. So, where GWT is a Java-to-Javscript compiler plus widget set, Pyjamas is a python-to-javascript compiler plus widget set. Documentation and details are available at the web site, http://pyjamas.sf.net Download available at: https://sourceforge.net/project/showfiles.php?group_id=239074 -- http://mail.python.org/mailman/listinfo/python-list
Re: Add vs in-place add of str to list
rs387 wrote: > On Oct 2, 8:11 am, Erik Max Francis <[EMAIL PROTECTED]> wrote: >> It's because the `+=` operator is doing the equivalent of calling the >> `extend` method, which treats its argument as a generic sequence, and >> doesn't enforce type. > > I see. Do you know whether this is seen as a problem with the language > design? No. [1,2,3] + [4,5,6] produces [1,2,3,4,5,6] not [1,2,3,[4,5,6]] Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE doesn't run on OSX 10.3.9
Now I downloaded the latest Python 2.6 that came out yesterday, and also downloaded the latest ActiveTcl... I run a Terminal, cd /usr/local/bin, and type "idle2.6"...get this error message: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/Current/bin/ idle2.6", line 5, in main() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/idlelib/PyShell.py", line 1382, in main root = Tk(className="Idle") File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/lib-tk/Tkinter.py", line 1645, in __init__ self._loadtk() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/lib-tk/Tkinter.py", line 1659, in _loadtk % (_tkinter.TK_VERSION, tk_version) RuntimeError: tk.h version (8.4) doesn't match libtk.a version (8.5) Thanks for any help. -Tom On Oct 1, 9:22 am, Kevin Walzer <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Just did a new install of Tcl/tk from activestate.com and IDLE still > > not working... > > > -Tom > > Did you install Tcl/Tk 8.5? It won't work with the build of Python from > python.org (it looks for 8.4). > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On Wed, 01 Oct 2008 10:38:12 +, Marc 'BlackJack' Rintsch wrote: >> The first problem with "with" is that it looks like the Pascal "with" >> statement, but acts nothing like it. That may confuse anyone with >> Pascal experience, and there are a lot of us out there. > > But Python is not Pascal either. Nonetheless a Pascal coder might guess > what the ``with`` does. Not all the gory details but that it opens a > file and introduces `lines` should be more or less obvious to someone > who has programmed before. But that's not what the with statement does. It doesn't open a file and it doesn't introduce lines. That's what open() does. So what you say is "obvious" is actually wrong. To a newbie who knows nothing about context managers, the statement with open(filename) as lines will look like "syntactic fat" (like syntactic sugar but harder to digest and more fattening) for the simpler code: lines = open(filename) [snip] > Even if newbies don't understand all the details they should be > introduced to ``with`` right away IMHO. Because if you explain all the > details, even if they understand them, they likely will ignore the > knowledge because doing it right is a lot of boiler plate code. So > usually people write less robust code and ``with`` is a simple way to > solve that problem. So what you're saying is that we should encourage cargo-cult coding. "Write this boilerplate, because I tell you that if you do, good things will happen." Newbies aren't going to be writing robust code anyway. The ability to write robust code is one of the things which distinguishes experienced coders from newbies. If they don't understand what the code is actually doing, they're going to make mistakes like these: import urllib2 try: result = urllib2.open('http://www.python.org') except IOError, URLError: print "Can't reach website" except HTTPError: print "Page not found" [much more snippage] > Why on earth has everything to be guessable for someone who doesn't > know Python or even programming at all? Oh please. Don't take my words out of context. I'm not talking about "everything", and I'm not suggesting that advanced programming features should be prohibited and we should write to the level my grandmother would understand. The context was that a Fortran programmer asked for some help in writing a piece of code in Python. Your answer was entirely opaque and undecipherable to the OP. If your intention in answering was to teach the OP how to write Python code, you failed, because the OP couldn't understand your code! You can argue with me until Doomsday and it won't change that basic fact. Your answer may have solved the OP's *technical* problem, but it didn't do anything to solve the OP's *actual* problem, which was that he didn't know enough basic Python techniques to solve a simple problem. And that's the issue I was commenting on. [more snippage] > > Nevertheless, for people coming from less dynamic languages than > > Python (such as Fortran), it is a common idiom to never use the same > > variable for two different things. It's not a bad choice really: > > imagine reading a function where the name "lines" started off as an > > integer number of lines, then became a template string, then was used > > for a list of character positions... > > Which I'm not doing at all. It has the same duck type all the time: > "iterable of lines". It has nothing to do with duck typing and everything to do with re-use of variables (or in Python, names) for different "things". Just because "lines" has the same duck-type doesn't mean they are conceptually the same things. If they were, the assignments would be null-ops. There is a programming principle that says never re-use variables. It makes it harder for the programmer to figure out what the variable represents and for some languages, it can defeat compiler optimizations. Now, I personally wouldn't treat this principle as a law. I'd treat it as a guideline with just as many exceptions as examples. But there's no doubt in my mind that reuse of names can lead to hard to understand code, particularly if the reader is not used to the language and is already struggling to understand it. [snippity snip] > *I* think I would do Python a disservice if I encourage people to > continue writing Python code as if it where language X or pretending > Python is all about "readable, executable Pseudocode for anyone". There's no "pretending". Python is excellent for writing readable, executable pseudo-code for anyone. With Python 3.0, GvR had the opportunity to strip Python of all the features that makes Python easy to learn, and he didn't. Python still has features that are easy for newbies, and features that are powerful for experienced coders, and that friendliness for newbies isn't going away. That's a good thing. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
code critique requested - just 60 lines
Hi, I would like some feedback on how you would improve the following program: http://www.bitbucket.org/metaperl/ptc_math/src/21979c65074f/payout.py Basically, using non-strict dictionary keys can lead to bugs, so that worried me. Also, I'm not sure that my code is as crisp and concise as it could be. I also did not like the long string representation in the Scenerio class. It is hard to read and error-prone to code. Any feedback on how you would've written this differently is welcome, either by commenting below, or by checking out the repo and checking it back in! class Rates: def __init__(self, per_click, per_ref_click): self.per_click = per_click self.per_ref_click = per_ref_click def __str__(self): return 'per_click: %.2f per_ref_click: %.2f' % (self.per_click, self.per_ref_click) ad_rate = 200 # 2 dollars for 100 clicks # http://code.activestate.com/recipes/278259/ def sumDict(d): return reduce(lambda x,y:x+y, d.values()) rates = {} rates['std'] = Rates(per_click=1,per_ref_click=0.5) rates['vip'] = Rates(per_click=1.25, per_ref_click=1.25) class Scenario: def __init__(self, std_clicks, vip_clicks, upline_status): self.clicks = {} self.payout = {} self.ad_rate = 200 self.clicks['std'] = std_clicks self.clicks['vip'] = vip_clicks self.upline_status = upline_status def calc_profit(self): for member_type in rates: self.payout[member_type] = self.clicks[member_type] * rates[member_type].per_click if self.upline_status is None: self.payout['upline'] = 0 else: self.payout['upline'] = sumDict(self.clicks) * rates[upline_status].per_ref_click #print "rates: %s self.clicks: %d upline payout: %.1f\n" % (rates[upline_status], sumDict(self.clicks), self.payout['upline']) return ad_rate - sumDict(self.payout) def __str__(self): profit = self.calc_profit() return 'upline_status: %s upline_payout: %.1f\n\tstd_clicks: %d std_payout %.1f vip_clicks: %d vip_payout: %.1f\n\t\tProfit: %.1f \n' % (self.upline_status, self.payout['upline'], self.clicks['std'], self.payout['std'], self.clicks['vip'], self.payout['vip'], profit) scenario = [] for upline_status in [None, 'std', 'vip']: for vip_clicks in [0, 25, 50, 75, 100]: std_clicks = 100 - vip_clicks scenario.append(Scenario(std_clicks, vip_clicks, upline_status)) # really, we could've printed the objects as they were made, but for debugging, I kept creation and # printing as separate steps for s in scenario: print s -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd Errors
On Thu, 02 Oct 2008 18:52:58 +1300, Lawrence D'Oliveiro wrote: > In message <[EMAIL PROTECTED]>, > Steven D'Aprano wrote: > >> On Wed, 01 Oct 2008 22:14:49 +1300, Lawrence D'Oliveiro wrote: >> >>> In message >>> <[EMAIL PROTECTED]>, >>> Aaron "Castironpi" Brady wrote: >>> Do you ever want to scream from the rooftops, "'append' operates by side-effect!"? >>> >>> No. It's an effect, not a side-effect. >> >> "Side-effect" has the technical meaning in functional languages of any >> change of state that isn't the creation and return of a function >> result. > > "Side" means that it happens as the by-product of returning a function > result. Not in functional programming circles. This is what Paul Graham says about "side-effect" in Lisp: "A side-effect is some change to the state of the world that happens as a consequence of evaluating an expression." http://lib.store.yahoo.net/lib/paulgraham/acl2.txt It is common to refer to procedures (in languages which have them, like Pascal) as always operating by side-effect. I remember being taught that in Comp Sci classes in the mid 1980s. > ".append" isn't a function, it's a procedure. Hence the > modification of the list is the primary effect, not a side effect. Python doesn't have procedures. list.append is a function, and it returns None. That's why hardly a week goes by without somebody failing to read the Fine Manual and being surprised why code like this doesn't work: alist = [1, 2, 3] alist = alist.append(4) print len(alist) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: code critique requested - just 60 lines
On Thu, 02 Oct 2008 07:51:30 -0700, Terrence Brannon wrote: > Hi, I would like some feedback on how you would improve the following > program: > http://www.bitbucket.org/metaperl/ptc_math/src/21979c65074f/payout.py Well, for starters, I'd say that's the WORST implementation of Quicksort I've every seen!!! *wink* Seriously, the first thing I'd say is that you need to document what the program is supposed to do! It's a bit much to expect us to guess what it does, and then see if it does what we think it should do. What's the purpose of the program? > Basically, using non-strict dictionary keys can lead to bugs, so that > worried me. What's a "non-strict dictionary key"? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
windows help files ?
Hello, I've 2 questions about python help files: 1. how can I launch the windows help file (CHM), from python with a keyword as argument ? 2. now when my program should also run under Linux/Mac, how should I call the help file under Linux/Mac. Going to the website for the help information is not an option. thanks, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: Add vs in-place add of str to list
On Oct 2, 3:50 pm, Mel <[EMAIL PROTECTED]> wrote: > rs387 wrote: > > I see. Do you know whether this is seen as a problem with the language > > design? > > No. OK, I get it now. I was assuming that the "+" could be implemented in terms of "+=" as follows: def add(x,y): temp = list(x) temp += y return temp But it turns out that this is not what "+" means at all. A bit of a gotcha... Roman -- http://mail.python.org/mailman/listinfo/python-list
Re: using SSh problem!
On Oct 2, 3:27 am, sa6113 <[EMAIL PROTECTED]> wrote: > No, my problem isn't entering password or not ? > I want to know what should I do to connect between different platform and > copy a file . > > Lawrence D'Oliveiro wrote: > > > In message <[EMAIL PROTECTED]>, sa6113 > > wrote: > > >> I want to connect form a windows machine to a Linux one using SSH (I use > >> Paramiko) and simply copy a file to Linux machine. > > > Do you want to be able to connect without having to enter a password? > > You'll > > need to set up a public/private key pair for that. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > View this message in > context:http://www.nabble.com/using-SSh-problem%21-tp19775680p19776775.html > Sent from the Python - python-list mailing list archive at Nabble.com. I do it by wrapping "plink". http://www.chiark.greenend.org.uk/~sgtatham/putty/ I believe you can also install a version of OpenSSH on Windows. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
set DOS environment variable
Hi all, Can Python set a DOS environment variable? TIA, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: set DOS environment variable
On Thu, Oct 2, 2008 at 11:18 AM, bill <[EMAIL PROTECTED]> wrote: > Hi all, > > Can Python set a DOS environment variable? > > TIA, > > Bill I'd look at http://www.python.org/doc/2.5.2/lib/os-procinfo.html . It looks like putenv should do what you want. It might only affect the current process and things started from it using Popen, though. -dan -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6 final
On Oct 2, 7:46 am, Barry Warsaw <[EMAIL PROTECTED]> wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I > am happy to announce the release of Python 2.6 final. This is the > production-ready version of the latest in the Python 2 series. > > There are many new features and modules, improvements, bug fixes, and > other changes in Python 2.6. Please see the "What's new" page for > details > > http://docs.python.org/dev/whatsnew/2.6.html > > as well as PEP 361 > > http://www.python.org/dev/peps/pep-0361/ > > While Python 2.6 is backward compatible with earlier versions of > Python, 2.6 has many tools and features that will help you migrate to > Python 3. Wherever possible, Python 3.0 features have been added > without affecting existing code. In other cases, the new features can > be enabled through the use of __future__ imports and command line > switches. > > Python 3.0 is currently in release candidate and will be available > later this year. Both Python 2 and Python 3 will be supported for the > foreseeable future. > > Source tarballs, Windows installers, and Mac disk images can be > downloaded from the Python 2.6 page: > > http://www.python.org/download/releases/2.6/ > > (Please note that due to quirks in the earth's time zones, the Windows > installers will be available shortly.) > > Bugs can be reported in the Python bug tracker: > > http://bugs.python.org > > Enjoy, > - -Barry > > Barry Warsaw > [EMAIL PROTECTED] > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) > > -BEGIN PGP SIGNATURE- > Version: GnuPG v1.4.9 (Darwin) > > iQCVAwUBSOREJ3EjvBPtnXfVAQLAigP/aEnrdvAqk7wbNQLFbmBonIr2YQbd1vEu > TyTr5imYXFWGNfv1/JMeMBjMfwpHi1bgPEDTLEZdhDRNj/G1h4NqqnpfJS0lfIaU > 4JBKwnsO80se/RGyupcs5f09UdKxOljhbFKEw46CHDkd9lE+cqy2yhetEwyx3c3+ > AVC11sjcO54= > =Oxo3 > -END PGP SIGNATURE- Congratulations! Konstantin -- http://mail.python.org/mailman/listinfo/python-list
Re: code critique requested - just 60 lines
Terrence Brannon, I suggest you to shorten a lot some of those very long lines. > # http://code.activestate.com/recipes/278259/ > def sumDict(d): > return reduce(lambda x,y:x+y, d.values()) Not all recipes are good, and that looks bad in various ways. Try this: def sumDictValues(d): return sum(d.itervalues()) But probably it's better to inline that operation. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: code critique requested - just 60 lines
On Thu, 02 Oct 2008 07:51:30 -0700, Terrence Brannon wrote: > Hi, I would like some feedback on how you would improve the following > program: > http://www.bitbucket.org/metaperl/ptc_math/src/21979c65074f/payout.py Okay, I've read over the code, and tried to guess from context what it is supposed to do. I've added documentation (based on my guesses!) and modified the code in a few places. I've tried not to radically change the overall design of your code. Some comments: Readable is more important than concise. There's no prize for reducing the number of lines or leaving out comments. I'm not really sure that your Scenario code gains much by being based on class instances. Perhaps ordinary functions would be easier to understand? That's probably a matter of taste though. I don't consider it a good idea for __str__ to be used for complicated formatted results. In general, I would expect str(obj) to return a simple string version of the object. (Note that "simple" doesn't necessarily mean short.) Your Rates class is simple enough that you could probably replace it with a plain tuple: rates = { # lookup table for standard and VIP payment rates. 'std': (1, 0.5), 'vip': (1.25, 1.25)} And then later in the code rates[member_type].per_click would become rates[member_type][0]. I wouldn't do that for more than two fields per record. An even better idea would be the NamedTuple found here: http://code.activestate.com/recipes/500261/ which is included in Python 2.6. For your simple purposes, the class Rate is probably good enough. Here's my code, untested so there's no guarantee it will work. Also, because I'm lazy I haven't tried to fix long lines that have word- wrapped, sorry. I make no claim of copyright on the following, feel free to use it or discard it. == class Rates: """Record holding two fields. The fields are payment rates in cents per click and per referred(?) click. (FIXME : what is per_ref_click???) """ def __init__(self, per_click, per_ref_click): self.per_click = per_click self.per_ref_click = per_ref_click def __str__(self): return '' % (self.per_click, self.per_ref_click) ad_rate = 200 # 2 dollars for 100 clicks FIXME: is this actually used? rates = { # lookup table for standard and VIP payment rates. 'std': Rates(per_click=1, per_ref_click=0.5), 'vip': Rates(per_click=1.25, per_ref_click=1.25) } class Scenario: """Scenerio is a financial What-If calculation.""" def __init__(self, std_clicks, vip_clicks, upline_status): """Initialise an instance with: std_clicks = the number of standard clicks to be paid (???) vip_clicks = the number of VIP clicks to be paid (???) upline_status = one of None, "std" or "vip" (but I don't know what the different statuses mean...) """ self.clicks = {'std': std_clicks, 'vip' = vip_clicks} self.payout = {} self.ad_rate = 200 self.upline_status = upline_status self.setup_payup() def setup_payup(self): """Set up the payout dictionary.""" for member_type in rates: # FIXME: should rates be global? self.payout[member_type] = self.clicks[member_type] * rates [member_type].per_click if self.upline_status is None: self.payout['upline'] = 0 else: self.payout['upline'] = sum(self.clicks.values()) * rates [upline_status].per_ref_click def calc_profit(self): """Return the profit made.""" return self.ad_rate - sum(self.payout.values()) def display(self): """Pretty print a nicely formatted table of the scenario.""" profit = self.calc_profit() template = """ Scenario: === Upline status: %5s Upline payout: %.1f Std clicks: %5d Std payout: %.1f VIP clicks: %5d VIP payout: %.1f Profit: %.1f """ s = self # alias to save space return template % (s.upline_status, s.payout['upline'], s.clicks['std'], s.payout['std'], s.clicks['vip'], s.payout['vip'], profit) if __name__ == '__main__': # Set up some scenarios. scenarios = [] for upline_status in [None, 'std', 'vip']: for vip_clicks in [0, 25, 50, 75, 100]: std_clicks = 100 - vip_clicks scenarios.append( Scenario(std_clicks, vip_clicks, upline_status) ) # And display them. for s in scenarios: print s.display() -- http://mail.python.org/mailman/listinfo/python-list
problem with sockets code
Hello, I can't seem to get my sockets code to work right. Here is what I have inside my RequestHandler handle() function: total_data=[] data = True logger_server.debug(self.__class__.__name__ + ' set data = True') while data: logger_server.debug(self.__class__.__name__ + ' receive first readline() of data') data = self.rfile.readline().strip() logger_server.debug(self.__class__.__name__ + ' first readline() of data = %s' % data) total_data.append(data) receivedCommand = '\n'.join(total_data) And this is what I have inside my client code sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect(('localhost',5001)) sock.sendall('Hello, world\r\n') data = sock.recv(1024) sock.close() print 'Received', repr(data) There's a little more to it, but this is enough for me to ask my question. The problem is that I can't get the server loop (while data:) to stop without closing the connection, but I want to receive something back from the server before closing the sockets connection. My logs show that the server never leaves the loop. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: windows help files ?
On Oct 2, 9:13 am, Stef Mientki <[EMAIL PROTECTED]> wrote: > Hello, > > I've 2 questions about python help files: > > 1. how can I launch the windows help file (CHM), from python with a > keyword as argument ? > > 2. now when my program should also run under Linux/Mac, how should I > call the help file under Linux/Mac. > > Going to the website for the help information is not an option. > > thanks, > Stef You say that you can't send them to a website for help files. Can you make the help files HTML and launch them locally in a browser (no internet connection required)? That would enable you to use the same mechanism on all platforms. Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Sample code required to validate a xml file against XSD
On Oct 2, 7:32 am, hrishy <[EMAIL PROTECTED]> wrote: > Hi > > Does anybody have a python xample program to validate a xml file against a > XSD. > > regards > Hrisy I just googled "python validate a xml file against XSD" and found this: http://mail.python.org/pipermail/xml-sig/2003-March/009244.html hope it helps. Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Database GUI generation from schema
> Perhaps are you talking about dabo ? > http://www.dabodev.com Yes, that was it. Thanks! I was a little dissapointed to see that the wikipedia entry for that software was deleted. Is dabo not widely used? -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: pylab without X11
Thanks that worked ! I changed the backend to Agg. Allthough a problem there is that with the backend Agg you only can write the resulting image to a file or a file like object, it does not accept the (apache) request handler to write the file to. And I do not want to save the file to disk first before sending to the client. WJV marc wrote: This may help you ... or not You may have to change your backend : p13 of the matplotlib user guide: backends p17 how to change the backend in the matplotlibrc An example of matplotlibrc ( backend choice is at the beginning ): http://matplotlib.sourceforge.net/matplotlibrc You may choose PS or SVG or pdf, there might be other possibilities, I do not know To save the file : savefig Marc Willem-Jan Vriend a écrit : I want to use pylab (matplotlib) on a machine without X11. I'm trying to generate onthefly graphics for an apache2 web service, so they do not have to be displayed on this machine ! When i do pylab.figure() I get the error TclError: couldn't connect to display ":0.0" I tried setting the DISPLAY environment variable to "", ":0.0" but I got the same error message. Any help is very much appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: index all instances by id - a memory leak?
On Oct 1, 10:35 pm, Jason Scheirer <[EMAIL PROTECTED]> wrote: > On Oct 1, 10:01 pm, Dan Barbus <[EMAIL PROTECTED]> wrote: > > > On Oct 2, 7:54 am, Dan Barbus <[EMAIL PROTECTED]> wrote: > > > > def getItemById(id): > > > return _itemsById[id] > > > I just saw that this won't compile. Still, ignoring this, I thing the > > purpose of the code is pretty clear. > > > Thanks for any feedback. > > Check the weakref module, you can create a WeakValueDictionary which > will not increment the refcount of the value, and will return None > after it's been garbage collected. Another idea: have an AbstractFactory that keeps track of instances created. When you done, delete the abstract factory, which will delete the internal index. You'll have to figure out how to pass the factory around, and when to delete it. Weakref sounds better, overall. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE doesn't run on OSX 10.3.9
Looks like installing TclTkAqua-8.4.10.dmg fixed it...IDLE runs now! -Tom On Oct 1, 9:22 am, Kevin Walzer <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Just did a new install of Tcl/tk from activestate.com and IDLE still > > not working... > > > -Tom > > Did you install Tcl/Tk 8.5? It won't work with the build of Python from > python.org (it looks for 8.4). > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Python equivalent of Perl e flag with regular expression
I have lines that look like this: select column1, 'select' as type from table where column2 = 'foo' I want to return: SELECT column1, 'select' AS type FROM table WHERE column2 = 'foo' This is SQL with the keywords converted to uppercase. Note that the second "select" string is not a keyword and thus I do not want to convert it to uppercase. Thus, I don't think the string.replace() method will work for me. With Perl I might do something like this: $line =~ s/(select)/uc($1)/e; More generally: for $keyword in (@keyword) { $line =~ s/($keyword)/uc($1)/e; } How would I do this with Python? -- This e-mail transmission may contain information that is proprietary, privileged and/or confidential and is intended exclusively for the person(s) to whom it is addressed. Any use, copying, retention or disclosure by any person other than the intended recipient or the intended recipient's designees is strictly prohibited. If you are not the intended recipient or their designee, please notify the sender immediately by return e-mail and delete all copies. OppenheimerFunds may, at its sole discretion, monitor, review, retain and/or disclose the content of all email communications. == -- http://mail.python.org/mailman/listinfo/python-list
self signing a py2exe winxp executable with signtool
Hi All, I am trying to figure out how to self sign a py2exe winxp executable with signtool. Anyone know? I saw this which looked kind of promising: http://markmail.org/message/zj5nzechzgmjuu7c#query:signtool%20python+page:1+mid:s4jrb2hter4zxvg3+state:results -Tim P.S. Python rocks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Database GUI generation from schema
On Thu, Oct 2, 2008 at 11:24 AM, Eric Wertman <[EMAIL PROTECTED]> wrote: >> Perhaps are you talking about dabo ? >> http://www.dabodev.com > > Yes, that was it. Thanks! I was a little dissapointed to see that > the wikipedia entry for that software was deleted. Is dabo not widely > used? Depends on your definition of 'widely'. :) I know that there are several hundred subscribers to the dabo-users list. Perhaps if you asked there you might get a better idea of just how many people use Dabo. I'm curious about the Wikipedia entry. I read the deletion page arguments, but I don't know enough about how the editors decide these things to comment. I wonder what it would take to get it restored? -- p.d. -- http://mail.python.org/mailman/listinfo/python-list
javascript to python
Could someone help me translate to something that would close to it in python? The anonymous functions are giving me problems. var dataListener = { data : "", onStartRequest: function(request, context){}, onStopRequest: function(request, context, status){ instream.close(); outstream.close(); listener.finished(this.data); }, onDataAvailable: function(request, context, inputStream, offset, count){ this.data += instream.read(count); }, }; -- http://mail.python.org/mailman/listinfo/python-list
Re: code critique requested - just 60 lines
On Thu, 02 Oct 2008 07:51:30 -0700, Terrence Brannon wrote: > Hi, I would like some feedback on how you would improve the following > program: > http://www.bitbucket.org/metaperl/ptc_math/src/21979c65074f/payout.py > > Basically, using non-strict dictionary keys can lead to bugs, so that > worried me. Also, I'm not sure that my code is as crisp and concise as > it could be. I also did not like the long string representation in the > Scenerio class. It is hard to read and error-prone to code. > > Any feedback on how you would've written this differently is welcome, > either by commenting below, or by checking out the repo and checking it > back in! > > class Rates: > > def __init__(self, per_click, per_ref_click): > self.per_click = per_click > self.per_ref_click = per_ref_click You could use a better name, something that contains "price" or "cost" or something on that line, it is not immediately obvious what is per_click. > def __str__(self): > return 'per_click: %.2f per_ref_click: %.2f' % > (self.per_click, self.per_ref_click) > > > ad_rate = 200 # 2 dollars for 100 clicks > > # http://code.activestate.com/recipes/278259/ def sumDict(d): > return reduce(lambda x,y:x+y, d.values()) > > > rates = {} > rates['std'] = Rates(per_click=1,per_ref_click=0.5) rates['vip'] = > Rates(per_click=1.25, per_ref_click=1.25) It's not a really good idea to interleave module-level code and class/ function declarations. Python's code usually put all module-level code below all declarations. (of course there are exceptions too, such as higher level functions, although now there are decorators to avoid it) > class Scenario: > > > > def __init__(self, std_clicks, vip_clicks, upline_status): > self.clicks = {} > self.payout = {} > self.ad_rate = 200 > > self.clicks['std'] = std_clicks > self.clicks['vip'] = vip_clicks > self.upline_status = upline_status > > def calc_profit(self): > for member_type in rates: Global variables... avoid them unless you have to... It's better (in this case) to pass rates to the __init__ function. > self.payout[member_type] = self.clicks[member_type] * > rates[member_type].per_click > if self.upline_status is None: > self.payout['upline'] = 0 > else: > self.payout['upline'] = sumDict(self.clicks) * > rates[upline_status].per_ref_click > #print "rates: %s self.clicks: %d upline payout: %.1f\n" % > (rates[upline_status], sumDict(self.clicks), self.payout['upline']) > return ad_rate - sumDict(self.payout) > > > def __str__(self): > profit = self.calc_profit() > return 'upline_status: %s upline_payout: %.1f\n\tstd_clicks: > %d std_payout %.1f vip_clicks: %d vip_payout: %.1f\n\t\tProfit: %.1f \n' > % (self.upline_status, self.payout['upline'], self.clicks['std'], > self.payout['std'], self.clicks['vip'], self.payout['vip'], profit) Ewww NEVER WRITE A LINE THAT LONG... (and with \n) Instead python have multi-line string: '''blah blah''' or """blah blah""" A good practice is to limit a line to be < 80 chars. > scenario = [] > > for upline_status in [None, 'std', 'vip']: rather than using None, you should use another string (perhaps 'N/A', 'Nothing'), this way the code in your class above wouldn't have to special case None. > for vip_clicks in [0, 25, 50, 75, 100]: > std_clicks = 100 - vip_clicks > scenario.append(Scenario(std_clicks, vip_clicks, > upline_status)) > > # really, we could've printed the objects as they were made, but for > debugging, I kept creation and > # printing as separate steps > for s in scenario: > print s Separating object creation (model) and printing (view) is a good thing, it's a step toward MVC (Model, View, Controller). Your code could use some documentation/comments. -- http://mail.python.org/mailman/listinfo/python-list
Re: javascript to python
On Oct 2, 5:54 pm, Joe Hrbek <[EMAIL PROTECTED]> wrote: > Could someone help me translate to something that would close to it in > python? The anonymous functions are giving me problems. class dataListener: def __init__(self): data = "" def onStartRequest(self, request, context): pass def onStopRequest(self, request, context, status): # TODO: pass these three in to dataListener as # params to the constructor, so it's # def __init__(self, instream, outstream, listener) # and do self.instream = instream global instream global outstream global listener instream.close() outstream.close() listener.finished(self.data) def onDataAvailable(self, request, context, inputStream, offset, count): global instream self.data += instream.read(count) question. why are request and context being ignored? why is there an inputStream argument to onDataAvailable, yet there's a global variable (in the javascript) called instream? is it the same? all this, and more, thanks to the awfulness that is javascript :) for fits and giggles, compile the above python using pyjs.py, the python-to-javascript compiler (see http://pyjamas.sf.net) and compare the resultant javascript to your original code-fragment. l. -- http://mail.python.org/mailman/listinfo/python-list
Re: windows help files ?
On Thu, 02 Oct 2008 17:13:50 +0200, Stef Mientki wrote: > Hello, > > I've 2 questions about python help files: Python help files or your program's help files? > 1. how can I launch the windows help file (CHM), from python with a > keyword as argument ? I'm not really sure, but isn't CHM obsoleted by Microsoft? > 2. now when my program should also run under Linux/Mac, how should I > call the help file under Linux/Mac. In Linux they usually use the 'man' commands to get help, but python's docstring viewer has a less-like pager (or was it less) in Linux, just call the built-in function help(someClass) (also works in Windows, although I believe there is no pager in windows). > Going to the website for the help information is not an option. > > thanks, > Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: javascript to python
Joe Hrbek a écrit : Could someone help me translate to something that would close to it in python? The anonymous functions are giving me problems. var dataListener = { data : "", onStartRequest: function(request, context){}, onStopRequest: function(request, context, status){ instream.close(); outstream.close(); listener.finished(this.data); }, onDataAvailable: function(request, context, inputStream, offset, count){ this.data += instream.read(count); }, }; class DataListener(object): def __init__(self): self.data = '' def on_start_request(self, request, context): pass def on_stop_request(self, request, context, status): instream.close() oustream.close() listener.finished(self.data) def on_data_available(self, request, context, input_stream, offset, count): self.data += instream.read(count) data_listener = DataListener() Or if you want a more straightforward (but less pythonic) translation: class dataListener(object): data = '' @classmethod def onStartRequest(this, request, context): pass @classmethod def onStopRequest(this, request, context, status): instream.close() oustream.close() listener.finished(this.data) @classmethod def onDataAvailable(this, request, context, inputStream, offset, count): this.data += instream.read(count) -- http://mail.python.org/mailman/listinfo/python-list
Unpickling Exception-type objects
Hi everyone, I'm stumped over what is probably (hopefully?) a very simple problem. Suppose I have a class that multiply inherits from two classes, call them A and B. A inherits from a class that takes any number of arguments in __init__. B does not inherit from anything and requires one argument. For reasons I don't understand, if A inherits from Exception, unpickling fails due to a TypeError: __init__() takes exactly 2 arguments (1 given) If A in inherits from a class that also takes any number of arguments, the TypeError vanishes. To illustrate: # import pickle class Parent: def __init__(self, *optional): self.optional = optional for Base in (Parent, Exception): print "Base =", Base print class A(Base): pass class B: def __init__(self, required): self.required = required class Child(A, B): def __init__(self, *args): A.__init__(self) B.__init__(self, *args) def test_dump(obj): print 'obj:', type(obj), obj.__dict__ pickle.dump(obj, file('/tmp/pickle.p', 'w'), -1) try: loaded = pickle.load(file('/tmp/pickle.p')) print 'loaded', type(loaded), loaded.__dict__ except TypeError, e: print 'failed to load', e print test_dump(Child(7)) # I get the following output in python 2.5.2: # Base = __main__.Parent obj: {'required': 7, 'optional': ()} loaded {'required': 7, 'optional': ()} Base = obj: {'required': 7} failed to load __init__() takes exactly 2 arguments (1 given) # Any help on this would be greatly appreciated. Thanks, David -- http://mail.python.org/mailman/listinfo/python-list
Python 2.6, GUI not working on vista?
i just downloaded 2.6 and when running the gui nothing happens. anyone else with the same problem? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python equivalent of Perl e flag with regular expression
Friedman, Jason wrote: > I have lines that look like this: > select column1, 'select' as type > from table > where column2 = 'foo' > > I want to return: > SELECT column1, 'select' AS type > FROM table > WHERE column2 = 'foo' > > This is SQL with the keywords converted to uppercase. Note that the > second "select" string is not a keyword and thus I do not want to > convert it to uppercase. Thus, I don't think the string.replace() > method will work for me. > > With Perl I might do something like this: > $line =~ s/(select)/uc($1)/e; > More generally: > for $keyword in (@keyword) { > $line =~ s/($keyword)/uc($1)/e; > } I think your perl code is broken. It mechanically replaces the first occurence of the keyword. This fails e. g. for "select 'from' as x, b as y from table;" > How would I do this with Python? Here's my attempt, but you won't get 100% reliability without a real parser. import re sql = "select 'x' as t, 'y''' as u, selected, 'from' as fromage from temp;" def fix_sql(sql): def sub(m): kw = m.group(3) if kw: return kw.upper() return m.group(1) or m.group(2) return re.compile("""('.*?')|(".*?")|\\b(select|as|from)\\b""").sub(sub, sql) print fix_sql(sql) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6, GUI not working on vista?
On Oct 2, 2:27 pm, process <[EMAIL PROTECTED]> wrote: > i just downloaded 2.6 and when running the gui nothing happens. > > anyone else with the same problem? I have no idea what "gui" you're referring to. However, when I try to run Python on vista, I get: The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log for more detail. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python equivalent of Perl e flag with regular expression
On Oct 2, 1:06 pm, "Friedman, Jason" <[EMAIL PROTECTED]> wrote: > I have lines that look like this: > select column1, 'select' as type > from table > where column2 = 'foo' > > I want to return: > SELECT column1, 'select' AS type > FROM table > WHERE column2 = 'foo' > > This is SQL with the keywords converted to uppercase. Note that the > second "select" string is not a keyword and thus I do not want to > convert it to uppercase. Thus, I don't think the string.replace() > method will work for me. > > With Perl I might do something like this: > $line =~ s/(select)/uc($1)/e; > More generally: > for $keyword in (@keyword) { > $line =~ s/($keyword)/uc($1)/e; > > } Are you sure that this version returns the desired results ? How does perl know not to much the keyword within the quotes ? > How would I do this with Python? Leaving aside the fact that regexps are not the right tool to check whether a string is within quotes or not, you can use re.sub() and pass a callable instead of a replacement string: >>> import re >>> keywords = 'select from where as'.split() >>> regex = re.compile('|'.join(r'\b%s\b' % re.escape(k) for k in keywords), >>> re.I) >>> sql = """ select column1, 'select' as type from table where column2 = 'foo' """ >>> print regex.sub(lambda match: match.group().upper(), sql) SELECT column1, 'SELECT' AS type FROM table WHERE column2 = 'foo' George -- http://mail.python.org/mailman/listinfo/python-list
how to find the directory where python is installed ?
hello, how can I determine the location of the Python installation under winXP / Linux, with a Python program ? thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6 final
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On Oct 1, 2008, at 11:46 PM, Barry Warsaw wrote: On behalf of the Python development team and the Python community, I am happy to announce the release of Python 2.6 final. This is the production-ready version of the latest in the Python 2 series. Source tarballs, Windows installers, and Mac disk images can be downloaded from the Python 2.6 page: http://www.python.org/download/releases/2.6/ Due to a minor snafu in our build scripts, the source tgz and tar.bz2 files contained some extra cruft. I have created and uploaded new tarballs but I have /not/ bumped the Python version number since they were made from exactly the same Subversion tag. The new tarballs are identical to the originals except that they don't contain the cruft (.svn files and such). If you have already downloaded the tarballs, you do not need to download the new ones. The new tarballs are about 2MB smaller though. With apologies, - -Barry -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (Darwin) iQCUAwUBSOUgjnEjvBPtnXfVAQJ3gQP4mxxW9kaaMlsg7yd1uNcgYa29pitYdF2+ DhFgrCajPZpskc3XlKbPcnPJWT8wtI/EIC5QcPEpAWCHECrTUHzPyGLNeMQz0kFF /ZGCGbef7Mc/JaZvEyF6OATnKhYA5XyUOPdddygx6oar/Y6ZbK2JyLR4pvzh+gtQ SA+u6OPIpQ== =7uu8 -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: how to find the directory where python is installed ?
On Thu, Oct 2, 2008 at 12:16 PM, Stef Mientki <[EMAIL PROTECTED]> wrote: > hello, > > how can I determine the location of the Python installation under winXP / > Linux, > with a Python program ? > > thanks, > Stef Mientki > > -- > http://mail.python.org/mailman/listinfo/python-list > This what you're looking for? ([EMAIL PROTECTED]) python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.executable '/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python' >>> sys.path ['', '/Library/Python/2.5/site-packages/enum-0.4.3-py2.5.egg', '/Library/Python/2.5/site-packages/mechanize-0.1.8-py2.5.egg', '/Library/Python/2.5/site-packages/ClientForm-0.2.9-py2.5.egg', '/Users/tjg/code/libs', '/Users/tjg/code/py-dist', '/usr/local/lib/wxPython-unicode-2.8.8.0/lib/python2.5/site-packages', '/usr/local/lib/wxPython-unicode-2.8.8.0/lib/python2.5/site-packages/wx-2.8-mac-unicode', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload', '/Library/Python/2.5/site-packages', '/usr/local/lib/wxPython-unicode-2.8.8.0/lib/python2.5', '/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjC'] >>> -- Stand Fast, tjg. [Timothy Grant] -- http://mail.python.org/mailman/listinfo/python-list
Regular expressions and Unicode
I have a regular expression that I use to extract the surname: surname = r'(?u).+ (\w+)' However, when I apply it to this Unicode string, I get only the first 3 letters of the surname: name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' surname_re = re.compile(surname) m = surname_re.search(name) m.groups() ('Dvo\xc5',) I suppose that there is an encoding problem, but I don't understand Unicode well enough to know what to do to digest properly the Unicode characters in the surname. -- Jeffrey Barish -- http://mail.python.org/mailman/listinfo/python-list
Re: how to find the directory where python is installed ?
Timothy Grant wrote: On Thu, Oct 2, 2008 at 12:16 PM, Stef Mientki <[EMAIL PROTECTED]> wrote: hello, how can I determine the location of the Python installation under winXP / Linux, with a Python program ? thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list This what you're looking for? ([EMAIL PROTECTED]) python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. import sys sys.executable '/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python' Yes that might be sufficient. thanks, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: why? __builtins__ key added from eval
On Tue, 30 Sep 2008 16:04:34 -0500, William Purcell wrote: > I want to use eval to evaluate wx.TextCtrl inputs. How can I keep python > from adding the __builtins__ key to mydict when I use it with eval? > Other wise I have to __delitem__('__builtins__') everytime I use eval? > mydict = {'a':2,'b':3} eval('a*b',mydict) > 6 mydict > {'a': 2, '__builtins__': {'IndexError': , > ...(I'll spare you the rest)...}, 'b': 3} > > Also, how come eval has this behavior? Is it desirable? > > -Bill when you pass mydict, it is used as the global variables in the eval, right? Then, you passed a code to eval('...', mydict), sometimes you might create global variable inside eval, and you want to see the value of that inner global, that's why python modified mydict as a side-effect. Then what is __builtins__ doing there? Because when eval created an environment for the code to run, python interpreter need to define things that it used by itself. The __builtins__ contained all built-in names that is always available in python (python have to store it somewhere, the built-in names couldn't be bound by magic, right?). You could remove the builtin if you don't think it is necessary for you. Or you could do "dictionary comprehension" that collects only names you require (actually use generator comprehension then do a dict() conversion, dictionary comprehension was rejected some time ago) e.g.: newdict = dict(k, v for k, v in mydict.iteritems() if k in ['a', 'b']) or you could make a copy of mydict before passing it to eval. Last note: eval is evil. (no pun intended) -- http://mail.python.org/mailman/listinfo/python-list
questions from a lost sheep
Hi all, I used to by a big Python fan, many years ago [1]. I stopped using it after discovering REALbasic, because my main developmental need is to write desktop applications that are as native as possible on each platform, and because I really like a strongly-typed language with a good IDE. At the time (circa 2000), Python just didn't cut the mustard in this regard. (Indeed, none of the standard cross-platform C libraries -- Tk, QT, wxWidgets -- worked worth a darn on the Mac, at least at that time.) But REALbasic is a commercial, closed-source project with a small development team, and I find myself consistently frustrated by quality issues (read "bugs"). I've started to think fondly of the rock-solid stability of Python, and have been wondering if perhaps aggressive unit testing could mitigate most of the problems of weak typing. But that still leaves the other issue: creating high-quality desktop apps that look and feel just as good to users as anything written in the "standard" tools for each platform (Cocoa, .NET, etc.). REALbasic still does a great job of that (when it works at all). What's the state of the art in desktop app development in Python these days? Also, apart from simply searching with Google, is there anyplace I could go to find a good Python contractor to build a cross-platform desktop app demo? Many thanks, - Joe [1] http://www.strout.net/info/coding/python/ -- http://mail.python.org/mailman/listinfo/python-list
tkinter textwidget problem
Hi, In a tkinter TextWidget I would like to retrieve the last typed word. I've tried this with the 'wordstart' Expression [From the effbot site, "wordstart" and "wordend" moves the index to the beginning (end) of the current word. Words are sequences of letters, digits, and underline, or single non-space characters.], but it fails : #!/usr/bin/env python # -*- coding: utf-8 -*- from Tkinter import * root = Tk() text = Text(root, font=("Calibri")) text.pack() # Insert some text inside (13 chars long) text.insert(INSERT, "one two three") # idx_st : the position of the cursor # idx_ed : same but translated to the beginning of the last word ? idx_st = text.index( "insert" ) # returns 1.13 idx_ed = text.index( "insert wordstart" ) # returns 1.13 too : why ? print idx_st,idx_ed print "Text=",text.get(idx_st,idx_ed) mainloop() Any idea ? Thanks in advance : Kib². -- http://mail.python.org/mailman/listinfo/python-list
Re: questions from a lost sheep
On Thu, Oct 2, 2008 at 2:22 PM, Joe Strout <[EMAIL PROTECTED]> wrote: > Hi all, > > I used to by a big Python fan, many years ago [1]. I stopped using it after > discovering REALbasic, because my main developmental need is to write > desktop applications that are as native as possible on each platform, and > because I really like a strongly-typed language with a good IDE. At the > time (circa 2000), Python just didn't cut the mustard in this regard. > (Indeed, none of the standard cross-platform C libraries -- Tk, QT, > wxWidgets -- worked worth a darn on the Mac, at least at that time.) > > But REALbasic is a commercial, closed-source project with a small > development team, and I find myself consistently frustrated by quality > issues (read "bugs"). I've started to think fondly of the rock-solid > stability of Python, and have been wondering if perhaps aggressive unit > testing could mitigate most of the problems of weak typing. > > But that still leaves the other issue: creating high-quality desktop apps > that look and feel just as good to users as anything written in the > "standard" tools for each platform (Cocoa, .NET, etc.). REALbasic still > does a great job of that (when it works at all). What's the state of the > art in desktop app development in Python these days? > > Also, apart from simply searching with Google, is there anyplace I could go > to find a good Python contractor to build a cross-platform desktop app demo? > > Many thanks, > - Joe wxPython and Qts Mac support are leaps and bounds ahead of what they were in 2000, I would strongly suggest giving them another look. I know several that people in the wx community do contract work (or even just in bounties, if there are toolkit issues you'd like solved), take a look at wxwidgets.org for that. There's also the Python job board at python.org. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python equivalent of Perl e flag with regular expression
Jason> With Perl I might do something like this: Jason> $line =~ s/(select)/uc($1)/e; ... Jason> How would I do this with Python? I'm sure there are plenty of ways to skin this particular cat, but how is 's/.../.../e' different from 's/.../.../'? (For those of us who are not Perl mongers.) Skip -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Entry blocked by tkFileDialog
Hello I have the following problem in Python 2.5 on Windows XP. On Ubuntu I do not see the problem. I have a Tkinter application as in the following example The entry-widget is somehow blocked (i cannot type characters into it) when I call askopenfilename before I create the widget. Calling askopenfile again (by clicking the button) releases the block, I can type into the entry as expected. Could someone please try out the example and tell if you observe the blocked entry, too? Do you know a workaround? I want to call askopenfilename before creating the widgets, since i use it to choose a config file which controls the number and type of widgets I create. Regards Leonhard import Tkinter import tkFileDialog tk = Tkinter.Tk() tkFileDialog.askopenfilename() Tkinter.Entry(tk).grid() Tkinter.Button(tk, text='ask', command=tkFileDialog.askopenfilename).grid() tk.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expressions and Unicode
Jeffrey> However, when I apply it to this Unicode string, I get only the Jeffrey> first 3 letters of the surname: Jeffrey> name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' Maybe name = unicode('Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k', "utf-8") ? Yup, that works: >>> name = unicode('Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k', "utf-8") >>> name u'Anton\xedn Dvo\u0159\xe1k' >>> surname = r'(?u).+ (\w+)' >>> import re >>> surname_re = re.compile(surname) >>> m = surname_re.search(name) >>> m.groups() (u'Dvo\u0159\xe1k',) -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expressions and Unicode
Jeffrey Barish wrote: > I have a regular expression that I use to extract the surname: > > surname = r'(?u).+ (\w+)' > > However, when I apply it to this Unicode string, I get only the first 3 > letters of the surname: > > name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' That's a byte string. You can either modify the literal name = u'Anton\xedn Dvo\u0159\xe1k' or decode it with the proper encoding name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' name = name.decode("utf-8") > surname_re = re.compile(surname) > m = surname_re.search(name) > m.groups() > ('Dvo\xc5',) > > I suppose that there is an encoding problem, but I don't understand > Unicode well enough to know what to do to digest properly the Unicode > characters in the surname. >>> name = 'Anton\xc3\xadn Dvo\xc5\x99\xc3\xa1k' >>> re.compile(r"(?u).+ (\w+)").search(name.decode("utf-8")).groups() (u'Dvo\u0159\xe1k',) >>> print _[0] Dvořák Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: questions from a lost sheep
Joe> I've started to think fondly of the rock-solid stability of Python, Joe> and have been wondering if perhaps aggressive unit testing could Joe> mitigate most of the problems of weak typing. Note: Python is not weakly typed. It is dynamically typed. But, yes, there is no substitute for unit tests in a language like Python. Joe> But that still leaves the other issue: creating high-quality Joe> desktop apps that look and feel just as good to users as anything Joe> written in the "standard" tools for each platform (Cocoa, .NET, Joe> etc.). REALbasic still does a great job of that (when it works at Joe> all). What's the state of the art in desktop app development in Joe> Python these days? Dabo was just mentioned here earlier today: http://www.dabodev.com/ I have no experience with it, but it might be worth a look. From the front page: Dabo's authors, Ed Leafe and Paul McNett, have strong backgrounds in database application development using the awesome and underrated Microsoft Visual FoxPro development environment. While Visual FoxPro shines at developing data-centric applications, it has one limitation that cannot be ignored: it only runs on Microsoft Windows, and Ed and Paul both have clients that want their applications to run on Linux and Macintosh. We are sure we are not alone in this regard: it is a multi-platform world with more diverse needs than one vendor can fulfill. Skip -- http://mail.python.org/mailman/listinfo/python-list
Inheritance but only partly?
Let's say I have a class X which has 10 methods. I want class Y to inherit 5 of them. Can I do that? Can I do something along the lines of super(Y, exclude method 3 4 7 9 10) ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance but only partly?
process wrote: > Let's say I have a class X which has 10 methods. > > I want class Y to inherit 5 of them. > > Can I do that? Can I do something along the lines of super(Y, exclude > method 3 4 7 9 10) ? > > -- > http://mail.python.org/mailman/listinfo/python-list > No. But why do yo care? You can just ignore the 5 you don't want -- their existence costs you nothing in either memory or execution speed. You can also redefine the ones you don't want inherited: class A: def DontInheritMe(self, ...): ... Class B(A): def DontInheritMe(self, ...): raise NotImplementedError // Or some such Gary Herron -- http://mail.python.org/mailman/listinfo/python-list