ANN: Veusz 1.1
Veusz 1.1 - Velvet Ember Under Sky Zenith - http://home.gna.org/veusz/ Veusz is Copyright (C) 2003-2008 Jeremy Sanders [EMAIL PROTECTED] Licenced under the GPL (version 2 or greater). Veusz is a scientific plotting package written in Python, using PyQt4 for display and user-interfaces, and numpy for handling the numeric data. Veusz is designed to produce publication-ready Postscript/PDF output. The user interface aims to be simple, consistent and powerful. Veusz provides a GUI, command line, embedding and scripting interface (based on Python) to its plotting facilities. It also allows for manipulation and editing of datasets. Feature changes from 1.0: * Axes autoscale when plotting functions * Labels can be dragged around on plots * More marker symbols * SVG export of plots * The point plotting and axis range code has been rewritten. * Includes quite a few minor bugfixes Features of package: * X-Y plots (with errorbars) * Line and function plots * Contour plots * Images (with colour mappings and colorbars) * Stepped plots (for histograms) * Fitting functions to data * Stacked plots and arrays of plots * Plot keys * Plot labels * LaTeX-like formatting for text * EPS/PDF/PNG export * Scripting interface * Dataset creation/manipulation * Embed Veusz within other programs * Text, CSV and FITS importing Requirements: Python (2.3 or greater required) http://www.python.org/ Qt = 4.3 (free edition) http://www.trolltech.com/products/qt/ PyQt = 4.3 (SIP is required to be installed first) http://www.riverbankcomputing.co.uk/pyqt/ http://www.riverbankcomputing.co.uk/sip/ numpy = 1.0 http://numpy.scipy.org/ Microsoft Core Fonts (recommended for nice output) http://corefonts.sourceforge.net/ PyFITS = 1.1 (optional for FITS import) http://www.stsci.edu/resources/software_hardware/pyfits For documentation on using Veusz, see the Documents directory. The manual is in pdf, html and text format (generated from docbook). Issues: * Can be very slow to plot large datasets if antialiasing is enabled. Right click on graph and disable antialias to speed up output. * The embedding interface appears to crash on exiting. If you enjoy using Veusz, I would love to hear from you. Please join the mailing lists at https://gna.org/mail/?group=veusz to discuss new features or if you'd like to contribute code. The latest code can always be found in the SVN repository. Jeremy Sanders -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[ANN] PyYAML-3.06: YAML parser and emitter for Python
Announcing PyYAML-3.06 A new bug fix release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Changes === * setup.py checks whether LibYAML is installed and if so, builds and installs LibYAML bindings. To force or disable installation of LibYAML bindings, use '--with-libyaml' or '--without-libyaml' options respectively. * Building LibYAML bindings no longer requires Pyrex installed. * 'yaml.load()' raises an exception if the input stream contains more than one YAML document. * Fixed exceptions produced by LibYAML bindings. * Fixed a dot '.' character being recognized as !!float. * Fixed Python 2.3 compatibility issue in constructing !!timestamp values. * Windows binary packages are built against the LibYAML stable branch. * Added attributes 'yaml.__version__' and 'yaml.__with_libyaml__'. Resources = PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.06.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.06.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.06.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.06.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.06.win32-py2.5.exe http://pyyaml.org/download/pyyaml/PyYAML-3.06.win32-py2.6.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example === import yaml yaml.load( ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... ) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright = The PyYAML module is written by Kirill Simonov [EMAIL PROTECTED]. PyYAML is released under the MIT license. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Python is slow?
Steven D'Aprano wrote: We agree that the restriction is artificial, and I think irrational I think it's irrational for another reason, too -- it's actually vacuous. There's nothing to prevent you creating a set of patches that simply say Delete all of the original source and replace it with the following. Then you're effectively distributing the modified source in its entirety, just with a funny header at the top of each source file that serves no useful purpose. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: questions from a lost sheep
On Oct 2, 11:08 pm, johannes raggam [EMAIL PROTECTED] wrote: statically typed language: A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages. dynamically typed language: A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value. strongly typed language: A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it. weakly typed language: A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion. I have always considered this argument rather weak. It is true, we Pythonista we are in a better position that Perl and VBScript users, but still how strong is strong typing really? When I can never know the types accepted by a function at compile time? When I can change the class of an object at runtime? Dynamic typing has its advantages, but calling it strong is ridicolous for people coming from a background in ML or Haskell. The definitions change according to the circles you frequent, so there will be always confusions on the terminology, unfortunately. -- http://mail.python.org/mailman/listinfo/python-list
Re: python-2.6
Strange things happens. I've download the installer package for Mac of Python 2.6 and I've launched it. When finished, I've launched from a terminal the command Python and all worked fine The response was Python 2.6 etc Now I've launched IDLE. Nothing. IDLE icon blinked a couple of time in dock and then disapeared. I've disabled any firewall in the system but the behavior was the same. I've repared the privilege and restarted the system. A disaster. The system was dramatically slow and IDLE was still not starting. Then I've reinstalled Python 2.5.2 an all was working fine again (included IDLE and System speed). What is wrong with Python 2.6 on my system (MacOS X 10.4.11 PPC)? - Original Message Da: Terry Reedy [EMAIL PROTECTED] To: python-list@python.org python-list@python.org Oggetto: Re: python-2.6 Data: 03/10/08 03:41 [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? Keep your 2.5.2 install intact until you have everything you need and want in a 2.6 install. -- http://mail.python.org/mailman/listinfo/python-list -- Email.it, the professional e-mail, gratis per te: http://www.email.it/f Sponsor: CheBanca! La prima banca che ti dà gli interessi in anticipo. Fino al 4,70% sul Conto Deposito, zero spese e interessi subito. Aprilo! Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid=7919d=20081003 -- http://mail.python.org/mailman/listinfo/python-list
Conditionally subclassing based on Import
Hi, just want to conditionally base a class on another if it can be imported, otherwise base it on object. Does the following look ok for this? try: import foo.bar except ImportError: MyBase = foo.bar.Baz else: MyBase = object class Something(MyBase): -- http://mail.python.org/mailman/listinfo/python-list
RE module question
Hello folks : i have a string -bin-ulockmgr_server:0.99[NHX:C=0.195.0] from which i want to delete [NHX:C=0.195.0] . I wrote a regular expression for [NHX:C=0.195.0] as \[(\w)+:\w=((-)?(\d|\d\d|\d\d\d)\.)+\d\] now when i do p = re.compile('\[(\w)+:\w=((-)?(\d|\d\d|\d\d\d)\.)+\d\]') m =p.search(-bin-ulockmgr_server:0.99[NHX:C=0.195.0]) print m _sre.SRE_Match object at 0x01314EE8 print m.group() [NHX:C=0.195.0] So i guess i am able to find the substring , my question is how can i delete this substring from the original string? ie -bin-ulockmgr_server:0.99 should be my output. thanks Aditya -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
Mark Dickinson wrote: Option (2) appeals to me, but I can't see how to implement it. It could be implemented for the special case of floats and Decimals by keeping flags in each set indicating whether any elements of those types have been added. But doing this just for those two types would be rather hackish, and wouldn't do anything for any other incomparable types that might come along. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditionally subclassing based on Import
David Pratt wrote: Hi, just want to conditionally base a class on another if it can be imported, otherwise base it on object. Does the following look ok for this? try: import foo.bar except ImportError: MyBase = foo.bar.Baz else: MyBase = object class Something(MyBase): -- http://mail.python.org/mailman/listinfo/python-list Ahhh... I believe you've got that backwards. try: import foo.bar MyBase = foo.bar.Baz except ImportError: MyBase = object or try: import foo.bar except ImportError: MyBase = object else: MyBase = foo.bar.Baz Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
Terry Reedy wrote: Documenting the problem properly would mean changing the set documentation ... from their current math set based definitions to implementation based definitions It could be documented that the mathematical definitions hold only if the equality relations between all the elements involved are transitive, and leave the semantics in other cases undefined. Then in the Decimal module it could be warned that the equality relations between int-float and int-Decimal are not transitive, perhaps noting that this can cause problems with sets and dicts. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
Gabriel Genellina wrote: Had Python used the more generic size and __size__ from the beginning, we'd be all happy now :) Not necessarily -- len is slightly shorter, and more comfortable to type on a qwerty keyboard. But in any case, size-likers have an easy solution: size = len :-) (BTW, try doing that with the x.len() notation!) -- Greg But it's too late to change things. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
Aaron Castironpi Brady wrote: How do you have a yellow dog, It's not a yellow dog, it's a dog yellow. Attention pay! :-) -- Ewing Gregory -- http://mail.python.org/mailman/listinfo/python-list
Re: del and sets proposal
On Oct 2, 6:20 pm, Larry Bates [EMAIL PROTECTED] wrote: You can do the following: a = [1,2,3,4,5] del a[0] and a = {1:'1', 2: '2', 3: '3', 4:'4', 5:'5'} del a[1] why doesn't it work the same for sets (particularly since sets are based on a dictionary)? a = set([1,2,3,4,5]) del a[1] Yes I know that sets have a remove method (like lists), but since dictionaries don't have a remove method, shouldn't sets behave like more like dictionaries and less like lists? IMHO del for sets is quite intuitive. I guess it is too late to change now. Funny, I would welcome a change in the opposite direction: drop completely the del a[i] syntax from the language and use an explicit (non-special) method name, e.g. a.delete(i) or a.remove(i). Having some functionality exposed through methods and some through function builtins (e.g. len()) is more than enough; having a third way through the del statement is unnecessarily perl-ish. George -- http://mail.python.org/mailman/listinfo/python-list
Re: Ctypes behave differenty on windows 2000 and windows XP
En Thu, 02 Oct 2008 10:17:01 -0300, [EMAIL PROTECTED] escribió: 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 For myDll_GetVersion you should define its arguments and return type using .argtypes and .restype - else ctypes assumes int -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Event-driven framework (other than Twisted)?
On 10/2/08, Phillip B Oldham [EMAIL PROTECTED] wrote: 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. Sorry my VPS has been down for quite some time today :/ Not happy! Here is the sample: code #!/usr/bin/env python # -*- coding: utf-8 -*- # vim: set sw=3 sts=3 ts=3 import optparse from pymills import event from pymills.event import manager from pymills.net.sockets import TCPServer from pymills.event.core import listener, Component from pymills.net.http import HTTP, Response, Dispatcher from pymills import __version__ as systemVersion USAGE = %prog [options] [path] VERSION = %prog v + systemVersion ### ### Functions ### def parse_options(): parse_options() - opts, args Parse any command-line options given returning both the parsed options and arguments. parser = optparse.OptionParser(usage=USAGE, version=VERSION) parser.add_option(-b, --bind, action=store, default=0.0.0.0:8000, dest=bind, help=Bind to address:port) opts, args = parser.parse_args() return opts, args ### ### Components ### class Test(Component): channel = / @listener(index) def onINDEX(self, request, response): self.send(Response(response), response) @listener(hello) def onHello(self, request, response): if request.cookie.get(seen, False): response.body = Seen you before! else: response.body = Hello World! response.cookie[seen] = True self.send(Response(response), response) @listener(test) def onTEST(self, request, response): response.body = OK self.send(Response(response), response) class WebServer(TCPServer, HTTP): pass ### ### Main ### def main(): opts, args = parse_options() if : in opts.bind: address, port = opts.bind.split(:) port = int(port) else: address, port = opts.bind, 80 server = WebServer(port, address) dispatcher = Dispatcher() event.manager += server event.manager += Test() event.manager += dispatcher while True: try: manager.flush() server.poll() except KeyboardInterrupt: break ### ### Entry Point ### if __name__ == __main__: main() /code -- -- -- Problems are solved by method -- http://mail.python.org/mailman/listinfo/python-list
Re: One class per file?
Bruno Desthuilliers wrote: OTHO, 'one class per file' is a standard idiom in Java and IIRC in C++ (which both have namespaces one way or another) In Java you don't get a choice, because the compiler assumes a class can be found in the correspondingly named file. While C++ has namespaces, they don't have any defined relationship to source files, so they don't help you find which file something is defined in. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: 2.6 multiprocessing and pdb
En Thu, 02 Oct 2008 18:14:07 -0300, Aaron Castironpi Brady [EMAIL PROTECTED] escribió: I'm trying to step through a subprocess I launch with multiprocessing. Does anyone know what hack to add? The actual call comes in forking.Popen.__init__, Windows version, forking.py, line 222: hp, ht, pid, tid = _subprocess.CreateProcess( _python_exe, cmd, None, None, 1, 0, None, None, None ) to step through a subprocess means that you are using a debugger (pdb?) to execute the parent process, and want to debug the child process too? You'll have to modify the command line (the cmd argument), so the child is run thru the debugger too. I don't think pdb has any remote capabilities. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: code critique requested - just 60 lines
On Oct 2, 11:56 am, [EMAIL PROTECTED] wrote: Terrence Brannon, I suggest you to shorten a lot some of those very long lines. yes, I wanted to, but was not sure how to continue a line on the next line in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd Errors
Steven D'Aprano wrote: 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. Actually, the term has that meaning for all programming languages. The main distinguishing feature of functional languages is that there are *no* side effects. The confusing thing is that in everyday English the term implies something bad or unwanted (e.g. side effects of a drug). That's not necessarily true of the technical meaning -- often the side effect is exactly what we want, as in the case of append. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Professional quality scripts/code
robean a écrit : I have been learning Python for the last 3 months or so and I have a working (but somewhat patchy) sense of the the language. I've been using a couple of the more popular Python books as well as online resources. A question for experienced Python programmers: can you recommend resources where I can look at high quality Python code and scripts? Well... Not everything is 'high quality' in it[1], but why not start with the stdlib ? Most of it is pure Python, opensource code and is already installed on your machine, isn't it ?-) [1] IIRC, last time I had a look at the zipfile module's code, it was more of a QD hack than anything else - now as long as it works fine for what I do with it and I don't have to maintain it, well, that's fine. I've spent some time at http://code.activestate.com/recipes/ but am concerned that the quality of what is posted there can be somewhat hit and miss. Indeed. What I have in mind is a site like cpan, where one can look at the actual source code of many of the modules and learn a thing or two about idiomatic Perl programming from studying the better ones. Any sites like that for Python? Lurking here is probably a good way to see a lot of code reviews. And even possibly to submit snippets of your own code to review. Some (if not most) of us here like to show how good we are at improving the poor newbies code !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter textwidget problem
On Thu, 02 Oct 2008 21:57:01 +0200, kib2 [EMAIL PROTECTED] wrote: 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 ? Tk/Tkinter apparently considers the position 1.13 to be after the last word in the text. You get the same problem if you set the insertion point just after the word 'two' for example: text.index('insert') returns 1.7 and text.index('insert wordstart') returns 1.7 too... My solution would simply be to go back one character before asking the word start: text.index('insert - 1 chars wordstart') Don't know if that'll do what you want if there are spaces at the end of the text. And BTW, if you actually want the *last* word in the text, you may want to use text.index('end - 2 chars wordstart'). Here, you have to use '- 2 chars' because end points to the first non-existent index (2.0 in your case...). HTH -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Re: del and sets proposal
On Thu, 02 Oct 2008 22:27:04 -0500, Larry Bates wrote: Maybe dictionaries should have had a .remove method then things would be more consistent? But why should sets be consistent with dictionaries? There are a few similarities, but also differences. Personally, I'd rather see dictionaries grow methods like symmetric_difference, union, etc. than worry about whether you use del or remove to remove elements from a set. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: code critique requested - just 60 lines
En Fri, 03 Oct 2008 05:07:41 -0300, Terrence Brannon [EMAIL PROTECTED] escribió: On Oct 2, 11:56 am, [EMAIL PROTECTED] wrote: Terrence Brannon, I suggest you to shorten a lot some of those very long lines. yes, I wanted to, but was not sure how to continue a line on the next line in Python. Having ANY open () or [] or {} is enough to implicitely continue a line (being it a function call, a list definition, a generator expression, whatever...) tags = { 'S': 'Small', 'M': 'Medium', 'L': 'Large', 'XL': 'Extra large', } Also, you may use \ as the LAST character (immediately preceding the newline) to continue the logical line on the next physical line: result = coef[0] * sum_deliverd + \ coef[1] * max_income + \ coef[2] * min_delay -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: closures and dynamic binding
jhermann wrote: I didn't see this mentioned in the thread yet: the double-lambda is unnecessary (and a hack). Well, the alternative -- abusing default argument values -- is seen by many to be a hack as well, possibly a worse one. It doesn't work in general, e.g. it fails if the function needs to be called with a variable number of arguments. The double lambda is conceptually more sound in some ways, and can be made to work correctly in all cases. The root of the problem actually has nothing to do with lambdas or static vs. non-static scoping. It's the fact that Python's for-loop doesn't create a new environment for the loop variable each time around, but re-uses a slot in the containing environment. Contrast this with Scheme, where the equivalent of a for-loop *does* create a new environment for each value of the loop variable. Effectively it's using a double lambda, except that one of the lambdas is folded into the syntax of the loop, so you don't notice it. So if anything were to be done to the language to fix this, it really should be focused on fixing the semantics of the for-loop. Unfortunately, the fact that the loop variable leaks out of the scope of the loop is regarded as a feature, so anything which changes that seems to be a non-starter. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: javascript to python
On Oct 2, 7:42 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: lkcl a écrit : 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 Since you don't rebind them, you don't need the global statement for these three identifiers instream.close() outstream.close() listener.finished(self.data) def onDataAvailable(self, request, context, inputStream, offset, count): global instream idem self.data += instream.read(count) And then you have a class. Calling instance methods on the class won't work. Looks like there's something missing... 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 :) None of this, and more is because of javascript. You'll find bad code in every language (and without more context, you can't tell if it's bad code - might as well be the right thing to do). FWIW, javascript is a very interesting and powerful language. for fits and giggles, compile the above python using pyjs.py, the python-to-javascript compiler (seehttp://pyjamas.sf.net) and compare the resultant javascript to your original code-fragment. l. I did. Here's the result: ok - these are the important bits. notice that the pyjamas compiler is doing a little bit more than your original code: it's overriding the prototype of dataListener, making it a true class object. this is where there's a key departure from the original code and the translation to python: the original code isn't actually a class, at all - it's more like a c struct that has function pointers in it. by declaring a python class, the javascript equivalent is to add to prototypes. __dataListener.prototype.__init__ = function() { var data = ''; }; [ ... so for example here, now when you declare _any number_ of dataListeners, each and every one will have its __init__ function called. in your original example, you're effectively making one and only one dataListener. you're kinda... it's a bit like having a lambda-class (nameless class) and declaring one and only one instance of that python class... ] __dataListener.prototype.onStopRequest = function(request, context, status) { instream.close(); outstream.close(); listener.finished(this.data); }; __dataListener.prototype.onDataAvailable = function(request, context, inputStream, offset, count) { this.data += instream.read(count); }; so - yeah, you can see that (apart from the .prototype, which is necessary to make a class a la javascript) it's a pretty accurate translation back to the original javascript. All this, and more, thanks to the strange idea that it would be better to write javascript in Python instead of writing it in javascript !-) *lol* :) fortunately, pyjs.py does that translation for you ha ha. like they say on brainiac, STOP! we do these experiments, so you don't have to. yes - it's because in the translated python, dataListener was declared as a class, whereas in the original javascript, the corresponding concept (prototypes) are not made use of. if you wanted to experiment, you could try this: def onStartRequest(this, request, context): pass def onStopRequest(this, request, context, status): instream.close() oustream.close() listener.finished(this.data) def onDataAvailable(this, request, context, inputStream, offset, count): this.data += instream.read(count) class dataListener: def __init__(self): self.data = '' self.onStartRequest = onStartRequest self.onStopRequest = onStopRequest self.onDataAvailable = onDataAvailable which you will find to be more accurately representative of the original javascript, conceptually. i.e taking into account that in the _original_ javascript, you don't have any prototypes. but - i don't believe it to be what you actually want, even though it's a slightly more accurate representation. l. -- http://mail.python.org/mailman/listinfo/python-list
Re: RE module question
En Fri, 03 Oct 2008 03:59:18 -0300, aditya shukla [EMAIL PROTECTED] escribió: Hello folks : i have a string -bin-ulockmgr_server:0.99[NHX:C=0.195.0] from which i want to delete [NHX:C=0.195.0] . I wrote a regular expression for [NHX:C=0.195.0] as \[(\w)+:\w=((-)?(\d|\d\d|\d\d\d)\.)+\d\] now when i do p = re.compile('\[(\w)+:\w=((-)?(\d|\d\d|\d\d\d)\.)+\d\]') m =p.search(-bin-ulockmgr_server:0.99[NHX:C=0.195.0]) print m _sre.SRE_Match object at 0x01314EE8 print m.group() [NHX:C=0.195.0] So i guess i am able to find the substring , my question is how can i delete this substring from the original string? ie -bin-ulockmgr_server:0.99 should be my output. Instead of p.search, use p.sub Or, if you need the match for other purposes, delete the characters from m.start() to m.end() See http://docs.python.org/library/re.html#regular-expression-objects -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
On Fri, 03 Oct 2008 19:10:27 +1200, greg wrote: But in any case, size-likers have an easy solution: size = len :-) (BTW, try doing that with the x.len() notation!) def size(obj): return obj.len() or size = operator.methodcaller('len') in Python 2.6 and up. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: del and sets proposal
On Oct 2, 8:02 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Thu, 02 Oct 2008 15:39:55 -0700, Chris Rebert wrote: On Thu, Oct 2, 2008 at 3:20 PM, Larry Bates [EMAIL PROTECTED] wrote: a = set([1,2,3,4,5]) del a[1] Sets don't support subscripting, so if you can't go 'a_set[something]', why would you expect to be able to be able to 'del' such an expression? What would the subscription even mean without the 'del'? It doesn't make sense and would just be inconsistent. Then add subscription access too. By aliasing `__getitem__()` to `__contains__()`. And `__setitem__()` could be implemented to add or remove objects by assigning truth values. So hypothetically: a = set([1, 2, 3]) a[1] True a[4] False a[2] = False a set([1, 3]) a[4] = True a set([1, 3, 4]) del a[1] a set([3, 4]) I wouldn't want that addition to `set`\s but at least it can be implemented without introducing inconsistencies. If set behaved that way then del a[1] wouldn't behave like del anymore. Normally, del whatever means that you can no longer use whatever; in this proposal you can. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
I'm not sure if our views are moving closer together or further apart, but here goes... On Thu, 02 Oct 2008 23:49:16 +, Marc 'BlackJack' Rintsch wrote: On Thu, 02 Oct 2008 14:51:29 +, Steven D'Aprano wrote: On Wed, 01 Oct 2008 10:38:12 +, Marc 'BlackJack' Rintsch wrote: 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. It's not cargo cult programming if you tell people to use the ``with`` statement to make sure the file will be closed after the block is left, for whatever reason the block was left. You are right. If you explain what with blocks do, it isn't cargo cult programming. 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. My intention wasn't to teach the OP how to write Python but to give a concise, easy and straight forward solution in Python. Yes, I really believe I have written such thing. I'm well aware that a Fortran programmer will not understand this without learning Python. I'm curious what the point of answering the OP's question was if you knew he wouldn't understand the answer. You might have saved us both a lot of time if you started your post with You aren't expected to understand this. 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. If he doesn't know enough basic Python techniques to solve *a simple problem* I think this is the wrong forum and he should work through the tutorial from the documentation to learn the basics first. The tutorial includes `map()`, list comprehensions, methods in strings, the fact that files are iterable, and generator expressions. Then you should have said so. [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. Of course it means they are the same things, that is what duck typing is about. No, you still don't understand me. Let me give you a more extreme example to help clarify: average_age = 64.7 width_of_page = 20.2 speed_of_car = 35.2 concentration_of_acid = 1.03 children_per_family = 2.3 All of the above have not just the same duck-type, but the same actual type (floats), and yet they are COMPLETELY different things. Imagine a piece of code like this: def foo(): x = 64.7 # x is the average age of a person ... more lines of code here x = 2.3 # x is now the average number of children per family ... return something Would you defend the above code on the basis that x had the same duck- type in both places? I hope not. A decade or so ago, one of the Mars spaceships crashed because a coder used a variable that was a float in inches when they were supposed to use a variable that was a float in millimetres (or vice versa, I forget). Because of this mistake, the retro-rockets fired too late, and the spaceship flew into the surface of Mars at some thousands of miles an hour. And yet both variables were not just the same duck-type, but the same actual type. You cannot conclude that two things are the same kind of thing just because they have the same type. The difference
Re: closures and dynamic binding
On Oct 3, 10:44 am, greg [EMAIL PROTECTED] wrote: So if anything were to be done to the language to fix this, it really should be focused on fixing the semantics of the for-loop. Unfortunately, the fact that the loop variable leaks out of the scope of the loop is regarded as a feature, so anything which changes that seems to be a non-starter. And Guido stated many times in the past that he is happy with the for loop as it is, so I don't think this will never change, even if the question keep getting asked here and there. Notice that even generator expressions, where the loop variable does not leak outside the loop, have the same behavior. The behavior of the list comprehension is a good test of how much functional a language is; Common Lisp and Python behaves in the same way (there is a single loop variable which is mutated at each iteration) wherea Scheme and Haskell introduce a new binding at each iteration. -- http://mail.python.org/mailman/listinfo/python-list
Re: code critique requested - just 60 lines
On Oct 2, 11:09 am, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Thu, 02 Oct 2008 07:51:30 -0700, Terrence Brannon wrote: Basically, using non-strict dictionary keys can lead to bugs, so that worried me. What's a non-strict dictionary key? In Perl, you can pre-define what keys are allowed in a dictionary. That way, mis-spelling the dict key doesnt lead to accessing something didnt mean to. -- http://mail.python.org/mailman/listinfo/python-list
Re: del and sets proposal
On Fri, 03 Oct 2008 02:18:53 -0700, Carl Banks wrote: On Oct 2, 11:27 pm, Larry Bates [EMAIL PROTECTED] wrote: I didn't mean to imply that del a[1] would delete the first thing in the set, but rather the item with a value of 1. Just as when we use it on a dictionary: del a[1] doesn't mean delete the first dictionary entry but rather delete the entry in the object with a value of 1, which IMHO would be perfectly logical for a set (which is why I started this discussion). It's not logical at all. In all current uses of del, the thing that follows del is a valid expression. With sets, that's not the case. I think Larry is suggesting that elements of sets should be removed in the same way that keys of dictionaries are removed: d = {57: foo} s = set([57]) He's suggesting that del s[57] should work just like del d[57] works. The fact that sets don't have a __getitem__ method doesn't mean that they couldn't have a __delitem__ method: class DelSet(set): def __delitem__(self, element): self.remove(element) s = DelSet([1, 2, 3, 4, 5]) s DelSet([1, 2, 3, 4, 5]) del s[4] del s[5] s DelSet([1, 2, 3]) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
Boris Borcic a écrit : 42, for instance. Proof : 42 is not object True QED Lol. -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance but only partly?
[EMAIL PROTECTED] wrote: class Mask(object): def m3(self): raise NotImplementedError def m4(self): raise NotImplementedError What's the name of this python design pattern? :-) Don't know. Perhaps we could call it the FigLeaf pattern (covering up what you don't want seen)? There's another possibility that's even more pythonish (I won't say pythonic, since it's not necessarily a *recommended* thing to do): class A: m1 = B.__dict__['m1'] m2 = B.__dict__['m2'] ... I propose calling this the Magpie pattern (stealing the shiny baubles you want and hiding them away in your own nest). -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: closures and dynamic binding
greg [EMAIL PROTECTED] writes: The root of the problem actually has nothing to do with lambdas or static vs. non-static scoping. It's the fact that Python's for-loop doesn't create a new environment for the loop variable each time around, but re-uses a slot in the containing environment. Contrast this with Scheme, where the equivalent of a for-loop *does* create a new environment for each value of the loop variable. Note that Python's semantics of for regarding closures are not unique to Python. Common Lisp behaves similar to Python in this regard: * (loop for i from 0 to 2 collect (lambda () i)) (#CLOSURE... {A86F3CD} #CLOSURE... {A86F3E5} #CLOSURE... {A86F3FD}) * (mapcar #'funcall *) (3 3 3) Other looping constructs, such as do, behave in equivalent fashion. So if anything were to be done to the language to fix this, it really should be focused on fixing the semantics of the for-loop. Unfortunately, the fact that the loop variable leaks out of the scope of the loop is regarded as a feature, so anything which changes that seems to be a non-starter. I don't think it has anything to do with variable leaking out of the loop. Common Lisp doesn't leak the loop variable, and it behaves the same. It is more a result of the different views of what iteration is. Common Lisp and Python define iteration in terms of repeating the same instructions over and over, not different from what C does, in which case it makes sense to reuse the same environment for all loop passes. (Python's language ref defines that a standard assignment is done for each new iteration.) In contrast, Scheme regards iteration as a special case of recursion, and R5RS do prescribes assigning loop variables to fresh locations to match what recursion normally does. In most cases both definitions exhibit the same behavior, but unfortunately not when closures are created inside the loop. -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance but only partly?
greg wrote: class Mask(object): def m3(self): raise NotImplementedError def m4(self): raise NotImplementedError What's the name of this python design pattern? :-) Don't know. Perhaps we could call it the FigLeaf pattern (covering up what you don't want seen)? Braghettone ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python arrays and sting formatting options
On Thu, 02 Oct 2008 18:15:59 -0700, bearophileHUGS wrote: What's a range(n)? A function that returns a list of n items, from 0 to n. This is easy to understand, while xrange(n) is a bit less easy to understand (a generator or generators). nitpick `xrange()` doesn't return a generator or iterator but an object that implements the sequence protocol: In [159]: a = xrange(0, 10, 2) In [160]: len(a) Out[160]: 5 In [161]: a[0] Out[161]: 0 In [162]: a[2] Out[162]: 4 /nitpick Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
On Fri, 03 Oct 2008 17:09:07 +1200, greg wrote: Lawrence D'Oliveiro wrote: In message [EMAIL PROTECTED], Steven D'Aprano wrote: (2) Even when the source is available, it is sometimes a legal trap to read it with respect to patents and copyright. That's not how patents work. I don't think that's how copyrights work either. As far as I know, whether something is deemed a derivative work is judged on the basis of how similar it is to another work, not whether its author had knowledge of the other work. As long as you express an idea in an original way, it shouldn't matter where you got the idea from. That is absolutely not the case with patents. It is *supposed* to be the case with copyrights, but in practice the courts are interpreting derivative work more and more broadly these days. As for Microsoft Shared Source licences, there are two which are approved by the FSF, but the others are a whole different story. You will note that both the GNU project and the Mono project warn against reading proprietary source code before contributing. Mono even goes so far as to say that if you have read the source code to .NET, they cannot accept your contributions: If you have looked at Microsoft's implementation of .NET or their shared source code, you will not be able to contribute to Mono. In general, be careful when you are implementing free software and you have access to proprietary code. We need to make sure that we are not using someone else's copyrighted code accidentally. http://www.mono-project.com/Contributing -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: del and sets proposal
On Oct 2, 11:27 pm, Larry Bates [EMAIL PROTECTED] wrote: I didn't mean to imply that del a[1] would delete the first thing in the set, but rather the item with a value of 1. Just as when we use it on a dictionary: del a[1] doesn't mean delete the first dictionary entry but rather delete the entry in the object with a value of 1, which IMHO would be perfectly logical for a set (which is why I started this discussion). It's not logical at all. In all current uses of del, the thing that follows del is a valid expression. With sets, that's not the case. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
2008/9/30 Lie Ryan [EMAIL PROTECTED]: Actually str.len and len(str) is just like saying the string's length and the length of the string. There is no difference between the two except for personal preference. (I am no linguist-- not even a native speaker of English --but I think there is a subtle difference on emphasis, the string's length emphasizes on the length being string's property, while the length of the string emphasizes on the length itself, am I correct?) Well, I'm doing a linguistics degree, so I'm not a linguist /yet/, but I think I know this one. There is the difference in emphasis that you mention, but there may be something more significant. In both forms, length is what linguists call the head of the noun phrase: it's the actual thing being talked about. In The string's length the head is only pre-modified (the string's comes before the head and there's nothing after the head). The length of the string has both pre- and post- modification (The before, of the string after). Post modification in noun phrases has been measured to be much less frequent in spoken English than in written English, and it gets progressively more common as the writing style gets more formal. That suggests that the string's length is an easier phrase to produce and understand, but the length of the string sounds more official. -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: javascript to python
lkcl a écrit : On Oct 2, 7:42 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: lkcl a écrit : (snip) for fits and giggles, compile the above python using pyjs.py, the python-to-javascript compiler (seehttp://pyjamas.sf.net) and compare the resultant javascript to your original code-fragment. l. I did. Here's the result: ok - these are the important bits. notice that the pyjamas compiler is doing a little bit more than your original code: Not 'mine' - I'm not the OP. And as far as I'm concerned, the point is exactly here : it's doing a little bit more than the original code. This little bit requires 6 times the original code (cf below), and is actually useless for the OP's use case (else the OP's code wouldn't use litteral object notation but a full-blown prototype). it's overriding the prototype of dataListener, making it a true class object. There's nothing like a notion of class in javascript - as you of course already know. this is where there's a key departure from the original code and the translation to python: the original code isn't actually a class, at all Indeed. Why would it need to be ? - it's more like a c struct that has function pointers in it. It's an object. What's wrong with objects ? by declaring a python class, the javascript equivalent is to add to prototypes. Indeed. But the point is that Python - while close to a prototype-based language in many aspects - is still class-based. The closer Python translation of the OP's javascript snippet is probably the one I gave using a 'class singleton' - that is, using the class itself as an object. But retranslating this to javascript using a python-source-to-javascript-source tool like pyjamas won't give you back the original javascript snippet (which is by no mean a criticism of pyjamas - it would just be way too complicated to automatize such a translation). __dataListener.prototype.__init__ = function() { var data = ''; }; [ ... so for example here, now when you declare _any number_ of dataListeners, What for ? In the original snippet, there's clearly only a need for a single one - and that's a *very* common pattern in browser-side javascript scripting. The original snippet is 12 lines, 29 words, 369 bytes long (according to wc). The pyjamas translation of the Python translation of the original javascript snippet is 49 lines, 126 words, 2285 bytes long. That's 6 times more code (to download and parse) - for an unneeded feature. Often, less is better. each and every one will have its __init__ function called. in your original example, my ? I repeat : I'm *not* the OP. you're effectively making one and only one dataListener. s/you/the OP/ And yes, indeed, there's only one dataListener object. What makes you think there's a need for more than one ? you're kinda... it's a bit like having a lambda-class (nameless class) and declaring one and only one instance of that python class... ] It's like having an object. period. While most OOPLs are class-based, classes are by no mean a requirement of OO. so - yeah, you can see that (apart from the .prototype, which is necessary to make a class a la javascript) it's a pretty accurate translation back to the original javascript. I don't mean it's not working. I mean that it's a lot of unnecessary code for an unnecessary feature. Believe me, 6 times more code makes a *huge* difference when it comes to browser-side scripting and user-experience. Also and IMHO, it's trying to forcefit alien idioms in javascript. Being prototype-based is by design - it's not a shortcoming. All this, and more, thanks to the strange idea that it would be better to write javascript in Python instead of writing it in javascript !-) *lol* :) fortunately, pyjs.py does that translation for you ha ha. like they say on brainiac, STOP! we do these experiments, so you don't have to. fortunately is judgement call. As far as I'm concerned, and despite a couple warts (but hey, no language is wart-free, and Python has it's own share, isn't it ?), I like javascript as a language, and enjoy coding in javascript almost as much as I enjoy coding in Python. yes - it's because in the translated python, dataListener was declared as a class, whereas in the original javascript, the corresponding concept (prototypes) are not made use of. There's probably a reason why the OP didn't use a full blown prototype, isn't it ?-) if you wanted to experiment, you could try this: def onStartRequest(this, request, context): pass def onStopRequest(this, request, context, status): instream.close() oustream.close() listener.finished(this.data) def onDataAvailable(this, request, context, inputStream, offset, count): this.data += instream.read(count) class dataListener: def __init__(self): self.data = '' self.onStartRequest = onStartRequest self.onStopRequest
Re: Python arrays and sting formatting options
Marc 'BlackJack' Rintsch: bearophile while xrange(n) is a bit less easy to understand (a generator or generators). I meant a generator of generators, a typo, sorry. -.- Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Fun with reverse sorts
Chris Rebert: So the improved code is: your_list.sort(key=lambda elem: (elem[3], elem[2]), reverse=True) Better (untested): from operator import itemgetter ... your_list.sort(key=itemgetter(3, 2), reverse=True) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance but only partly?
On Oct 2, 10:16 pm, process [EMAIL PROTECTED] 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) ? Don't use inheritance, use delegation or just copy the methods you need: class A(object): def meth_a(self): pass class B(object): meth_a = A.meth_a.im_func IMO, if you have methods that you want to use in different classes, this is hint that you are in need of generic functions. See this blog post for an example: http://www.artima.com/weblogs/viewpost.jsp?thread=237764 -- http://mail.python.org/mailman/listinfo/python-list
Re: del and sets proposal
Steven D'Aprano: Personally, I'd rather see dictionaries grow methods like symmetric_difference, union, etc. than worry about whether you use del or remove to remove elements from a set. I have functions for all those operations, so I think they can be useful, but in practice I don't use them often. I think it's a matter of keeping data structures separated in the mind. Another problem is that with those operations you have to find a way to manage values too, are they part of the uniqueness, etc? So there can be different semantics of a single operation, and this may lead to people that have a wrong image model of the purpose of some of those methods. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: javascript to python
On Oct 3, 10:29 am, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: lkcl a écrit : On Oct 2, 7:42 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: lkcl a écrit : Not 'mine' - I'm not the OP. whoops, yes - i missed that. sorry! And as far as I'm concerned, the point is exactly here : it's doing a little bit more than the original code. yeah, i know. and that bit more gets you a proper representation of the python class concept. i was merely pointing out that if you want to _really_ translate the original code into python - _really_ strictly - it's not actually possible. because python doesn't have the concept of non-prototyping (but... see below: i believe i may stand corrected on that) [..snip..] and is actually useless for the OP's use case (else the OP's code wouldn't use litteral object notation but a full-blown prototype). i know :) it's overriding the prototype of dataListener, making it a true class object. There's nothing like a notion of class in javascript - as you of course already know. okay,okay :) class-like :) Indeed. But the point is that Python - while close to a prototype-based language in many aspects - is still class-based. The closer Python translation of the OP's javascript snippet is probably the one I gave using a 'class singleton' - that is, using the class itself as an object. oh is _that_ how you do it. thanks. i always wondered how you did class singletons in python. python-source-to-javascript-source tool like pyjamas won't give you back the original javascript snippet (which is by no mean a criticism of pyjamas - it would just be way too complicated to automatize such a translation). well... you _say_ that... but... actually, if that's the real way to represent class singletons, and it's an accurate representation of the OP's javascript, and a good example, then _yes_, pyjs should definitely have that added as a feature - to understand that a class singleton _can_ get mapped to the much more efficient javascript example you gave. not that many people would _want_ to do that, so it goes onto the diminishing returns TODO list, but... Nope. You defined functions outside the object's scope, and you still have to instanciate dataListener. Also, this above code just won't work - unless you explicitely pass the dataListener instance to the functions, ie: d = dataListener() d.onDataAvailable(d, ...) yeah - i didn't realise what the python class singleton thing was. It seem you didn't read my other translation proprosal, so I repost it here: class dataListener(object): data = '' i did - i just didn't understand its significance. so - to get this straight: when you do class clsname(object), and you have the indentation and declaration of variables (e.g. data, above) at the same level as the functions, it means that there's only one of them? (i.e. a singleton)? so, if i do this: d = dataListener() e = dataListener() d.data = fred print f.data will return fred? l. -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance but only partly?
2008/10/2 process [EMAIL PROTECTED]: 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? As others have said, no. What nobody seems to have said yet is why. If Y descends from X, you are saying that Y is an X; that a Y can be used anywhere an X can. If Y doesn't support some methods of X then it is *not* an X, and *can't* be used anywhere an X can. Rather than looking at workarounds, as others have, I think you need to go back to your design and work out what's gone wrong that you /want/ to descend Y from X. Your present design is wrong, plain and simple. Working around it won't fix that. -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
lxml and schema validation
Hi I am validating a xmlfile against a xsd (My.xsd) but i notice that the xsd has a include which includes another xsd (My1.xsd) I have written a simple program that to validate this from lxml import etree xmlschemadoc=etree.parse(My.xsd) xmlschema=etree.XMLSchema(xmlschemadoc) xmldoc=etree.parse(My.XML) xmlschema.assertValid(xmldoc) will my program validate against My.xsd and My1.xsd both ? I also would like my program to continue validation against the xsd and not stope at the first failure . my question would be how do i do that in python ? regards Hrishy -- http://mail.python.org/mailman/listinfo/python-list
Re: windows help files ?
Martin v. Löwis wrote: 1. how can I launch the windows help file (CHM), from python with a keyword as argument ? Run hh.exe. If you want it to navigate to specific page, also pass that page on the command line (finding out the exact syntax is left as an exercise) That's one way, in the meanwhile I found win32help.py, which I finally got to work. The whole hh.exe (seems also to be a wellknown virus) and win32help documentation is very hard to find. 2. now when my program should also run under Linux/Mac, how should I call the help file under Linux/Mac. Provide an HTML tree of the documentation, and use the webbrowser module to start a browser on it. Yes, but for context sensitive help that's a little bit primitive. I'm now working on the idea of offering 3 levels of context sensitive help (through F1, shift-F1, ctrl-F1): - standard doc ( chm-keyword / html-tag ) - search on google - help from a user defined location ( chm / html / search engine / txt / pdf ) thanks again, cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
SQLite
Hi, This is probably trivial, but I cannot find a solution right now. With MySQLdb, I could test the success of a deleting action like this: sql = DELETE FROM table WHERE name='xxx' res = cur.execute(sql) if res == 1: print 'Okay' else: print 'nothing deleted' This seems not to work with sqlite3. How can I test whether deletion was sussessful or not? Thanks, Matthias -- http://mail.python.org/mailman/listinfo/python-list
[BaseHTTPServer/SimpleHTTPServer] Remove Server: header
Hello. I'm using SimpleHTTPServer (work well) but it always sends Server header in response: Server: SimpleHTTP/0.6 Python/2.5.1 How can I remove that ? I tried: self.server_version = self.sys_version = but the header is still sent, empty. I there a way to remove the Server: header completely ? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance but only partly?
2008/10/3 Tim Rowe [EMAIL PROTECTED]: As others have said, no. What nobody seems to have said yet is why. If Y descends from X, you are saying that Y is an X; that a Y can be used anywhere an X can. If Y doesn't support some methods of X then it is *not* an X, and *can't* be used anywhere an X can. See http://en.wikipedia.org/wiki/Liskov_substitution_principle. -- Cheers, Simon B. [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns | Facebook: http://tinyurl.com/6f47zo -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite
Howdy Matthias! The delete operation will set the rowcount member of your cursor. Let's assume you have an sqlite3 database with a table called 'test' with an id column. It does have a record with id=1. It does not have a record with id=2. import sqlite3 connection = sqlite3.connect('test.sqlite3') cursor = connection.cursor() cursor.execute('delete from test where id=1') sqlite3.Cursor object at 0x7f3450 print cursor.rowcount 1 cursor.execute('delete from test where id=2') sqlite3.Cursor object at 0x7f3450 print cursor.rowcount 0 cursor.close() connection.close() --gordy -- http://mail.python.org/mailman/listinfo/python-list
tkinter question
I saw this (close to this anyway) lieing around on the internet and was wanting to use it to define a start point exc but I need the graphics to stay within a set y coords and I am not realy sure how to do that. I have no idea on how to bind a min/max y to it. (the concept is inspired by the java csound blue). #!/usr/bin/python from Tkinter import * import csoundroutines as cs root = Tk() global canv xx = {} def makeFrame(root): global canv test = cs.csdInstrumentlist3('bay-at-night.csd') canv = Canvas (root, height = 200, width = 350) for i in range (0, len(test.instr_number)): canv.create_text(10, i *10, text=str(test.instr_number[i]) + '...', tags=('movable')) xx[i] = canv.tag_bind('movable', 'B1-Motion', slide) #B1-motion is a drag with left button down canv.pack() def slide (event): ''' triggered when something is dragged on the canvas - move thing under mouse ('current') to new position ''' newx = event.x if event.y 10 and event.y 0: newy = event.y canv.coords('current', newx, newy) makeFrame(root) root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: del and sets proposal
On Fri, 03 Oct 2008 02:09:09 -0700, Carl Banks wrote: On Oct 2, 8:02 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: Then add subscription access too. By aliasing `__getitem__()` to `__contains__()`. And `__setitem__()` could be implemented to add or remove objects by assigning truth values. So hypothetically: a = set([1, 2, 3]) a[1] True a[4] False a[2] = False a set([1, 3]) a[4] = True a set([1, 3, 4]) del a[1] a set([3, 4]) I wouldn't want that addition to `set`\s but at least it can be implemented without introducing inconsistencies. If set behaved that way then del a[1] wouldn't behave like del anymore. Normally, del whatever means that you can no longer use whatever; in this proposal you can. Then there should be no ``del`` for `collections.defaultdict`: In [169]: from collections import defaultdict In [170]: d = defaultdict(int) In [171]: d[42] Out[171]: 0 In [172]: del d[42] In [173]: d[42] Out[173]: 0 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
processing email with Python on Windows?
I work for a financial company where we run Windows XP and read email using Microsoft Outlook 2003. I get daily files that come as email attachments from various counterparties. I save them as h:\firm_name \mmdd.csv . Would Python be a good tool to automate the process of saving reports, or would it be more convenient to use a Microsoft proprietary language such as VB or C#? Of course one factor is one's relative competence with the various languages. -- http://mail.python.org/mailman/listinfo/python-list
Re: javascript to python
so, if i do this: d = dataListener() e = dataListener() d.data = fred print f.data duh, duh - that should be print e.data :) -- http://mail.python.org/mailman/listinfo/python-list
execute a function before and after any method of a parent class
Hi everybody, I would like to be able to specialize an existing class A, so as to obtain a class B(A), with all methods of B being the methods of A preceded by a special method of B called _before_any_method_of_A( self ), and followed by a special method of B called _after_any_method_of_A( self ). The goal is to avoid to redefine explicitly in B all methods of A. Is this possible in Python? Thanks a lot Julien -- python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z (55l4(']) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong. (first law of AC Clarke) -- http://mail.python.org/mailman/listinfo/python-list
Re: [BaseHTTPServer/SimpleHTTPServer] Remove Server: header
you've got ?self.send_header('Server', self.version_string()) in the send_response method of the BaseHTTPRequestHandler class in the BaseHTTPServer module. Long story, short, it's going to be a lot of work to get rid of. [EMAIL PROTECTED] wrote: Hello. I'm using SimpleHTTPServer (work well) but it always sends Server header in response: Server: SimpleHTTP/0.6 Python/2.5.1 How can I remove that ? I tried: self.server_version = self.sys_version = but the header is still sent, empty. I there a way to remove the Server: header completely ? Thanks. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
On 2008-10-03, greg [EMAIL PROTECTED] wrote: Lawrence D'Oliveiro wrote: In message [EMAIL PROTECTED], Steven D'Aprano wrote: (2) Even when the source is available, it is sometimes a legal trap to read it with respect to patents and copyright. That's not how patents work. I don't think that's how copyrights work either. As far as I know, whether something is deemed a derivative work is judged on the basis of how similar it is to another work, not whether its author had knowledge of the other work. As long as you express an idea in an original way, it shouldn't matter where you got the idea from. IANAL, but IIRC it does matter when it comes to establishing punative damages. If you knowingly and intentionally infringe a patent, I think you're libel for more damages than if you accidentally re-invent something. At least that's what I was told... -- Grant Edwards grante Yow! Thousands of days of at civilians ... have produced visi.coma ... feeling for the aesthetic modules -- -- http://mail.python.org/mailman/listinfo/python-list
Re: windows help files ?
In message [EMAIL PROTECTED], Lie Ryan wrote: ...python's docstring viewer has a less-like pager (or was it less) in Linux ... It invokes whatever you define in $PAGER. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
On Fri, 2008-10-03 at 09:15 -0500, Grant Edwards wrote: On 2008-10-03, greg [EMAIL PROTECTED] wrote: Lawrence D'Oliveiro wrote: In message [EMAIL PROTECTED], Steven D'Aprano wrote: (2) Even when the source is available, it is sometimes a legal trap to read it with respect to patents and copyright. That's not how patents work. I don't think that's how copyrights work either. As far as I know, whether something is deemed a derivative work is judged on the basis of how similar it is to another work, not whether its author had knowledge of the other work. As long as you express an idea in an original way, it shouldn't matter where you got the idea from. IANAL, but IIRC it does matter when it comes to establishing punative damages. If you knowingly and intentionally infringe a patent, I think you're libel for more damages than if you accidentally re-invent something. At least that's what I was told... s/libel/liable/ When talking about legal matters, it's kind of an important distinction. -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function before and after any method of a parent class
Maybe you can use __getattribute__. I tried it, but got stuck trying to let __getattribute__ work normal without calling itself. class A(object): def foo(self): print hi class B(A): def __getattribute__(self,name): try: fun = A.__dict__[name] except KeyError: fun = None if fun and callable(fun): self._before_any_method_of_A() result = fun(self) self._after_any_method_of_A() return result else: # do some stuff to act normal try: # erm, this invokes __getattribute__, which will invoke again, # and again, and again... return self.__dict__[name] except KeyError: pass try: return B.__dict__[name] except KeyError: pass def _before_any_method_of_A(self): print before def _after_any_method_of_A(self): print after b = B() b.foo() greetings, Almar 2008/10/3 TP [EMAIL PROTECTED] Hi everybody, I would like to be able to specialize an existing class A, so as to obtain a class B(A), with all methods of B being the methods of A preceded by a special method of B called _before_any_method_of_A( self ), and followed by a special method of B called _after_any_method_of_A( self ). The goal is to avoid to redefine explicitly in B all methods of A. Is this possible in Python? Thanks a lot Julien -- python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z (55l4(']) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong. (first law of AC Clarke) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
On 2008-10-03, J. Cliff Dyer [EMAIL PROTECTED] wrote: On Fri, 2008-10-03 at 09:15 -0500, Grant Edwards wrote: On 2008-10-03, greg [EMAIL PROTECTED] wrote: Lawrence D'Oliveiro wrote: In message [EMAIL PROTECTED], Steven D'Aprano wrote: (2) Even when the source is available, it is sometimes a legal trap to read it with respect to patents and copyright. That's not how patents work. I don't think that's how copyrights work either. As far as I know, whether something is deemed a derivative work is judged on the basis of how similar it is to another work, not whether its author had knowledge of the other work. As long as you express an idea in an original way, it shouldn't matter where you got the idea from. IANAL, but IIRC it does matter when it comes to establishing punative damages. If you knowingly and intentionally infringe a patent, I think you're libel for more damages than if you accidentally re-invent something. At least that's what I was told... s/libel/liable/ Of course. When talking about legal matters, it's kind of an important distinction. Once again we see why a spell-checker is no substitue for proof-reading. A bit of googling finds that 35 USC 284 allows the court to increase damages up to triple the compensatory value. Whether or not the infringement was willful is often a primary consideration in that decision. http://www.invention-protection.com/ip/publications/docs/Damage_Relief_for_Patent_Infringement.html http://www.ipwatchdog.com/willful_patent_infringement.html http://www.law.duke.edu/journals/dltr/articles/2007DLTR0006.html If the infringer never new the invention was patented, then the infringement can't be willful. -- Grant Edwards grante Yow! I'm ANN LANDERS!! at I can SHOPLIFT!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter textwidget problem
Tk/Tkinter apparently considers the position 1.13 to be after the last word in the text. You get the same problem if you set the insertion point just after the word 'two' for example: text.index('insert') returns 1.7 and text.index('insert wordstart') returns 1.7 too... Exactly. My solution would simply be to go back one character before asking the word start: text.index('insert - 1 chars wordstart') Don't know if that'll do what you want if there are spaces at the end of the text. And BTW, if you actually want the *last* word in the text, you may want to use text.index('end - 2 chars wordstart'). Here, you have to use '- 2 chars' because end points to the first non-existent index (2.0 in your case...). HTH Good idea, it seems to work fine now. See you. Kib². -- http://mail.python.org/mailman/listinfo/python-list
ABCs - infix syntax for isinstance() ?
Given the ABC innovation, maybe an infix syntax for isinstance() would be good. Possibilities : - stealing is away from object identity. As a motivation, true use cases for testing object identity are rare; forcing the usage of a function or method to test it, would dissuade abuse. - allowing containment tests, ie x in Number to invoke isinstance() in the background when the container is of type type. My brain is too muddled by flu at the moment, to see whether Guido's fabled time machine allowed him to already provide all the necessities in py26. Any takers ? - combining both keywords to create a third one, eg is in Whaddyathink ? BB -- http://mail.python.org/mailman/listinfo/python-list
C API type issue
Made a simple little test program as im learning to embed python, have a simple script that just sets x=10.0 in test.py and prints type(x). Python prints that x is a float but PyFloat_Check() returns false. If i removed the check and just force it to print the double value, its correct. Any ideas why PyFloat_Check() returns false on a float? Thanks in advance. #include Python.h #include cstdio int main(int argc, char** argv) { FILE* fp = fopen(test.py, r); assert(fp); Py_Initialize(); // //create a dictionary, load the builtins and execute our file // PyObject *d = PyDict_New(); assert(d); PyDict_SetItemString(d, __builtins__, PyEval_GetBuiltins()); PyRun_File(fp, test.py, Py_file_input, d, NULL); // //get a variable that should be in our global namespace // PyObject *x = PyDict_GetItemString(d, x); assert(x); Py_DECREF(d); // //determine its type and print it // if(PyFloat_Check(x)) { printf(x = %lf\n, PyFloat_AS_DOUBLE(x)); } Py_DECREF(x); Py_Finalize(); fclose(fp); return 0; } -- http://mail.python.org/mailman/listinfo/python-list
Re: ABCs - infix syntax for isinstance() ?
Boris Borcic: - combining both keywords to create a third one, eg is in A note only on syntax: isa seems better for Python. I don't comment how useful it can be. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: lxml and schema validation
hrishy wrote: I am validating a xmlfile against a xsd (My.xsd) but i notice that the xsd has a include which includes another xsd (My1.xsd) I have written a simple program that to validate this from lxml import etree xmlschemadoc=etree.parse(My.xsd) xmlschema=etree.XMLSchema(xmlschemadoc) Includes/Imports will be resolved at this point. xmldoc=etree.parse(My.XML) xmlschema.assertValid(xmldoc) will my program validate against My.xsd and My1.xsd both ? It will be validated against My.xsd, which (as you said), includes My1.xsd. So, yes, both schemas will participate in the validation. I also would like my program to continue validation against the xsd and not stope at the first failure. You want to get a list of all validation errors, instead of bailing out after the first failure, right? libxml2 doesn't support that. All you get is the list of errors in the error log of the validator, but when libxml2 decides to bail out from the validation, that's it. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: lxml and adding a stylesheet
Sean Davis wrote: I have an xml document and simply need to add an xml-stylesheet to it. I am using lxml to parse the xml document and then would like to insert the xml-stylesheet tag using the etree api. Any suggestions? I assume you are talking about a processing instruction here, not a tag. Use the .addprevious() method on the root Element with a PI object. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: lxml question
Uwe Schmitt wrote: I have to parse some text which pretends to be XML. lxml does not want to parse it, because it lacks a root element. I think that this situation is not unusual, so: is there a way to force lxml to parse it ? My work around is wrapping the text with root.../root before feeding lxmls parser. Yes, you can do that. To avoid creating an intermediate string, you can use the feed parser and do something like this: parser = etree.XMLParser() parser.feed(root) parser.feed(your_xml_tag_sequence_data) parser.feed(/root) root = parser.close() Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: closures and dynamic binding
On Oct 3, 3:44 am, greg [EMAIL PROTECTED] wrote: jhermann wrote: I didn't see this mentioned in the thread yet: the double-lambda is unnecessary (and a hack). Well, the alternative -- abusing default argument values -- is seen by many to be a hack as well, possibly a worse one. It doesn't work in general, e.g. it fails if the function needs to be called with a variable number of arguments. The double lambda is conceptually more sound in some ways, and can be made to work correctly in all cases. The root of the problem actually has nothing to do with lambdas or static vs. non-static scoping. It's the fact that Python's for-loop doesn't create a new environment for the loop variable each time around, but re-uses a slot in the containing environment. Contrast this with Scheme, where the equivalent of a for-loop *does* create a new environment for each value of the loop variable. Effectively it's using a double lambda, except that one of the lambdas is folded into the syntax of the loop, so you don't notice it. So if anything were to be done to the language to fix this, it really should be focused on fixing the semantics of the for-loop. Unfortunately, the fact that the loop variable leaks out of the scope of the loop is regarded as a feature, so anything which changes that seems to be a non-starter. -- Greg I agree that the default argument syntax is an abuse, but it accomplishes exactly what I want: to create a copy of a namespace. I don't think there's a way to create a closure in Python without another function, so you might need new syntax if you wanted to. Otherwise, using function syntax, I want a new namespace on each iteration that nests inside the old one, except for one variable which overrides the outer scope. I agree that a new variable isn't the obviously correct meaning of a for loop, and functions are the same as a new scope, just you have to call them, so why not use them as is? (untested) for i in range( 3 ): def f( n ): def g( ): return n return g closures[ i ]= f( i ) Or: (non-standard) for i in range( 3 ): closure f( i ): def g( ): return i return g closures[ i ]= f Here the only difference is whether you call 'f' or not. 'closure' would theoretically call itself, and make a copy of its scope upon execution of the definition, overriding the arguments. So, functions are the same. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is not objects in Python?
On Oct 3, 5:10 am, Tim Rowe [EMAIL PROTECTED] wrote: 2008/9/30 Lie Ryan [EMAIL PROTECTED]: Actually str.len and len(str) is just like saying the string's length and the length of the string. There is no difference between the two except for personal preference. (I am no linguist-- not even a native speaker of English --but I think there is a subtle difference on emphasis, the string's length emphasizes on the length being string's property, while the length of the string emphasizes on the length itself, am I correct?) Well, I'm doing a linguistics degree, so I'm not a linguist /yet/, but I think I know this one. There is the difference in emphasis that you mention, but there may be something more significant. In both forms, length is what linguists call the head of the noun phrase: it's the actual thing being talked about. In The string's length the head is only pre-modified (the string's comes before the head and there's nothing after the head). The length of the string has both pre- and post- modification (The before, of the string after). Post modification in noun phrases has been measured to be much less frequent in spoken English than in written English, and it gets progressively more common as the writing style gets more formal. That suggests that the string's length is an easier phrase to produce and understand, but the length of the string sounds more official. -- Tim Rowe ... Unless, there is some corresponding distinction in mechanics between speaking and writing. That is, if something about the process of generating writing makes it, post-modification, easier. I'm going to assume that it's been observed across all modes of writing too, (in addition to across all formality levels), where in all cases it was equally easy to go back and edit, which is impossible in speech. And, in the cases where the entire process of writing was observed, that neither kind of modification occurred more frequently in revisions. -- http://mail.python.org/mailman/listinfo/python-list
Re: do you fail at FizzBuzz? simple prog test
range(1,101), no? On Tue, May 20, 2008 at 4:46 PM, Sells, Fred [EMAIL PROTECTED] wrote: or for i in range(1,100): print ('fizz','','')[i%3] + ('buzz','','','','')[i%5] or i Write a program that prints the numbers from 1 to 100. But for multiples of three print Fizz instead of the number and for the multiples of five print Buzz. For numbers which are multiples of both three and five print FizzBuzz. for i in range(1,101): if i%3 == 0 and i%5 != 0: print Fizz elif i%5 == 0 and i%3 != 0: print Buzz elif i%5 == 0 and i%3 == 0: print FizzBuzz else: print i is there a better way than my solution? is mine ok? -- http://mail.python.org/mailman/listinfo/python-list -- http://www.badmuthahubbard.com -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function before and after any method of a parent class
On Oct 3, 9:03 am, TP [EMAIL PROTECTED] wrote: Hi everybody, I would like to be able to specialize an existing class A, so as to obtain a class B(A), with all methods of B being the methods of A preceded by a special method of B called _before_any_method_of_A( self ), and followed by a special method of B called _after_any_method_of_A( self ). The goal is to avoid to redefine explicitly in B all methods of A. Is this possible in Python? Thanks a lot Julien -- python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z (55l4(']) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong. (first law of AC Clarke) Yes it's possible. The exact solution depends on how much control you want, and over what. Do you want inheritance or delegation? Do you want the same pre and post method for all inherited methods? Will you always use single-inheritance? Would you mind using a list of names, as a sort of midpoint between complete redefinition and completely dynamic? Do you want class lookups to succeed? If so, what do you want them to do? Generally, you could build the class dynamically with a metaclass, or use __getattr__ a lookup. -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite
On Oct 3, 2008, at 2:33 PM, Matthias Huening wrote: This seems not to work with sqlite3. Before going any further... make sure that SQLite's count_change is enabled: PRAGMA count_changes PRAGMA count_changes = 0 | 1 Query or change the count-changes flag. Normally, when the count- changes flag is not set, INSERT, UPDATE and DELETE statements return no data. When count-changes is set, each of these commands returns a single row of data consisting of one integer value - the number of rows inserted, modified or deleted by the command. http://www.sqlite.org/pragma.html Cheers, -- PA. http://alt.textdrive.com/nanoki/ -- http://mail.python.org/mailman/listinfo/python-list
how to get a class instance name during creation?
hi all, I have a code z = MyClass(some_args) can I somehow get info in MyClass __init__ function that user uses z as name of the variable? I.e. to have __init__ function that creates field z.name with value z. Thank you in advance, D. -- http://mail.python.org/mailman/listinfo/python-list
Exploding (**myvariable) a dict with unicode keys
So Python can have unicode variable names but you can't explode (**myvariable) a dict with unicode keys? WTF? -Devin -- http://mail.python.org/mailman/listinfo/python-list
Re: windows help files ?
En Fri, 03 Oct 2008 09:07:21 -0300, Stef Mientki [EMAIL PROTECTED] escribió: Martin v. Löwis wrote: 1. how can I launch the windows help file (CHM), from python with a keyword as argument ? Run hh.exe. If you want it to navigate to specific page, also pass that page on the command line (finding out the exact syntax is left as an exercise) That's one way, in the meanwhile I found win32help.py, which I finally got to work. The whole hh.exe (seems also to be a wellknown virus) and win32help documentation is very hard to find. hh.exe is part of the Windows OS and is included on all non-prehistoric Windows versions. See http://support.microsoft.com/dllhelp/ win32help is part of the pywin32 package - but it's just a thin wrapper around the help API. The authoritative documentation source should be the Microsoft site: http://msdn.microsoft.com/en-us/library/cc196383.aspx -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: [BaseHTTPServer/SimpleHTTPServer] Remove Server: header
[EMAIL PROTECTED] wrote: I'm using SimpleHTTPServer (work well) but it always sends Server header in response: How can I remove that ? En Fri, 03 Oct 2008 11:11:34 -0300, Gary M. Josack [EMAIL PROTECTED] escribió: you've got ?self.send_header('Server', self.version_string()) in the send_response method of the BaseHTTPRequestHandler class in the BaseHTTPServer module. Long story, short, it's going to be a lot of work to get rid of. One can always write a customized RequestHandler, and just copy the send_response method omiting the offending line. (Ok, you have to check whether it still works with the next Python release... a warning triggered by a new sys.version would be enough to remember that) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleXMLRPCServer -- turning off request log?
Vinay Sajip [EMAIL PROTECTED] wrote: Did you try setting logRequests to false? Perfect, that's just what I needed. Thanks Vinay!! Mark -- Mark Harrison Pixar Animation Studios -- http://mail.python.org/mailman/listinfo/python-list
Re: Exploding (**myvariable) a dict with unicode keys
Devin wrote: So Python can have unicode variable names but you can't explode (**myvariable) a dict with unicode keys? WTF? That works fine for me. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Exploding (**myvariable) a dict with unicode keys
Martin v. Löwis wrote: Devin wrote: So Python can have unicode variable names but you can't explode (**myvariable) a dict with unicode keys? WTF? That works fine for me. The OP probably means def f(a=1): return a ... f(**{a: 42}) 42 f(**{ua: 42}) Traceback (most recent call last): File stdin, line 1, in module TypeError: f() keywords must be strings Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Exploding (**myvariable) a dict with unicode keys
On Oct 3, 1:57 pm, Peter Otten [EMAIL PROTECTED] wrote: Martin v. Löwis wrote: Devin wrote: So Python can have unicode variable names but you can't explode (**myvariable) a dict with unicode keys? WTF? That works fine for me. The OP probably means def f(a=1): return a ... f(**{a: 42}) 42 f(**{ua: 42}) Traceback (most recent call last): File stdin, line 1, in module TypeError: f() keywords must be strings Peter Yes, that's exactly what I mean. -- http://mail.python.org/mailman/listinfo/python-list
Re: execute a function before and after any method of a parent class
En Fri, 03 Oct 2008 11:03:22 -0300, TP [EMAIL PROTECTED] escribió: I would like to be able to specialize an existing class A, so as to obtain a class B(A), with all methods of B being the methods of A preceded by a special method of B called _before_any_method_of_A( self ), and followed by a special method of B called _after_any_method_of_A( self ). The goal is to avoid to redefine explicitly in B all methods of A. Is this possible in Python? Sure. After reading this (excelent!) article by M. Simionato http://www.phyast.pitt.edu/~micheles/python/documentation.html you should be able to write a decorator to make any method into a sandwich (probably based on his trace example). Your code would look like this: @decorator def sandwich(f, self, *args, **kw): self.before() f(self, *args, **kw) self.after() class A: @sandwich def foo(self): ... @sandwich def bar(self, x): ... Ok, but then you have to explicitely decorate every method. To avoid this, you may use a metaclass; this article by Michael Foord explains how: http://www.voidspace.org.uk/python/articles/metaclasses.shtml#a-method-decorating-metaclass That's all! -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Exploding (**myvariable) a dict with unicode keys
Devin wrote: On Oct 3, 1:57 pm, Peter Otten [EMAIL PROTECTED] wrote: Martin v. Löwis wrote: Devin wrote: So Python can have unicode variable names but you can't explode (**myvariable) a dict with unicode keys? WTF? That works fine for me. The OP probably means def f(a=1): return a ... f(**{a: 42}) 42 f(**{ua: 42}) Traceback (most recent call last): File stdin, line 1, in module TypeError: f() keywords must be strings Peter Yes, that's exactly what I mean. Hmm. Why did you say that Python can have unicode variable names? In the version you are using, it can't. In Python 3.0, it can, but then, you can also use Unicode strings as keys in **arguments, in Python 3.0. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Cheapest Generic Tramadol
generic tramadol . . . Enough to seek generic tramadol! You've already found the best site where you can buy generic tramadol online for lowest price! Just click our link below and buy cheap generic tramadol. To order generic tramadol without prescription visit link below! http://med247.us/?p=buy+tramadol . . . . . . . . . . . . . . . . . . . . . . . They all stared at eneric tramadol with equal marks of surprise, and whenever eneric tramadol cast eneric tramadol eyes upon him, invariably stroked eneric tramadol chins. They all stared at gneric tramadol with equal marks of surprise, and whenever gneric tramadol cast gneric tramadol eyes upon him, invariably stroked gneric tramadol chins. They all stared at geeric tramadol with equal marks of surprise, and whenever geeric tramadol cast geeric tramadol eyes upon him, invariably stroked geeric tramadol chins. They all stared at genric tramadol with equal marks of surprise, and whenever genric tramadol cast genric tramadol eyes upon him, invariably stroked genric tramadol chins. They all stared at geneic tramadol with equal marks of surprise, and whenever geneic tramadol cast geneic tramadol eyes upon him, invariably stroked geneic tramadol chins. They all stared at generc tramadol with equal marks of surprise, and whenever generc tramadol cast generc tramadol eyes upon him, invariably stroked generc tramadol chins. They all stared at generi tramadol with equal marks of surprise, and whenever generi tramadol cast generi tramadol eyes upon him, invariably stroked generi tramadol chins. They all stared at generic ramadol with equal marks of surprise, and whenever generic ramadol cast generic ramadol eyes upon him, invariably stroked generic ramadol chins. They all stared at generic tamadol with equal marks of surprise, and whenever generic tamadol cast generic tamadol eyes upon him, invariably stroked generic tamadol chins. They all stared at generic trmadol with equal marks of surprise, and whenever generic trmadol cast generic trmadol eyes upon him, invariably stroked generic trmadol chins. They all stared at generic traadol with equal marks of surprise, and whenever generic traadol cast generic traadol eyes upon him, invariably stroked generic traadol chins. What am generic tramdol to do, said the poorman. What am generic tramaol to do, said the poorman. What am generic tramadl to do, said the poorman. What am generic tramado to do, said the poorman. What am ggeneric tramadol to do, said the poorman. What am geeneric tramadol to do, said the poorman. What am genneric tramadol to do, said the poorman. What am geneeric tramadol to do, said the poorman. What am generric tramadol to do, said the poorman. What am generiic tramadol to do, said the poorman. What am genericc tramadol to do, said the poorman. What am generic ttramadol to do, said the poorman. What am generic trramadol to do, said the poorman. What am generic traamadol to do, said the poorman. What am generic trammadol to do, said the poorman. What am generic tramaadol to do, said the poorman. What am generic tramaddol to do, said the poorman. What am generic tramadool to do, said the poorman. What am generic tramadoll to do, said the poorman. He shrugged egneric tramadol shoulders, shook egneric tramadol head, cast up egneric tramadol eyes, but said nothing. He shrugged gneeric tramadol shoulders, shook gneeric tramadol head, cast up gneeric tramadol eyes, but said nothing. He shrugged geenric tramadol shoulders, shook geenric tramadol head, cast up geenric tramadol eyes, but said nothing. He shrugged genreic tramadol shoulders, shook genreic tramadol head, cast up genreic tramadol eyes, but said nothing. He shrugged geneirc tramadol shoulders, shook geneirc tramadol head, cast up geneirc tramadol eyes, but said nothing. He shrugged generci tramadol shoulders, shook generci tramadol head, cast up generci tramadol eyes, but said nothing. He shrugged generic tramadol shoulders, shook generic tramadol head, cast up generic tramadol eyes, but said nothing. He shrugged generic rtamadol shoulders, shook generic rtamadol head, cast up generic rtamadol eyes, but said nothing. He shrugged generic tarmadol shoulders, shook generic tarmadol head, cast up generic tarmadol eyes, but said nothing. He shrugged generic trmaadol shoulders, shook generic trmaadol head, cast up generic trmaadol eyes, but said nothing. He shrugged generic traamdol shoulders, shook generic traamdol head, cast up generic traamdol eyes, but said nothing. He shrugged generic tramdaol shoulders, shook generic tramdaol head, cast up generic tramdaol eyes, but said nothing. He shrugged generic tramaodl shoulders, shook generic tramaodl head, cast up generic tramaodl eyes, but said nothing. He shrugged generic tramadlo shoulders, shook generic tramadlo head, cast up generic tramadlo eyes, but said nothing. He shrugged generic tramadol shoulders, shook generic tramadol
Re: Python is slow?
greg wrote: Steven D'Aprano wrote: We agree that the restriction is artificial, and I think irrational I think it's irrational for another reason, too -- it's actually vacuous. There's nothing to prevent you creating a set of patches that simply say Delete all of the original source and replace it with the following. Then you're effectively distributing the modified source in its entirety, just with a funny header at the top of each source file that serves no useful purpose. The useful purpose is to show that you are distributing your work under someone else's product name, instead of making up your own as you ought to. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] PyYAML-3.06: YAML parser and emitter for Python
Announcing PyYAML-3.06 A new bug fix release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Changes === * setup.py checks whether LibYAML is installed and if so, builds and installs LibYAML bindings. To force or disable installation of LibYAML bindings, use '--with-libyaml' or '--without-libyaml' options respectively. * Building LibYAML bindings no longer requires Pyrex installed. * 'yaml.load()' raises an exception if the input stream contains more than one YAML document. * Fixed exceptions produced by LibYAML bindings. * Fixed a dot '.' character being recognized as !!float. * Fixed Python 2.3 compatibility issue in constructing !!timestamp values. * Windows binary packages are built against the LibYAML stable branch. * Added attributes 'yaml.__version__' and 'yaml.__with_libyaml__'. Resources = PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.06.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.06.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.06.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.06.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.06.win32-py2.5.exe http://pyyaml.org/download/pyyaml/PyYAML-3.06.win32-py2.6.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example === import yaml yaml.load( ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... ) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright = The PyYAML module is written by Kirill Simonov [EMAIL PROTECTED]. PyYAML is released under the MIT license. -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite
Thanks! cursor.rowcount does exactly what I need. Before going any further... make sure that SQLite's count_change is enabled: PRAGMA count_changes PRAGMA count_changes = 0 | 1 Query or change the count-changes flag. Normally, when the count-changes flag is not set, INSERT, UPDATE and DELETE statements return no data. When count-changes is set, each of these commands returns a single row of data consisting of one integer value - the number of rows inserted, modified or deleted by the command. Looks like this is not really necessary. My database hat count_changes disabled, but rowcount seems to work anyway. Are there any pitfalls? Matthias -- http://mail.python.org/mailman/listinfo/python-list
Re: C API type issue
En Fri, 03 Oct 2008 12:27:50 -0300, Rich Henry [EMAIL PROTECTED] escribió: Made a simple little test program as im learning to embed python, have a simple script that just sets x=10.0 in test.py and prints type(x). Python prints that x is a float but PyFloat_Check() returns false. If i removed the check and just force it to print the double value, its correct. Any ideas why PyFloat_Check() returns false on a float? Thanks in advance. You got the reference count wrong. This is by far the most common source of errors when writting C code for Python (at least for beginners) #include Python.h #include cstdio int main(int argc, char** argv) { FILE* fp = fopen(test.py, r); assert(fp); Py_Initialize(); // //create a dictionary, load the builtins and execute our file // PyObject *d = PyDict_New(); assert(d); PyDict_SetItemString(d, __builtins__, PyEval_GetBuiltins()); PyRun_File(fp, test.py, Py_file_input, d, NULL); Instead of a bare dictionary, I'd use a module. Or the __main__ module. See how PyRun_SimpleFileExFlags handles this (or just use that function, or other variant). // //get a variable that should be in our global namespace // PyObject *x = PyDict_GetItemString(d, x); assert(x); This returns a borrowed reference, not a new one. Py_DECREF(d); This releases the only reference to d, and the dictionary is deleted. This in turn releases the last refrence to x, and it's deleted too. //determine its type and print it // if(PyFloat_Check(x)) { printf(x = %lf\n, PyFloat_AS_DOUBLE(x)); } At this stage x is an invalid object. Py_DECREF(x); And this is wrong now. Py_Finalize(); fclose(fp); return 0; } -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Tkinter setting alpha
I'm trying to make a Tkinter/Python port of the demo at http://wiki.tcl.tk/10515 , which has adjustable alpha under Windows and (I think) MacOS. I'm not quite sure how to port: wm attributes . -alpha [expr {$alphaLevel + 0.05} ] set AlphaLevel [wm attributes . -alpha] The goal is to have a screen pop that fades in and out at least on Windows, and it would be nice if it could fade on other platforms (including my preferred Linux). Two questions: 1: Is Tkinter a good choice, or are there other libraries that are easier and/or will allow cross-platform GUI work with (ideally) fading in and out? 2: If I go with Tkinter, how can I port lines like those quoted above to be able to get and set a Frame's alpha value? -- -- Jonathan Hayward, [EMAIL PROTECTED] ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com ++ Would you like to curl up with one of my hardcover books? ++ You can now get my books from http://CJSHayward.com -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get a class instance name during creation?
En Fri, 03 Oct 2008 15:04:01 -0300, dmitrey [EMAIL PROTECTED] escribió: I have a code z = MyClass(some_args) can I somehow get info in MyClass __init__ function that user uses z as name of the variable? I.e. to have __init__ function that creates field z.name with value z. No. I'd just write it as: z = MyClass(some, args, 'z') wich is pretty simple and readable (although you have to repeat the 'z'). All the alternative ways I know of require too much black magic. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Exploding (**myvariable) a dict with unicode keys
On Oct 3, 2:29 pm, Martin v. Löwis [EMAIL PROTECTED] wrote: Devin wrote: On Oct 3, 1:57 pm, Peter Otten [EMAIL PROTECTED] wrote: Martin v. Löwis wrote: Devin wrote: So Python can have unicode variable names but you can't explode (**myvariable) a dict with unicode keys? WTF? That works fine for me. The OP probably means def f(a=1): return a ... f(**{a: 42}) 42 f(**{ua: 42}) Traceback (most recent call last): File stdin, line 1, in module TypeError: f() keywords must be strings Peter Yes, that's exactly what I mean. Hmm. Why did you say that Python can have unicode variable names? In the version you are using, it can't. In Python 3.0, it can, but then, you can also use Unicode strings as keys in **arguments, in Python 3.0. Regards, Martin Oh. I read somewhere that UTF-8 variable names we're supported. I thought I even saw a colleague using Kanji. -- http://mail.python.org/mailman/listinfo/python-list
Re: javascript to python
lkcl a écrit : On Oct 3, 10:29 am, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: lkcl a écrit : On Oct 2, 7:42 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: lkcl a écrit : And as far as I'm concerned, the point is exactly here : it's doing a little bit more than the original code. yeah, i know. and that bit more gets you a proper representation of the python class concept. Except that in most cases - at least when it comes to browser scripting[1] - this concept is just useless. IOW, that's quite a lot of code for something you just don't need. [1] but ask yourself how many times you end up having only one single instance of a given class in a python utility script... i was merely pointing out that if you want to _really_ translate the original code into python - _really_ strictly - it's not actually possible. really strictly, nope. But mainly because there's nothing in Python that behave like the 'this' javascript object (and it doesn't matter in the OP snippet). But you can have something quite close, using the class as an object (which it is anyway). because python doesn't have the concept of non-prototyping (but... see below: i believe i may stand corrected on that) !-) Indeed. But the point is that Python - while close to a prototype-based language in many aspects - is still class-based. The closer Python translation of the OP's javascript snippet is probably the one I gave using a 'class singleton' - that is, using the class itself as an object. oh is _that_ how you do it. thanks. i always wondered how you did class singletons in python. Note that this not really idiomatic Python - partly for cultural reasons, and mostly because use case and constraint differs (class singleton would surely become idiomatic if Python was used as browser-scripting language the way js is, because you then have to avoid any useless code to keep the site responsive). Anyway, that's still IMHO the pythonic way to translate a litteral javascript object - I fail to see anything closer in Python (if there's some guru around ?) python-source-to-javascript-source tool like pyjamas won't give you back the original javascript snippet (which is by no mean a criticism of pyjamas - it would just be way too complicated to automatize such a translation). well... you _say_ that... but... actually, if that's the real way to represent class singletons, and it's an accurate representation of the OP's javascript, and a good example, then _yes_, pyjs should definitely have that added as a feature - to understand that a class singleton _can_ get mapped to the much more efficient javascript example you gave. I'm afraid it's going to be quite complicated. You'd have to make sure the class only has classmethods - including inherited methods (and exception made of methods inherited from object). And FWIW, even such a class may be a base class for 'normal' python classes, so there's just no reliable semantic way to make sure the class is really a class singleton that should map to a litteral js object. See, the problem here is that we have two high level, highly dynamic languages, that are quite close on quite a lot of things but are based on two really different object models. So quite often, the best translation is obvious for a programmer with a decent knowledge of both languages, but almost impossible for a program because there are way too much imply stuff (like, for the python class singleton, the fact that the class is not meant to be instanciated is totally implicit). not that many people would _want_ to do that, Err... Do you have much experience in browser scripting ??? That's a *very* common js idiom. so it goes onto the diminishing returns TODO list, but... Nope. You defined functions outside the object's scope, and you still have to instanciate dataListener. Also, this above code just won't work - unless you explicitely pass the dataListener instance to the functions, ie: d = dataListener() d.onDataAvailable(d, ...) yeah - i didn't realise what the python class singleton thing was. In this case, the problem I pointed out was that Python's functions needs to be class instances to yield instancemethods when looked up on an instance or class. If you set a function as an instance attribute, the descriptor protocol is not invoked, and you just have a plain function (note that this is by design). It seem you didn't read my other translation proprosal, so I repost it here: class dataListener(object): data = '' i did - i just didn't understand its significance. so - to get this straight: when you do class clsname(object), and you have the indentation and declaration of variables (e.g. data, above) at the same level as the functions, it means that there's only one of them? (i.e. a singleton)? Nope. Whatever is declared within the class statement becomes a class attribute - that is, an attribute of the class object, shared
Re: ABCs - infix syntax for isinstance() ?
Boris Borcic a écrit : Given the ABC innovation, maybe an infix syntax for isinstance() would be good. Possibilities : - stealing is away from object identity. As a motivation, true use cases for testing object identity are rare; x is None is a *very* common test. Using a _marker object as default arg value when you want to accept None as a meaningfull value is pretty common. Testing a class identity often happens when writing metaclasses. -- http://mail.python.org/mailman/listinfo/python-list
Re: Stopping a Thread with Time Slicing
Hi Todd, Thanks for your suggestions on using the Event condition methods on this thread. Here is my updated code : import time import datetime import threading def log(message): now = datetime.datetime.now().strftime(%H:%M:%S) print %s : %s % (now, message) class StoppableThread(threading.Thread): def __init__(self, sleep_time, function, args=[], kwargs={}): self.sleep_time = sleep_time threading.Thread.__init__(self) self.function = function self.args = args self.kwargs = kwargs self.finished = threading.Event() def run(self): while not self.finished.isSet():# loop while condition is true log('** Doing Work') self.function(*self.args, **self.kwargs) # run the function self.finished.wait(self.sleep_time) # put thread in wait state log('** Thread Has STOPPED!') def stop(self): # stop the thread from running log('* Stopping Thread') self.finished.set() self.join() def my_function (a, b, c): log('my_function running... %s' % a) # #T E S T # SMALL_SLEEP = 35 CHECK_SLEEP = 300 # sleep interval in seconds to run a timed process log('Create Thread') thread_obj = StoppableThread(CHECK_SLEEP, my_function, (15,0,-1)) log('Thread Start\n') thread_obj.start() for current_loop in range(0,10): time.sleep(SMALL_SLEEP) log('current loop = %d \n' % current_loop) log('Call Thread Stop') thread_obj.stop() log('Done!') Test Output : python Simple_Thread_Stop_Event.py 12:58:42 : Create Thread 12:58:42 : Thread Start 12:58:42 : ** Doing Work 12:58:42 : my_function running... 15 12:59:17 : current loop = 0 12:59:52 : current loop = 1 13:00:27 : current loop = 2 13:01:02 : current loop = 3 13:01:37 : current loop = 4 13:02:12 : current loop = 5 13:02:47 : current loop = 6 13:03:22 : current loop = 7 13:03:42 : ** Doing Work 13:03:42 : my_function running... 15 13:03:57 : current loop = 8 13:04:32 : current loop = 9 13:04:32 : Call Thread Stop 13:04:32 : * Stopping Thread 13:04:32 : ** Thread Has STOPPED! 13:04:32 : Done! On Oct 2, 4:40 pm, Todd Whiteman [EMAIL PROTECTED] wrote: Steve wrote: A better approach for this is to use a Python Event or Condition object:http://docs.python.org/library/threading.html#id5 Example code: import threading my_stop_event = threading.Event() # Sleep Loop : #for current_loop in range(0, self.time_slice) : # time.sleep(self.sleep_time / self.time_slice) event.wait(self.sleep_time) if not self.running: # check the flag break # break out of the sleep loop # From another thread, you can notify the above sleeping thread using: my_stop_event.set() Cheers, Todd -- http://mail.python.org/mailman/listinfo/python-list
Re: closures and dynamic binding
greg wrote: jhermann wrote: I didn't see this mentioned in the thread yet: the double-lambda is unnecessary (and a hack). Well, the alternative -- abusing default argument values -- is seen by many to be a hack as well, possibly a worse one. I disagree. It is one way to evaluate an expression when a function is compiled. It doesn't work in general, e.g. it fails if the function needs to be called with a variable number of arguments. So? Many things do not work 'in general'. If one wants multiple closures with a variable number of arguments, one should use a def statement and some other binding method, such as given below Here are four ways to get the list of closures desired: All print 0 ... 9 with for f in lst: print(f()) #3.0 lst = [] for i in range(10): lst.append(eval(lambda: %d %i)) # use exec instead of eval with def statement instead of lambda expression lst = [] def f(i): return lambda: i for i in range(10): lst.append(f(i)) #I would most likely use this, with a def instead of lambda inside f for any real, non-trivial example. def populate(n): n -= 1 if n = 0: return populate(n)+[lambda:n] else: return [] lst = populate(10) # body recursion def populate(i,n,lst): if i n: return populate(i+1,n,lst+[lambda:i]) else: return lst lst = populate(0,10,[]) # tail recursion Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get a class instance name during creation?
dmitrey a écrit : hi all, I have a code z = MyClass(some_args) can I somehow get info in MyClass __init__ function that user uses z as name of the variable? I.e. to have __init__ function that creates field z.name with value z. This has been debated to hell and back. To make a long story short, here are two common use cases: x = MyClass() y = x del x objects = [MyClass() for i in range(100)] If you can come with a meaningfull answer to what's *the* name of any of the MyClass instance(s) in both cases, then please let us know... -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove Server: header
On 3 oct, 20:17, Gabriel Genellina [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: I'm using SimpleHTTPServer (work well) but it always sends Server header in response: How can I remove that ? En Fri, 03 Oct 2008 11:11:34 -0300, Gary M. Josack [EMAIL PROTECTED] escribió: you've got ?self.send_header('Server', self.version_string()) in the send_response method of the BaseHTTPRequestHandler class in the BaseHTTPServer module. Long story, short, it's going to be a lot of work to get rid of. One can always write a customized RequestHandler, and just copy the send_response method omiting the offending line. (Ok, you have to check whether it still works with the next Python release... a warning triggered by a new sys.version would be enough to remember that) I see. No choice but to override the method with a copy of the source :-/ I guess I'll have to do with that. Thanks. -- http://mail.python.org/mailman/listinfo/python-list