Re: (don't bash me too hard) Python interpreter in JavaScript
On Nov 15, 11:51 pm, Carl Banks wrote: > Some people have already made an LLVM-to-Javascript compiler, and have > managed to build Python 2.7 with it. > > The LLVM-to-Javascript project is called emscripten. > > https://github.com/kripken/emscripten/wiki > > Demo of Python (and a bunch of other languages) here: > > http://repl.it/ > > Carl Banks It definitely looks great!! -- http://mail.python.org/mailman/listinfo/python-list
Re: (don't bash me too hard) Python interpreter in JavaScript
> Very interesting. Is there a simple way to add third-party > libraries to these? I assume that for pure-Python modules you could > just put a python file in the appropriate place and import it, but what > about if you wanted a web app that used numpy or something? Is that > feasible? > I cannot imagine how slow can be a python interpreter in javascript crunching numbers using numpy, and converting those numeric libraries (ATLAS, LAPACK,MKL,ACML) to javascript. -- http://mail.python.org/mailman/listinfo/python-list
NEWBIE: Script help needed
I have this script that I want to use weekly to send me email with information regarding disk space and available upgrades for my system. This script is actually a learning tool for me as I learn Python. The problem I've run into has me stumped and I need some help. What happens is when the script runs it does these things, parses the result and appends that to an html string: 1) checks disk space by using df -t reiserfs 2) runs time emerge --sync 3) runs emerge -uvp world 4) runs emerge -uv --fetchonly world The 'emerge' command is a Gentoo specific one. If I remove step 3), everything else runs just fine, the email is sent and I receive what I expect. But when step 3) is allowed to run, even if its the only command that runs, it hangs somewhere in the function getCommandOutput. If I try and debug the command, it appears to hang on this line: err = child.wait() I suspect a race condition, but I'm not sure how to proceed, can someone lend me a hand. Here is the script I wrote, I got the command getCommandOutput from this site: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52296 TIA [code] #!/usr/bin/python ### NEED TO RUN THIS AS ROOT ### ### EMERGE SYNC REQUIRES THIS ### import os, re, smtplib, MimeWriter, mimetools, cStringIO, popen2, fcntl, select, pdb cmd = 'df -t reiserfs' finalList = [] theOutput = [] text = "This realy should be in HTML" html = "\ \ \ \ Disk Utilization on Hedley:" out = cStringIO.StringIO() writer = MimeWriter.MimeWriter(out) txtin = cStringIO.StringIO(text) def createhtmlmail (html, text, subject): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") writer.addheader("From", "[EMAIL PROTECTED]") writer.addheader("To", "[EMAIL PROTECTED]") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() print msg return msg def makeNonBlocking(fd): fl = fcntl.fcntl(fd, fcntl.F_GETFL) try: fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY) except AttributeError: fcntl.fcntl(fd, fcntl.F_SETFL, fl | fcntl.FNDELAY) def getCommandOutput(command): theOutput = [] child = popen2.Popen3(command, 1) # capture stdout and stderr from command child.tochild.close() # don't need to talk to child outfile = child.fromchild outfd = outfile.fileno() errfile = child.childerr errfd = errfile.fileno() makeNonBlocking(outfd)# don't deadlock! makeNonBlocking(errfd) outdata = errdata = '' outeof = erreof = 0 while 1: ready = select.select([outfd,errfd],[],[]) # wait for input if outfd in ready[0]: outchunk = outfile.read() if outchunk == '': outeof = 1 outdata = outdata + outchunk if errfd in ready[0]: errchunk = errfile.read() if errchunk == '': erreof = 1 errdata = errdata + errchunk if outeof and erreof: break select.select([],[],[],.1) # give a little time for buffers to fill err = child.wait() if err != 0: raise RuntimeError, '%s failed w/ exit code %d\n%s' % (command, err, errdata) theOutput.append(outdata) theOutput.append(errdata) return theOutput #Run df and get the disk info output = os.popen(cmd) # match two or more spaces, the header line has a sngle # space between the 'Mouted on' field # We need to keep those together # The other spaces are the separation in the field headers # To get the output from df down to just the field headers # and the data, we need to match 2 or more spaces # -
Re: How do I get a slice of a string held in a tuple?
In article <[EMAIL PROTECTED]>, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]> > wrote: > > I have tuple which hold a string in tup[0]. I want to get a slice of > > that string. I thought I would do something like: > > tup[0][start:end] > > But this fails. > > No, it doesn't. > > >>> a = ('abcdefg','hijkl') > >>> a[0] > 'abcdefg' > >>> a[0][1:2] > 'b' > > > > How do I go about it? > > Do it correctly. Post your actual example that fails > and the related error message. Possibnly your indexes > were out of range. > > > I googled this and found a couple > > of references, but no solution. > > Well, there wouldn't be a solution to a non-existent > problem, would there? > > > TIA Here's the code: elapsedTime = mydata[1] index = elapsedTime.find("real") # the index will have a value 0f 110 totaltime = elapsedTime[index:] # instead of this returning a shortened html string, i only # get the left angle bracket '<' -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get a slice of a string held in a tuple?
In article <[EMAIL PROTECTED]>, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]> > wrote: > > I have tuple which hold a string in tup[0]. I want to get a slice of > > that string. I thought I would do something like: > > tup[0][start:end] > > But this fails. > > No, it doesn't. > > >>> a = ('abcdefg','hijkl') > >>> a[0] > 'abcdefg' > >>> a[0][1:2] > 'b' > > > > How do I go about it? > > Do it correctly. Post your actual example that fails > and the related error message. Possibnly your indexes > were out of range. > > > I googled this and found a couple > > of references, but no solution. > > Well, there wouldn't be a solution to a non-existent > problem, would there? > > > TIA How would you get a slice of a[0] from your example? 'cde' for example? -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get a slice of a string held in a tuple?
In article <[EMAIL PROTECTED]>, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > On Apr 8, 12:29�pm, Lorenzo <[EMAIL PROTECTED]> wrote: > > In article <[EMAIL PROTECTED]>, > > > > > > > > > > > > "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > > > On Apr 8, 11:34?am, Lorenzo Thurman <[EMAIL PROTECTED]> > > > wrote: > > > > I have tuple which hold a string in tup[0]. I want to get a slice of > > > > that string. I thought I would do something like: > > > > tup[0][start:end] > > > > But this fails. > > > > > No, it doesn't. > > > > > >>> a = ('abcdefg','hijkl') > > > >>> a[0] > > > 'abcdefg' > > > >>> a[0][1:2] > > > 'b' > > > > > > How do I go about it? > > > > > Do it correctly. Post your actual example that fails > > > and the related error message. Possibnly your indexes > > > were out of range. > > > > > > I googled this and found a couple > > > > of references, but no solution. > > > > > Well, there wouldn't be a solution to a non-existent > > > problem, would there? > > > > > > TIA > > > > Here's the code: > > > > elapsedTime = mydata[1] > > index = elapsedTime.find("real") > > # the index will have a value 0f 110 > > totaltime = elapsedTime[index:] > > # instead of this returning a shortened html string, i only > > # get the left angle bracket '<' > > This implies that '<' is the 111th character (counting > from 0) and that it is the last character since you used > [index:]. > > Print out the entire string elapsedTime, count from > 0 to the characters you want and see if you have the > correct index numbers (verify them). > > > > > > -- > > "My Break-Dancing days are over, but there's always the Funky Chicken" > > --The Full Monty Oops! I sent the wrong piece of code. The above is actually the work around which actually works. The bad code is this: index = mydata[0].find("real") elapsedTime = mydata[0][index:] My apologies, but this is what fails. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I get a slice of a string held in a tuple?
In article <[EMAIL PROTECTED]>, Georg Brandl <[EMAIL PROTECTED]> wrote: > Lorenzo schrieb: > > >> > How do I go about it? > >> > >> Do it correctly. Post your actual example that fails > >> and the related error message. Possibnly your indexes > >> were out of range. > >> > >> > I googled this and found a couple > >> > of references, but no solution. > >> > >> Well, there wouldn't be a solution to a non-existent > >> problem, would there? > >> > >> > TIA > > > > Here's the code: > > > > elapsedTime = mydata[1] > > index = elapsedTime.find("real") > > # the index will have a value 0f 110 > > totaltime = elapsedTime[index:] > > # instead of this returning a shortened html string, i only > > # get the left angle bracket '<' > > May it be that mydata[1] doesn't contain "real" at all? In that case, > find() returns -1, and the slice elapsedTime[-1:] always contains > at most one character. > > If you replace "find" by "index", you get a ValueError exception if > "real" was not found, if that helps you. > > Whenever one calls str.find(), one has to check the return value for -1. > > Georg Oops! I sent the wrong piece of code. The above is actually the work around which actually works. The bad code is this: index = mydata[0].find("real") elapsedTime = mydata[0][index:] My apologies, but this is what fails. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
Unfortunately I have to use Apache. The server implementation will we very easy, so I'm also considering more efficient solutions than python lv On Feb 6, 11:36 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > > It's not too difficult to configure everything, but I would like to > > tune it in order to receive up to 2000 calls per minute without any > > problems. Do Pthon CGIs use threading? > > I need to make it very efficient, but I haven't found much information > > about Python CGI optimization. > > The called function will update a table in a mysql db. I will use > > triggers to export data from the table updated by the xmlrpc server to > > other tables used by the backend application. > > You might consider using the twisted application server framework instead, > and totally ditch the CGI, and even the apache. > > http://twistedmatrix.com/ > > http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
Unfortunately I have to use Apache. The server implementation will be very easy, so I'm also considering more efficient solutions than python lv On Feb 6, 11:36 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > > It's not too difficult to configure everything, but I would like to > > tune it in order to receive up to 2000 calls per minute without any > > problems. Do Pthon CGIs use threading? > > I need to make it very efficient, but I haven't found much information > > about Python CGI optimization. > > The called function will update a table in a mysql db. I will use > > triggers to export data from the table updated by the xmlrpc server to > > other tables used by the backend application. > > You might consider using the twisted application server framework instead, > and totally ditch the CGI, and even the apache. > > http://twistedmatrix.com/ > > http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Aggregate funuctions broken in MySQLdb?
I'm trying to use some of the agg functions in MySQLdb (avg, min, max), but they're just not working as I would expect. They all return the value 1 when executed as part of Python scripts, but work as expected when used in mysql 4.1. Does anyone have any experience using Python with MySQLdb? Quite frankly, the more I use it, the more MySQLdb seems to be not quite ready for prime time. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty -- http://mail.python.org/mailman/listinfo/python-list
Re: Aggregate funuctions broken in MySQLdb?
In article <[EMAIL PROTECTED]>, John Salerno <[EMAIL PROTECTED]> wrote: > http://sourceforge.net/docman/?group_id=22307 Yes, I did, but I did not find them thorough enough. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty -- http://mail.python.org/mailman/listinfo/python-list
Re: Aggregate funuctions broken in MySQLdb?
In article <[EMAIL PROTECTED]>, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Mon, 15 May 2006 20:14:29 GMT, John Salerno > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > > Lorenzo Thurman wrote: > > > Thanks, that was my problem. Can you point me to some documentation on > > > MySQLdb? I've been googling to get answers and that obviously has not > > > been working. > > > > I've been looking into this too lately, and finding thorough docs for it > > is hard. Have you seen these yet: > > http://sourceforge.net/docman/?group_id=22307 > > For the most part, it follows the DB-API 2 specifications. The > subject of this thread (aggregates) would have occurred with ANY db-api > compliant adapter, even plain ODBC -- since it was a misunderstanding > that .execute() returns the status code (typically # of records > affected by the query), and .fetchnnn() is needed to obtain the data > values. This misunderstanding is not specific to use of aggregates as > any "select..." statement functions this way. > > Most divergences from the db-api specifications should be > determinable by looking at the sources of the python portion of the > adapter; or by looking at the features of the underlying RDBM. Thanks, you are correct. I have done similar database things using PHP and Perl to connect to databases, and I felt like DUH, when I got my first reply, but there are times when one cannot see the forest for the trees, so to speak. Better docs can help. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty -- http://mail.python.org/mailman/listinfo/python-list
Re: This application has failed to start because the application configuration is incorrect
On 17 feb, 19:44, Mark Hammond wrote: > On 18/02/2009 5:49 AM, Sam Clark wrote: > > > I am receiving the message "Thisapplicationhasfailedtostartbecause > > theapplicationconfiguration is incorrect" when I attempt to run a > > compiled Python program on another machine. I have used py2exe on both a > > 2.6.1 and a 2.6.0 version of the .py and .pyw files. Everything works > > great on the machine where Python 2.6 is loaded, but fails on machines > > where I copy the .exe to the machine. I'm a beginner at python > > programming. In fact this is my first packaged program. Any thoughts at > > a beginners level would be helpful. > > This will be due to the C runtime library not being installed correctly > on the target machine. I had the same issue. After looking some "patch" solutions of putting manually some dlls on the dist folder, I realized that you can fix it by installing one of these packages, see which one fits your system: x86 http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en x64 http://www.microsoft.com/downloads/details.aspx?familyid=BA9257CA-337F-4B40-8C14-157CFDFFEE4E&displaylang=en PS: Mark, this could be added to a kind of "Deployment" entry in py2exe wiki, it would be useful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Inverse of dict(zip(x,y))
Having a look at python documentation I found: zip() in conjunction with the * operator can be used to unzip a list: >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> zipped [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zipped) >>> x == x2, y == y2 True So, >>> x2, y2 = zip(*d.items()) should fix your problem -- http://mail.python.org/mailman/listinfo/python-list
Re: can python import class or module directly from a zip package
On Mar 10, 2:13 pm, Flank wrote: > can python import class or module directly from a zip package ,just > like jave does from jar package without extracting the class file into > directory > > so far as i know ,python module should be unzip to file system in > order to use them, After a little digging/googling, the answer came right from the docs: http://docs.python.org/library/zipimport.html I think that this module is just right what you need. Cheers! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to add months to a date (datetime object)?
On Mar 15, 1:28 pm, tinn...@isbd.co.uk wrote: > I have a date in the form of a datetime object and I want to add (for > example) three months to it. At the moment I can't see any very > obvious way of doing this. I need something like:- > > myDate = datetime.date.today() > inc = datetime.timedelta(months=3) > myDate += inc > > but, of course, timedelta doesn't know about months. I had a look at > the calendar object but that didn't seem to help much. > > -- > Chris Green After seeing all this discussion, the best suggestion that comes to my mind is: Implement your own logic, and handle special cases as desired, using calendar.monthrange as a reference to determine if the day really exists on the new month. i.e. from datetime import datetime import calendar months_to_add = 3 d = datetime.now() if d.months + months_to_add > 12: d.replace(year = d.year + (d.months + months_to_add)/12) d.replace(month = (d.months + months_to_add)%12) else: d.replace(month = (d.months + months_to_add)) if d.day > calendar.monthrange(d.year,d.month)[1]: # do some custom stuff i.e. force to last day of the month or skip to the next month just my .02 -- http://mail.python.org/mailman/listinfo/python-list
Re: Stripping non-numbers from a file parse without nested lists?
Maybe you can try a regex, something like -- import re pattern = re.compile('^(\d+)/(\d+).*') def read_data(filename): fh = open(filename, "r", encoding="ascii") for line in fh: if pattern.match(line): dip_,dir_ = pattern.match(line).groups() dip.append(dip_) dir.append(dir_) - -- http://mail.python.org/mailman/listinfo/python-list
http client encoding
Hi everybody, I wrote a small http client I'm using to download and analyze some web pages.I used urllib and the examples on the doc to create the http client, but I have some problems with the encoding of the returned data. Where can I find a good example about how to manage encoding for http responses???? Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: Python homework
Hi, On 05/12/17 06:33, nick martinez2 via Python-list wrote: I have a question on my homework. My homework is to write a program in which the computer simulates the rolling of a die 50 times and then prints (i). the most frequent side of the die (ii). the average die value of all rolls. For this kind of problem I think the collections module [1] can be very useful. In this case in particular have a look at the Counter package ;) Lorenzo. [1] https://docs.python.org/3.6/library/collections.html I wrote the program so it says the most frequent number out of all the rolls for example (12,4,6,14,10,4) and will print out "14" instead of 4 like I need. This is what I have so far: import random def rollDie(number): rolls = [0] * 6 for i in range(0, number): roll=int(random.randint(1,6)) rolls[roll - 1] += 1 return rolls if __name__ == "__main__": result = rollDie(50) print (result) print(max(result)) -- https://mail.python.org/mailman/listinfo/python-list
Answers to homework questions [WAS]: Re: Python homework
Hi Roger, On 13/12/17 23:31, ROGER GRAYDON CHRISTMAN wrote: On Wed, Dec 13, 2017, Lorenzo Sutton wrote: On 05/12/17 06:33, nick martinez2 via Python-list wrote: I have a question on my homework. [...] For this kind of problem I think the collections module [1] can be very useful. In this case in particular have a look at the Counter package ;) [...] A nice answer at face value, and for general questions, but perhaps not the best given the subject line and the first sentence in the OP's note. > [...] When I teach my course, I have no desire to have all my students turn into cargo cultists. At least this particular student did post his intended solution, instead of outright begging for code. And most of the responses I see did attempt to work within the perceived constraints regarding what language tools the student was expected to use. I see your point as a teacher, but after all this *is* a Python mailing list and not a python-homework-support mailing list. Plus, the OP had already received various good answers specifically helping them solve the problem along the lines of his proposed code, so I guessed hinting to a standard library module which is interesting and potentially relevant in this case might be useful to both the OP and other people on the ML while enriching the discussion ;-) Best, Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: Are the critiques in "All the things I hate about Python" valid?
On Saturday, February 17, 2018 at 12:28:29 PM UTC+1, Ben Bacarisse wrote: > Marko Rauhamaa writes: > > > Many people think static typing is key to high quality. I tend to think > > the reverse is true: the boilerplate of static typing hampers > > expressivity so much that, on the net, quality suffers. > > I don't find that with Haskell. It's statically typed but the types are > almost always inferred. If you see an explicit type, it's usually > because the author thinks it helps explain something. > > (I don't want to start a Haskell/Python thread -- the only point is that > static typing does not inevitably imply lots of 'boilerplate'.) > > -- > Ben. There are two sides to not declaring types: having readers spend a fraction of a second to figure out what types are being used and having tools apply type inference for useful purposes. Python is bad at type inference (but only because deliberate loopholes like eval() are preserved) but good at making programmers trust code, while Haskell is bad at encouraging straightforward and understandable types but good at extracting maximum value from type inference. -- https://mail.python.org/mailman/listinfo/python-list
VisPy 0.12 released
Hi all, On behalf of the vispy contributors, I'm happy to announce vispy v0.12! Here are the main highlights: - Better attenuated_mip shader for Volume visuals, which scales automatically based on contrast limits - Instanced rendering in gloo, with some examples showcasing how to use it - Allow setting array to `symbol` in `MarkersVisual` Several bugs were also fixed, and documentation was updated. For a complete changelog, see https://github.com/vispy/vispy/releases/tag/v0.12.0 What is VisPy? -- VisPy is a Python library for interactive scientific visualization that is designed to be fast, scalable, and easy to use. VisPy leverages the computational power of modern Graphics Processing Units (GPUs) through the OpenGL library to display very large datasets. Applications of VisPy include: High-quality interactive scientific plots with millions of points. Direct visualization of real-time data. Fast interactive visualization of 3D models (meshes, volume rendering). OpenGL visualization demos. Scientific GUIs with fast, scalable visualization widgets (Qt or Jupyter Notebook via jupyter_rfb). See the Gallery and many other example scripts on the VisPy website ( http://vispy.org/). Upgrading - VisPy supports Python 3.x on Linux, Mac OSX, and Windows. VisPy's heavy use of the GPU means that users will need to have modern and up-to-date video drivers for their system. VisPy can use one of many backends, see the documentation for details. We strive to keep backwards compatibility with older versions of VisPy, but interfaces are still being designed to best serve our users. As such, some things may have changed that break your existing usage. See the Release Notes (linked below) for more information on what has changed and contact the VisPy developers for help with any problems you run into. Links - GitHub: https://github.com/vispy/vispy Website: http://vispy.org/ Gitter (for chat): https://gitter.im/vispy/vispy Mailing list: https://groups.google.com/forum/#!forum/vispy Release Notes: https://github.com/vispy/vispy/blob/main/CHANGELOG.md Contributing Help is always welcome. See our Contributor's Guide for information on how you can participate: https://vispy.org/dev_guide/contributor_guide.html Thanks, Lorenzo -- https://mail.python.org/mailman/listinfo/python-list
Question regarding unexpected behavior in using __enter__ method
Dear Python Mailing List members, I am writing to seek your assistance in understanding an unexpected behavior that I encountered while using the __enter__ method. I have provided a code snippet below to illustrate the problem: ``` >>> class X: ... __enter__ = int ... __exit__ = lambda *_: None ... >>> with X() as x: ... pass ... >>> x 0 ``` As you can see, the __enter__ method does not throw any exceptions and returns the output of "int()" correctly. However, one would normally expect the input parameter "self" to be passed to the function. On the other hand, when I implemented a custom function in place of the __enter__ method, I encountered the following TypeError: ``` >>> def myint(*a, **kw): ... return int(*a, **kw) ... >>> class X: ... __enter__ = myint ... __exit__ = lambda *_: None ... >>> with X() as x: ... pass ... Traceback (most recent call last): File "", line 1, in File "", line 2, in myint TypeError: int() argument must be a string, a bytes-like object or a real number, not 'X' ``` Here, the TypeError occurred because "self" was passed as an input parameter to "myint". Can someone explain why this unexpected behavior occurs only in the latter case? I tested this issue on the following Python versions, and the problem persists on all of them: - Python 3.8.10 (default, Nov 14 2022, 12:59:47) [GCC 9.4.0] on linux - Python 3.10.10 (main, Feb 8 2023, 14:50:01) [GCC 9.4.0] on linux - Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32 I appreciate any input or insights that you might have on this matter. Thank you for your help in advance! Best regards, Lorenzo Catoni -- https://mail.python.org/mailman/listinfo/python-list
Re: Question regarding unexpected behavior in using __enter__ method
Thankyou for your answer, i think i found the reason for this behavior, is has to do with the function being user defined or not, rather than being a plain function or type, as stated here https://docs.python.org/3/reference/datamodel.html#:~:text=Also%20notice%20that%20this%20transformation%20only%20happens%20for%20user%2Ddefined%20functions%3B%20other%20callable%20objects%20(and%20all%20non%2Dcallable%20objects)%20are%20retrieved%20without%20transformation Regards, Lorenzo Catoni On Fri, 21 Apr 2023 at 07:21, Cameron Simpson wrote: > On 21Apr2023 00:44, Lorenzo Catoni wrote: > >I am writing to seek your assistance in understanding an unexpected > >behavior that I encountered while using the __enter__ method. I have > >provided a code snippet below to illustrate the problem: > > > >``` > >>>> class X: > >... __enter__ = int > >... __exit__ = lambda *_: None > >... > >>>> with X() as x: > >... pass > >... > >>>> x > >0 > >``` > >As you can see, the __enter__ method does not throw any exceptions and > >returns the output of "int()" correctly. However, one would normally > expect > >the input parameter "self" to be passed to the function. > > My descriptor fu is weak, but I believe this is because `int` is not a > plain function but a type. > > Consider this class definition: > > class X: > x = 1 > def y(self): > return "y" > > When you define a class, the body of the class is run in a namespace, > and on completion, the namespace is _used_ to construct the class. > During that process, the various names are considered. Here we've got 2 > names: "x" and "y". > > "x" refers to an int and is just stored as a class attribute, unchanged. > > "y" refers to a function, and is promoted to a descriptor of an unbound > method. > > So later: X.x return 1 but X.y returns a unbound method. If we make an > instance: > > objx = X() > > then obj.x returns 1 (by not fining an "x" on "obj", but finding one on > "type(obj)" i.e. the class attribute. > > By contrast, obj.y returns a bound method, a function already curried > with a leading parameter "obj" (which will be "self"). There's no "y" > attribute directly on "obj" but there's an unbound method on > "type(obj).y", which gets bound by saying "obj.y". > > The means that what happens to a name when you define the class depends > on the typeof the value bound to the name. > > A plain function gets turned into an unbound instance method, but other > things are left alone. > > When you went: > > __enter__ = int > > That's not a plain function and so "obj.__enter__" doesn't turn into a > bound method - it it just `int`. > > Cheers, > Cameron Simpson > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: How to reduce the DRY violation in this code
On 27/09/2016 17:49, Steve D'Aprano wrote: I have a class that takes a bunch of optional arguments. They're all optional, with default values of various types. For simplicity, let's say some are ints and some are floats: class Spam: def __init__(self, bashful=10.0, doc=20.0, dopey=30.0, grumpy=40, happy=50, sleepy=60, sneezy=70): # the usual assign arguments to attributes dance... self.bashful = bashful self.doc = doc # etc. I also have an alternative constructor that will be called with string arguments. May I ask: do you really need to add this method? Can't you ensure that the data passed during initialisation is already of the right type (i.e. can you convert to float/ints externally)? If now why? Lorenzo. It converts the strings to the appropriate type, then calls the real constructor, which calls __init__. Again, I want the arguments to be optional, which means providing default values: @classmethod def from_strings(cls, bashful='10.0', doc='20.0', dopey='30.0', grumpy='40', happy='50', sleepy='60', sneezy='70'): bashful = float(bashful) doc = float(doc) dopey = float(dopey) grumpy = int(grumpy) happy = int(happy) sleepy = int(sleepy) sneezy = int(sneezy) return cls(bashful, doc, dopey, grumpy, happy, sleepy, sneezy) That's a pretty ugly DRY violation. Imagine that I change the default value for bashful from 10.0 to (let's say) 99. I have to touch the code in three places (to say nothing of unit tests): - modify the default value in __init__ - modify the stringified default value in from_strings - change the conversion function from float to int in from_strings Not to mention that each parameter is named seven times. How can I improve this code to reduce the number of times I have to repeat myself? -- https://mail.python.org/mailman/listinfo/python-list
Re: The irony
On 10/05/2016 20:03, DFS wrote: "There should be one-- and preferably only one --obvious way to do it." https://www.python.org/dev/peps/pep-0020/ "Explicit is better than implicit." What is your use case and scenario? :-) Maybe it's better to write a function to automatise this so that if instead of "line 1\n ..." you want "banana 1~banana 2~ " etc. you can simply change parameters? That said join and list comprehensions would also come to mind, but not sure how "obvious" that is... Lorenzo. --- sSQL = "line 1\n" sSQL += "line 2\n" sSQL += "line 3" --- sSQL = ("line 1\n" "line 2\n" "line 3") --- sSQL = "\n".join([ "line 1", "line 2", "line 3", ]) --- sSQL = """line 1 line 2 line 3""" --- sSQL = """\ line 1 line 2 line 3""" --- sSQL = "line 1\n" \ "line 2\n" \ "line 3" --- Which is the "one obvious way" to do it? I liked: sSQL = "line 1\n" sSQL += "line 2\n" sSQL += "line 3" but it's frowned upon in PEP8. -- https://mail.python.org/mailman/listinfo/python-list
Re: python parsing suggestion
Hi, On 30/05/2016 09:34, Ganesh Pal wrote: Hi , Trying to extract the '1,1,114688:8192' pattern form the below output. pdb>stdout: '3aae5d0-1: Parent Block for 1,1,19169280:8192 (block 1,1,114688:8192) --\n3aae5d0-1: magic 0xdeaff2fe mark_cookie 0x\ngpal-3aae5d0-1: super.status 3super.cookie 390781895\ngpal-3aae5d0-1: cg_xth 0 What parts of the string (i any) can we assume to always be the same? 1. Is parsing with stdout.strip().split('\n')[0].split()[6][:-1] sufficient do I need to add extra check ? it looks fine for me though. 2. Better ways to achieve the same output we need to parse is a string 3. Is re.search(r'(\d+),(\d+),(\d+):(\d+)', parent_block) needed ? I added as an extra check ,any ideas on the same Regards, Ganesh -- https://mail.python.org/mailman/listinfo/python-list
Re: Which one is the best XML-parser?
On Thursday, June 23, 2016 at 11:03:18 PM UTC+2, David Shi wrote: > Which one is the best XML-parser? > Can any one tell me? > Regards. > David Lxml offers lxml.etree.iterparse (http://lxml.de/tutorial.html#event-driven-parsing), an important combination of the memory savings of incremental parsing and the convenience of visiting a DOM tree without dealing with irrelevant details. An iterable incrementally produces DOM element objects, which can be deleted after processing them and before proceeding to parse the rest of the document. This technique allows easy processing of huge documents containing many medium-size units of work whose DOM trees fit into memory easily. -- https://mail.python.org/mailman/listinfo/python-list
Re: Getting back into PyQt and not loving it.
PyGTK is obsolete and stopped at Python 2.7, while PyGObject for Windows is several versions behind (currently 3.18 vs 3.21) and it doesn't support Python 3.5. Game over for GTK+. -- https://mail.python.org/mailman/listinfo/python-list
Re: Type hinting of Python is just a toy ?
On Friday, January 4, 2019 at 9:05:11 AM UTC+1, iam...@icloud.com wrote: > I read that pep 484 type hinting of python has no effect of performance, then > what’s the purpose of it? Just a toy ? Having no effect on performance is a good thing; Python is already slowish, additional runtime type checking would be a problem. The purpose of type hinting is helping tools, for example ones that look for type errors in source code (e.g. a function parameter is supposed to be a string, but an integer is being passed). > > Python is an old programming language, but not better than other programming > languages, then what are you all dong for so many times ? Being nice in general, and not too aggressive with trolls in particular, is also a good thing. > > Pep484 is too complex. Typle should not a seperate type, in fact it should be > just a class. Like this in other programming language > Python: Tuple(id: int, name: string, age: int) > Other: class someClass { > public int id; > public string name; > public int age; > } But tuple (not Tuple) is already is a class. Are you missing the difference between declaring a type and invoking a constructor? Try to work out complete examples. > Design of OOP of python is too bad, so it treat Tuple as a seperate type. If you mean that defining classes could be replaced by uniformly using tuples, it is not the case because classes can have a lot of significant behaviour, including encapsulation. If you mean that the specific tuple class shouldn't exist and all classes should be in some way like tuple, it is not the case because many classes have to behave differently and above that tuple has special syntax support. It's about as special as the dict class and the list class, and clearly different. > Why looks different than others? afraid of cannot been watched by others? Like most programming languages, Python was deliberately designed to be different from existing programming languages in order to make an experiment (which could be summarized as interpreted, with a lot of convenient syntax in order to be brief and readable, strictly object oriented, strongly but dynamically typed) and to gain adoption (by offering an advantage to users who wouldn't bother trying a language that is only marginally different from existing ones). By all means, use other programming languages if you think they are better, but don't expect Python to change in radical ways. -- https://mail.python.org/mailman/listinfo/python-list
Re: wxPython clipboard
[EMAIL PROTECTED] wrote: Ok well you should look at this module http://www.rutherfurd.net/python/sendkeys/#id1 I then you could take frequent snapshots and use and OCR to find your stuff. Then use the above library to type to the window. Ok the problem on Windows looks like solved but still I would have to check if Windows Scripting Host is enabled. Anyway I'll keep u updated Cheers Lorenzo -- Get my PGP Public Key @ http://www.bolognini.net/LBolognini.txt -- http://mail.python.org/mailman/listinfo/python-list
Web form validators for Python (RequiredFieldValidator anyone?)
Hi all, just trying to do some web development with Python. At the moment I'm keeping an eye on these projects: Nevow, JotWeb, Albatross, Snakeskin and my favorite, CherryPy, soon coming with a version 2! But, even though there's something I like in all of these frameworks, I can't find in the Python world anything similar to the .NET RequiredFieldValidator class (which I believe is the only thing I really like about .NET http://www.w3schools.com/aspnet/control_reqfieldvalidator.asp) even without the client side capabilities which I wouldn't rely upon anyway. Can you point me to some code/class/module that implements what I'm looking for? Thanks a lot, Lorenzo -- Get my PGP Public Key @ http://www.bolognini.net/LBolognini.txt -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python appropriate for web applications?
Unknown User wrote: I have the choice. Thanks for your opinion, If you have a look at CherryPy (www.cherrypy.org) you will not want to go back to PHP again! ;-) Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: Tk alternative to askopenfilename and askdirectory?
On 16/12/2015 14:18, Ulli Horlacher wrote: Is there an alternative to Tk's askopenfilename() and askdirectory()? I want to select a files and directories within one widget, but askopenfilename() let me only select files and askdirectory() let me only select directories. I guess it would help if you could provide some information on your use case and what you want to achieve ;) Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Reduce memory fragmentation with MALLOC_MMAP_THRESHOLD_ and MALLOC_MMAP_MAX_
Hi all, I've been experimenting with MALLOC_MMAP_THRESHOLD_ and MALLOC_MMAP_MAX_ env variables to affect memory management in a long-running Python 2 process. See http://man7.org/linux/man-pages/man3/mallopt.3.html I got the idea from this bug report: http://bugs.python.org/issue11849 The results I have are encouraging: memory fragmentation is reduced and the typical high-water mark visible in memory used by long-running processes is lower. My only concern is if there are other side effects that may bite back, when using such low level tweaks. Does anyone have any experience in using them? Here is an example script that shows how those variables affect RSS memory in a script that generate a large dictionary: https://gist.github.com/lbolla/8e2640133032b0a6bb9c Just run "alloc.sh" and compare the output. Thanks, L. -- https://mail.python.org/mailman/listinfo/python-list
Re: New user's initial thoughts / criticisms of Python
Regarding the "select" statement, I think the most "Pythonic" approach is using dictionaries rather than nested ifs. Supposing we want to decode abbreviated day names ("mon") to full names ("Monday"): day_abbr='mon' day_names_mapping={ 'mon':'Monday', 'tue':'Tuesday', 'wed':'Wednesday', 'thu':'Thursday', 'fri':'Friday', 'sat':'Saturday', 'sun':'Sunday' } try: full_day_name=day_names_mapping[day_abbr.casefold()] except KeyError: raise GoodLuckFixingItException('We don't have "'+day_abbr+'" in our week') This style is more compact (usually one line per case) and more meaningful (generic processing driven by separate data) than a pile of if statement, and more flexible: full_day_names=('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday') day_names={x.casefold()[0:3] : x for x in full_day_names} # A dict can also contain tuples, lists, and nested dicts, consolidating multiple switches over the same keys and organizing nested switches and other more complex control structures. -- https://mail.python.org/mailman/listinfo/python-list
Re: anomaly
On Monday, May 11, 2015 at 2:58:09 AM UTC+2, zipher wrote: > I guess everyone expects this behavior since Python implemented this idea of > "everything is an object", but I think this branch of OOP (on the branch of > the Tree of Programming Languages) has to be chopped off. The idea of > everything is an object is backwards (unless your in a LISP machine). Like I > say, it's trying to be too pure and not practical. Expressing this sort of emphatic, insulting and superficial opinions, to the people who would be most irritated by them (the Python mailing list) and without the slightest interest for contrary viewpoints and constructive discussion, is a very unpleasant form of trolling. If you don't like Python, you are welcome to prefer other programming languages. If you want to use Python with C-like primitive types, you can use arrays. Both choices are perfectly good, and routinely made without bothering other people with inane conversations. Lorenzo Gatti -- https://mail.python.org/mailman/listinfo/python-list
Re: global and loop control variable
On 23/07/2015 12:24, candide wrote: [...] Now, global declaration has another restriction, as PLR explains: [https://docs.python.org/3.4/reference/simple_stmts.html#the-global-statement] ~ Names listed in a global statement must not be defined as formal parameters or in a for loop control target, ~ What I understand is that the following is a must-not-code: # --- def f(): global i for i in range(1,3): print(10*i) f() print(i) # --- But, the later code executes silently without any warning: ~ 10 20 2 ~ So my question is: what is the restriction about global as loop control variable the docs is referring to? I think for situations like this one? # --- def f(): global temperature for temperature in range(1,3): print "In f temperature is:", temperature temperature = 500 print "temperature is now", temperature f() print"temperature is now:", temperature # temperature is now "broken" if temperature <= 100: print "Launching rocket" else: # this never happens print "temperature too high! Aborting launch." # --- -- https://mail.python.org/mailman/listinfo/python-list
Re: global and loop control variable
On 23/07/2015 14:31, Steven D'Aprano wrote: On Thu, 23 Jul 2015 09:20 pm, Lorenzo Sutton wrote: On 23/07/2015 12:24, candide wrote: Now, global declaration has another restriction, as PLR explains: [https://docs.python.org/3.4/reference/simple_stmts.html#the-global-statement] ~ Names listed in a global statement must not be defined as formal parameters or in a for loop control target, ~ What I understand is that the following is a must-not-code: def f(): global i for i in range(1,3): print(10*i) [...] So my question is: what is the restriction about global as loop control variable the docs is referring to? You are correct. The above example is exactly the restriction mentions. The very next paragraph in the docs says: "CPython implementation detail: The current implementation does not enforce the two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program." In other words, the behaviour of global loop variables is not guaranteed, and you should not use it even if the compiler/interpreter fails to raise a syntax error. I think for situations like this one? def f(): global temperature for temperature in range(1,3): print "In f temperature is:", temperature There's no meaningful difference between the example Candide gave (for i in range) and the example you give (for temperature in range). They both use a global for the loop variable. Only the names differ. Of course... it was just to highlight that it could be potentially, especially if your programme is going to launch a rocket - eventually (see my entire code example) :-) Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: XML Binding
Hi, On 03/09/2015 21:54, Burak Arslan wrote: Hello, On 09/03/15 19:54, Palpandi wrote: Hi All, Is there any module available in python standard library for XML binding? If not, any other suggestions. lxml is the right xml library to use. You can use lxml's objectify or Spyne. I second lxml.. [...] Which is good for parsing large file? How large is large? I have used lxml (coupled with pygtk) with very good results on XML files up to around 250Mb. Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: Pyarmor, guard your python scripts
On 18/09/2015 13:41, Jondy Zhao wrote: [...] In reality, when we leave the house, we lock the door, even the lock could not make sure the safe of our property. It's just make it difficult. It's same in the software world. Someone need the lock in both of the world. I think you meant "in the *proprietary* software world". This discussion on the topic, and in particular this answer, on Stackoverflow are quite inspiring: http://stackoverflow.com/questions/261638/how-do-i-protect-python-code/261727#261727 Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Python 3 windows installer problem [WAS: Re: an installing problem]
Hi, Not too familiar with the 'new' Python 3 installer on windows.. but On 23/09/2015 13:37, Narges Asadi wrote: Hello I’ve encountered a problem when I wanted to install Python 3.5. I sent you the log file. Please help me to fix the problem. From the log: [0F4C:1110][2015-09-23T14:54:17]e000: Error 0x80072ee7: Failed to send request to URL: https://www.python.org/ftp/python/3.5.0/win32/core_pdb.msi, trying to process HTTP status code anyway. which seems to be reachable now... so maybe a network problem when you were installing?? Look here about installing without downloading, it might be helpful. https://docs.python.org/3/using/windows.html#installing-without-downloading This bug report might also be relevant: https://bugs.python.org/issue25126 Hope this helps. Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python, convert an integer into an index?
On 23/09/2015 17:32, Denis McMahon wrote: On Tue, 22 Sep 2015 14:43:55 -0700, Chris Roberts wrote: results = 134523 #(Integer) This appears to be an integer expressed (presumably) in base 10 with 6 digits Desired: results = [1, 2, 3, 4, 5, 2, 3] #(INDEX) This appears to be a python list of 7 elements, with the first and the the third through seventh elements corresponding to the first and the second through sixth most significant digits respectively of the previously discussed integer. I can't actually see any direct method of creating the list given from the number given. However, if I understand the intent of the question you meant to ask, you might find that the following code does something interesting: x = 9876543210 y = [] while x > 0: y.append(x % 10) x = int(x / 10) y = list(reversed(y)) print y I like the math approach even if the pythonic list string is quicker... One 'math' way would also be (avoiding the list reverse, but need to import math): >>> import math >>> result = 1234567 >>> digits = int(math.log10(result) + 1) >>> y = [] >>> for x in range(digits, 0, -1): number = result % (10 ** x) / (10 **(x-1)) y.append(int(number)) >>> y [1, 2, 3, 4, 5, 6, 7] -- https://mail.python.org/mailman/listinfo/python-list
Re: Detection of a specific sound
On 26/10/15 01:17, Montana Burr wrote: I'm looking for a library that will allow Python to listen for the shriek of a smoke alarm. Once it detects this shriek, it is to notify someone. Ideally, specificity can be adjusted for the user's environment. For example, I expect to need moderate specificity as I live in a quiet neighborhood, but an apartment dweller might need more. I'm thinking of recording a smoke alarm and having the program try to find the recorded sound in the stream from the microphone. Any help is greatly appreciated! It would really be helpful if you could explain the (hardware) setting in more detail. When you say "Python to listen" I assume you mean a microphone connected to a computer where your python programme will be running. How many smoke allarms and in what radius should be detected? Or is it only a specific one? This could range from a simple programme triggered by an amplitude change (e.g. a piezo attached to the single alarm in question) to a complex audio fingerprinting one... Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about math.pi is mutable
On 06/11/2015 13:30, Bartc wrote: On 06/11/2015 02:33, wa...@travelsky.com wrote: Hello, python-list guys: I am a newbie of python from Beijing. China. I have a question about "math.pi". As you can see in the attachment, why i can modify "math.pi"? (in "mathmodule.c" "pi" is a "static const double") Python isn't C. Your attachment isn't visible, but it can be demonstrated easily: import math math.pi=0 print (math.pi) In Python, presumably 'pi' is just another variable, and variables can be written to. (Perhaps math.pi would be better off as a function.) Still nothing stops you from doing: math.sin = 0 If you really want to? -- https://mail.python.org/mailman/listinfo/python-list
unicode html
X-No-Archive: yes Hi, I've found lots of material on the net about unicode html conversions, but still i'm having many problems converting unicode characters to html entities. Is there any available function to solve this issue? As an example I would like to do this kind of conversion: \uc3B4 => ô for all available html entities. thanks, lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Execution timeout
X-No-Archive: yes Hi, I'm using feedparser to parse some xml feeds. As others reported (http://sourceforge.net/tracker/index.php?func=detail&aid=1519461&group_id=112328&atid=661937 ) the library halts while parsing some feeds. To overcome this issue I was thinking about creating some kind of wrapper for feedparser that encapsulates a timeout. So after launching the parse method wait a few seconds and if the control does not return mark the feed as bad. I haven't much experience with Python so I'm not able to code it, any hint? Is there a better method to avoid this kind of problem? Thanks, Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: NEWBIE: Script help needed
Thanks for the reply, but I know there is something wrong with the command, I'm just not sure how to troubleshoot it. Anyway, I can execute all of the commands from the command line, but only 3 fails when run from within the script. I'll take a look at the link. Nick Vatamaniuc wrote: > If the other commands work but 3) doesn't, it means there is something > different (wrong?) with the command. > > So try running 3) , then one of the other ones and see the difference. > > > The getCommandOutput() , I suspect, just waits for the data from the > actual command and the command is not returning anything. It could be > because it just takes way too long (I am not familiar with Gentoo, so > not sure if emerge world takes 1 second or 24 hours...) or perhaps the > "emerge -uvp world" stops at some point and is waiting for input (a > command prompt like "are you sure you want to do this [Y/n]?" > > For more in depth on subprocesses in Python take a look at the > subprocess module: > http://docs.python.org/lib/module-subprocess.html > > Hope this helps, > Nick V. > > > > Lorenzo wrote: >> I have this script that I want to use weekly to send me email with >> information regarding disk space and available upgrades for my system. >> This script is actually a learning tool for me as I learn Python. The >> problem I've run into has me stumped and I need some help. What happens >> is when the script runs it does these things, parses the result and >> appends that to an html string: >> >> 1) checks disk space by using df -t reiserfs >> 2) runs time emerge --sync >> 3) runs emerge -uvp world >> 4) runs emerge -uv --fetchonly world >> >> The 'emerge' command is a Gentoo specific one. If I remove step 3), >> everything else runs just fine, the email is sent and I receive what I >> expect. But when step 3) is allowed to run, even if its the only command >> that runs, it hangs somewhere in the function getCommandOutput. If I try >> and debug the command, it appears to hang on this line: >> err = child.wait() >> >> I suspect a race condition, but I'm not sure how to proceed, can someone >> lend me a hand. Here is the script I wrote, I got the command >> getCommandOutput from this site: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52296 >> TIA >> >> [code] >> #!/usr/bin/python >> >> >> ### NEED TO RUN THIS AS ROOT ### >> ### EMERGE SYNC REQUIRES THIS ### >> >> import os, re, smtplib, MimeWriter, mimetools, cStringIO, popen2, fcntl, >> select, pdb >> >> cmd = 'df -t reiserfs' >> finalList = [] >> theOutput = [] >> >> text = "This realy should be in HTML" >> >> >> html = "\ >> \ >> > charset=iso-8859-1\">\ >> \ >> Disk Utilization on >> Hedley:" >> >> out = cStringIO.StringIO() >> writer = MimeWriter.MimeWriter(out) >> txtin = cStringIO.StringIO(text) >> >> >> def createhtmlmail (html, text, subject): >> """Create a mime-message that will render HTML in popular >> MUAs, text in better ones""" >>import MimeWriter >>import mimetools >>import cStringIO >> >>out = cStringIO.StringIO() # output buffer for our message >>htmlin = cStringIO.StringIO(html) >>txtin = cStringIO.StringIO(text) >> >>writer = MimeWriter.MimeWriter(out) >># >># set up some basic headers... we put subject here >># because smtplib.sendmail expects it to be in the >># message body >># >>writer.addheader("Subject", subject) >>writer.addheader("MIME-Version", "1.0") >> >>writer.addheader("From", "[EMAIL PROTECTED]") >> writer.addheader("To", "[EMAIL PROTECTED]") >># >># start the multipart section of the message >># multipart/alternative seems to work better >># on some MUAs than multipart/mixed >># >>writer.startmultipartbody("alternative") >>writer.flushheaders() >># >># the plain text section >># >>subpart = writer.nextpart() >>subpart.addheader("Content-Transfer-Encoding", "quoted-printable") >>pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) >>mimetools.encode(t
Python on MIPS
Hi everybody, I bought a very small embedded card, with a MIPS processor, running Linux. So, I would to use Python on that; I checked on python.org, but I did'nt find any release for this architecture. Could you help me? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on MIPS
Thomas Krüger ha scritto: > Lorenzo Mainardi schrieb: >> I bought a very small embedded card, with a MIPS processor, running >> Linux. So, I would to use Python on that; I checked on python.org, but I >> did'nt find any release for this architecture. Could you help me? > > How about compiling it from source? > > Thomas I did'nt try...I will do that :-) -- http://mail.python.org/mailman/listinfo/python-list
Mail not setting timestamp
I'm using the Mimewriter and mimetools modules to create html messages. They work OK, except that when the messages are received, they always have the timestamp of 12/31/1969. I've looked through both packages and can't find anything that would allow me to manually set it. Can someone help me out? TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: Mail not setting timestamp
Gabriel Genellina wrote: > Lorenzo Thurman wrote: > >> I'm using the Mimewriter and mimetools modules to create html messages. >> They work OK, except that when the messages are received, they always >> have the timestamp of 12/31/1969. I've looked through both packages and >> can't find anything that would allow me to manually set it. Can someone >> help me out? > > The date goes into the message headers, like From, To, Subject... > message.add_header("Date", "Thu, 22 Jun 2006 23:18:15 -0300") > > -- > Gabriel Genellina > Thanks for the reply. When I try this though, I get an error: Traceback (most recent call last): File "./synctest.py", line 202, in ? message = createhtmlmail(html, text, subject) File "./synctest.py", line 49, in createhtmlmail writer.addheader("Date", theDate) File "/usr/lib/python2.4/MimeWriter.py", line 100, in addheader lines = value.split("\n") AttributeError: 'datetime.datetime' object has no attribute 'split' I'm trying to use a variable for the date, since of course, it should always be 'now'. someDate = datetime.datetime.now() writer.addheader("Date", someDate) Hard coding a date, like your example, works just fine. Any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: Mail not setting timestamp
Gabriel Genellina wrote: > Lorenzo Thurman wrote: >> Gabriel Genellina wrote: >>> Lorenzo Thurman wrote: >>> >>>> I'm using the Mimewriter and mimetools modules to create html messages. >>>> They work OK, except that when the messages are received, they always >>>> have the timestamp of 12/31/1969. I've looked through both packages and >>>> >>> The date goes into the message headers, like From, To, Subject... >>> message.add_header("Date", "Thu, 22 Jun 2006 23:18:15 -0300") >>> >> Thanks for the reply. When I try this though, I get an error: >> AttributeError: 'datetime.datetime' object has no attribute 'split' >> I'm trying to use a variable for the date, since of course, it should >> always be 'now'. > > You have to convert the date into a string, using the right format. > The docs for the time module have a recipe: > http://www.python.org/doc/current/lib/module-time.html > (look for RFC 2822) > > -- > Gabriel Genellina > Got it! thx -- http://mail.python.org/mailman/listinfo/python-list
How do I get a slice of a string held in a tuple?
I have tuple which hold a string in tup[0]. I want to get a slice of that string. I thought I would do something like: tup[0][start:end] But this fails. How do I go about it? I googled this and found a couple of references, but no solution. TIA -- http://mail.python.org/mailman/listinfo/python-list
can Python be useful as functional?
Hi all, I haven't experienced functional programming very much, but now I'm trying to learn Haskell and I've learned that: 1) in functional programming LISTS are fundmental; 2) any "cycle" in FP become recursion. I also know that Python got some useful tool such as map, filter, reduce... so I told: "let's try some FP-style programming with Python!". I took a little example of Haskell: listprimes :: Integer -> [Integer] listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)] where sieve [] = [] sieve (p:xs) = p : sieve (filter (\x -> mod x p > 0) xs) and I tried to "translate" it in Python: def sieve(s): if s == []: return [] else: return [s[0]] + sieve(filter((lambda x: x % s[0] > 0), s[1:])) def listprimes(n): return sieve(range(2,n)) These should be almost the same: listprimes actually lists prime integers up to n-1. The result is: Haskell implementation works well, maybe it's not the better way to do it, but it does what I wanted. Python implementation gives me RuntimeError: maximum recursion depth exceeded in cmp My question is: how can we call a language "functional" if it's major implementation has a limited stack? Or is my code wrong? LS -- http://mail.python.org/mailman/listinfo/python-list
Re: can Python be useful as functional?
On 18 Set, 18:51, Grant Edwards <[EMAIL PROTECTED]> wrote: > Perhaps Lorenzo Stella is referring to Python's lack of > tail-recursion optimization? There are languages that > guarantee unlimited tail-recursion with a limited stack. That's it. Rustom Mody: your implementation lacks exactly where mine does. Try listing the first 2000 primes... That's what I meant: I cannot in general (with Python) get such list just by defining *what* it is, I have to express *how* to get it (describing an algorithm). "What" or "How": that is the question. Steve Holden wrote: > You just don't like the specific limit that Python imposes. So increase > it with sys.setrecursionlimit(). That is obviously not the answer to my question. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ping Implementation in Python
Nel mezzo del cammin di nostra vita, mi ritrovai con Mrown che diceva: > Hi, > I was wondering if there was a ping implementation written in > Python. I'd rather using a Python module that implements ping in a > platform/OS-independent way than rely on the underlying OS, especially > as every OS has a different implementation. Furthermore, if you're > going to ping a large number of IPs, using a module would probably be a > lot faster. Any ideas if such a module exists? Thanks. Get Scapy, it's one of the best tool for this kind of problem, and it's Python based -- "Le opinioni dei fanatici prescindono dai fatti" python -c "print 'bG9ybWF5bmFAZ21haWwuY29t'.decode('base64')" -- http://mail.python.org/mailman/listinfo/python-list
SSL client authentication
Hi everybody, I'm developing a distributed application in Python and I intend to use SOAP over a SSL connection. I looked at the SOAPpy package and it seems to have all I need but client authentication; in other words I want my client certificate be sent to the server during the SSL handshake. SOPApy.SOPAServer has ssl_context to use the private key and certificate of the server but the client side SOAPProxy doesn't seem to take such context. I was wondering if this is due to httplib.HTTPS (used by SOAPProxy) not performing any certificate verification, according to the httplib.py sources. Any hints? -- http://mail.python.org/mailman/listinfo/python-list
NEWBIE: Tokenize command output
This is what I have so far: // #!/usr/bin/python import os cmd = 'ntpq -p' output = os.popen(cmd).read() // The output is saved in the variable 'output'. What I need to do next is select the line from that output that starts with the '*' remote refid st t when poll reach delay offset jitter = = +ntp-1.gw.uiuc.e 128.174.38.133 2 u 479 1024 377 33.835 -0.478 3.654 +milo.mcs.anl.go 130.126.24.443 u 676 1024 377 70.1431.893 1.296 *caesar.cs.wisc. 128.105.201.11 2 u 635 1024 377 29.514 -0.231 0.077 >From there, I need to tokenize the line using the spaces as delimiters. Can someone give me some pointers? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Aggregate funuctions broken in MySQLdb?
Thanks, that was my problem. Can you point me to some documentation on MySQLdb? I've been googling to get answers and that obviously has not been working. In article <[EMAIL PROTECTED]>, "Wade Leftwich" <[EMAIL PROTECTED]> wrote: > Works fine for me, and I certainly hope MySQLdb is ready for prime > time, because I use the heck out of it. Maybe you're getting fooled by > the fact that cursor.execute() returns the count of result rows. To > actually see the result rows, you have to say cursor.fetchone() or > fetchall() -- > > In [34]: cur.execute("select article_id from articles limit 10") > Out[34]: 10L > > In [35]: cur.fetchall() > Out[35]: ((3L,), (4L,), (5L,), (6L,), (7L,), (8L,), (9L,), (10L,), > (11L,), (12L,)) > > In [36]: cur.execute("select count(article_id) from articles where > article_id < 13") > Out[36]: 1L > > In [37]: cur.fetchall() > Out[37]: ((10L,),) > > In [38]: cur.execute("select sum(article_id) from articles where > article_id < 13") > Out[38]: 1L > > In [39]: cur.fetchone() > Out[39]: (75.0,) > > In [40]: cur.execute("select avg(article_id) from articles where > article_id < 13") > Out[40]: 1L > > In [41]: cur.fetchone() > Out[41]: (7.5,) -- http://mail.python.org/mailman/listinfo/python-list
Re: Howto on callbacks, queues and good design patterns
Nel mezzo del cammin di nostra vita, mi ritrovai con Michael Bernhard Arp Sørensen che diceva: > Hi there. > > As a newbie, I need to learn about callbacks and queues(syntax and > examples) working together. > > At work we talk a lot about design patterns. Does any of you know a good > site about that or any good books from Amazon? > Hello, I think the best way to understanding queues and callbacks is to learn Twisted. That's a very big framework for asynchronous network programming; it's completely callback based. For more info you should visit the Twisted Matrix website: http:// twistedmatrix.com/trac/ There also a good documentation, but it's a few embedded, so you need to looking for that with care:-) Good 2008 and have fun! -- "Le opinioni dei fanatici prescindono dai fatti" python -c "print 'bG9ybWF5bmFAZ21haWwuY29t'.decode('base64')" -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner's assignment question
On Mar 1, 3:39 pm, Schizoid Man <[EMAIL PROTECTED]> wrote: > As in variable assignment, not homework assignment! :) > > I understand the first line but not the second of the following code: > > a, b = 0, 1 > a, b = b, a + b > > In the first line a is assigned 0 and b is assigned 1 simultaneously. > > However what is the sequence of operation in the second statement? I;m > confused due to the inter-dependence of the variables. The expressions of the right of the assignment operator are evaluated before assigning any new values, to the destinations on the left side of the assignment operator. So substitutig the old values of a and b the second assignment means a, b = 0, 0 + 1 Simplifying the Python Reference Manual ("6.3 Assignment Statements") a little : assignment_stmt ::= target_list "="+ expression_list An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. [...] WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are `safe' (for example "a, b = b, a" swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints "[0, 2]": x = [0, 1] i = 0 i, x[i] = 1, 2 print x Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: syntax color lang source code in blogs or website
Xah Lee wrote: For those of you using emacs, here's the elisp code that allows you to syntax color computer language source code in your blog or website. http://xahlee.org/emacs/elisp_htmlize.html may I suggest also this one: http://www.gnu.org/software/src-highlite/ -- Lorenzo Bettini, PhD in Computer Science, DI, Univ. Torino ICQ# lbetto, 16080134 (GNU/Linux User # 158233) HOME: http://www.lorenzobettini.it MUSIC: http://www.purplesucker.com http://www.myspace.com/supertrouperabba BLOGS: http://tronprog.blogspot.com http://longlivemusic.blogspot.com http://www.gnu.org/software/src-highlite http://www.gnu.org/software/gengetopt http://www.gnu.org/software/gengen http://doublecpp.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: type-checking support in Python?
On 7 Ott, 08:36, Lawrence D'Oliveiro <[EMAIL PROTECTED] central.gen.new_zealand> wrote: > In message <[EMAIL PROTECTED]>, Gabriel > > Genellina wrote: > > As an example, in the oil industry here in my country there is a mix of > > measurement units in common usage. Depth is measured in meters, but pump > > stroke in inches; loads in lbs but pressures in kg/cm². > > Isn't the right way to handle that to attach dimensions to each number? Can you afford to avoid floats and ints? Attaching suffixes is the best one can do with the builtin types. In C++ one can check dimensions at compile time (http://www.boost.org/ doc/libs/1_36_0/doc/html/boost_units.html) with a modest increase of cumbersomeness, but Python would need very heavyweight classes containing a value and its dimension and a replacement of all needed functions and operations. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On 31 Mar, 09:19, jfager wrote: > On Mar 31, 2:54 am, David Stanek wrote: > > > On Mon, Mar 30, 2009 at 9:40 AM, jfager wrote: > > >http://jasonfager.com/?p=440. > > > > The basic idea is that a language could offer syntactic support for > > > declaring configurable points in the program. The language system > > > would then offer an api to allow the end user to discover a programs > > > configuration service, as well as a general api for providing > > > configuration values. A configuration "service"? An "end user" that bothers to discover it? API for "providing" configuration "values"? This suggestion, and the companion blog post, seem very distant from the real world for a number of reasons. 1) Users want to supply applications with the least amount of useful configuration information as rarely and easily as possible, not to use advanced tools to satisfy an application's crudely expressed configuration demands. Reducing inconvenience for the user entails sophisticated and mostly ad hoc techniques: deciding without asking (e.g. autoconf looking into C compiler headers and trying shell commands or countless applications with "user profiles" querying the OS for the current user's home directory), asking when the software is installed (e.g. what 8 bit character encoding should be used in a new database), designing sensible and safe defaults. 2) Practical complex configuration files (or their equivalent in a DB, a LDAP directory, etc.) are more important and more permanent than the applications that use them; their syntax and semantics should be defined by external specifications (such as manuals and examples), not in the code of a particular implementation. User documentation is necessary, and having a configuration mechanism that isn't subject to accidents when the application is modified is equally important. 3) Configuration consisting of values associated with individual variables is an unusually simple case. The normal case is translating between nontrivial sequential, hierarchical or reticular data structures in the configuration input and quite different ones in the implementation. 4) Your actual use case seems to be providing a lot of tests with a replacement for the "real" configuration of the actual application. Branding variables as "configuration" all over the program isn't an useful way to help the tests and the actual application build the same data structures in different ways. > > What value does this have over simply having a configuration file. > > "Simply having a configuration file" - okay. What format? What if > the end user wants to keep their configuration info in LDAP? Wait a minute. Reading the "configuration" from a live LDAP directory is a major feature, with involved application specific aspects (e.g. error handling) and a solid justification in the application's requirements (e.g. ensuring up to date authentication and authorization data), not an interchangeable configuration provider and certainly not something that the user can replace. Deciding where the configuration comes from is an integral part of the design, not something that can or should be left to the user: there can be value in defining common object models for various sources of configuration data and rules to combine them, like e.g. in the Spring framework for Java, but it's only a starting point for the actual design of the application's configuration. > > In your load testing application you could have easily checked for the > > settings in a config object. > > Not really easily, no. It would have been repeated boilerplate across > many different test cases (actually, that's what we started with and > refactored away), instead of a simple declaration that delegated the > checking to the test runner. A test runner has no business configuring tests beyond calling generic setup and teardown methods; tests can be designed smartly and factored properly to take care of their own configuration without repeating "boilerplate". > > I think that the discover-ability of > > configuration can be handled with example configs and documentation. > > Who's keeping that up to date? Who's making sure it stays in sync > with the code? Why even bother, if you could get it automatically > from the code? It's the code that must remain in sync with the documentation, the tests, and the actual usage of the application. For example, when did you last see incompatible changes in Apache's httpd.conf? You seem to think code is central and actual use and design is a second class citizen. You say in your blog post: "Users shouldn’t have to pore through the code to find all the little bits they can tweak". They shouldn't because a well designed application has adequate documentation of what should be configured in the form of manuals, wizards, etc. and they shouldn't because they don't want to tweak little bits, not even if they have to. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
pythonCE GetSystemPowerState windows api
Hi all, I need to call GetSystemPowerState windows api from pythonCE, because I need to know if a windows ce 5 device is in sleep/off status. I can find this api in ctypes.windll.coredll, but I cannot figure out how to pass parameters to this procedure: msdn giude ( http://msdn.microsoft.com/en-us/library/ms899319.aspx ) speaks about 3 parameters, of wich 2 are output: a "LPWSTR pBuffer" and a "PDWORD pFlags". Returned value of the call is an exit status code rappresenting if call succeded or failed. I tried to call this api in several ways, but obtained always exit code 87 (meaning that parameters are wrong) or 122 (meaning "pBuffer" variable is too small, in this case I passed None as pBuffer, since I'm interested only in pFlags result). Have you any idea? Maybe another api or way to perform this simple task? Thank you all, Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonCE GetSystemPowerState windows api
On Apr 25, 6:19 pm, Thomas Heller wrote: > lorenzo.mentas...@yahoo.it schrieb: > > > > > Hi all, > > I need to call GetSystemPowerState windows api from pythonCE, because > > I need to know if a windows ce 5 device is in sleep/off status. > > I can find this api in ctypes.windll.coredll, but I cannot figure out > > how to pass parameters to this procedure: msdn giude ( > >http://msdn.microsoft.com/en-us/library/ms899319.aspx) speaks about 3 > > parameters, of wich 2 are output: a "LPWSTR pBuffer" and a "PDWORD > > pFlags". Returned value of the call is an exit status code > > rappresenting if call succeded or failed. > > > I tried to call this api in several ways, but obtained always exit > > code 87 (meaning that parameters are wrong) or 122 (meaning "pBuffer" > > variable is too small, in this case I passed None as pBuffer, since > > I'm interested only in pFlags result). > > > Have you any idea? Maybe another api or way to perform this simple > > task? > > Python 2.5 (release25-maint, Dec 19 2006, 23:22:00) [MSC v.1201 32 bit (ARM)] > on win32>>> from ctypes import * > >>> d=windll.coredll > >>> d.GetSystemPowerState > > <_FuncPtr object at 0x0016EC60> > > >>> p=create_unicode_buffer(256) > >>> flags=c_ulong() > >>> f=d.GetSystemPowerState > >>> f(p,256,byref(flags)) > 0 > >>> p.value > u'on' > >>> flags > c_ulong(268500992L) > >>> hex(flags.value) > '0x1001L' > > Thomas Thank you very much! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: 2d graphics - what module to use?
On 25 Lug, 08:13, Pierre Dagenais <[EMAIL PROTECTED]> wrote: > What is the easiest way to draw to a window? I'd like to draw something > like sine waves from a mathematical equation. > Newbie to python. What you are really asking for is what GUI library you should use; every one allows you to draw freely. What do you need to do besides drawing sine waves? You should look at your full range of options; http://wiki.python.org/moin/GuiProgramming is a good starting point. The "easiest" way to draw might be with those toolkits that offer primarily a canvas to draw on rather than composable widgets. For example, Pyglet (http://pyglet.org/) offers OpenGL contexts with sensible defaults and unobtrusive automation: from pyglet import * from pyglet.gl import * import math win = window.Window(width=700, height=700, caption="sine wave demo", resizable=True) frequency,phase,amplitude=0.1,0.0,0.9 @win.event def on_draw(): half_height=win.height*0.5 glClear(GL_COLOR_BUFFER_BIT) glColor3f(0.9, 1.0, 0.8) glBegin(GL_LINE_STRIP) for x in xrange(0,win.width): y=half_height*(1.0+amplitude*math.sin(x*frequency+phase)) glVertex2f(x,y) glEnd() app.run() Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
https and POST method
Hi all, I'm trying to write a simple script for sending sms via vyke... I have to make a https connection and pass some data with the POST method, like this perl script does: http://www.nutella.org/vyke.sms.txt I tried to make the same, but it simply doesn't work! Any request gives a 200 OK result... This is my code: datah = {"act": "menulogin", "username": login, "password": passwd, "menu_login_form": 1} datas = urllib.urlencode(datah) conn = httplib.HTTPSConnection("www.vyke.com") conn.connect() conn.request("POST", "/merchantsite/login.c?Distributor=MASKINA", datas) res = conn.getresponse() print "login", res.status, res.reason datah = {"act": "sendSMS", "from": numfrom, "to": numto, "message": msg, "sms_form": 1} datas = urllib.urlencode(datah) conn.request("POST", "/merchantsite/sms.c", datas) res = conn.getresponse() print "send", res.status, res.reason conn.request("GET", "/merchantsite/logout.c?Distributor=MASKINA") res = conn.getresponse() print "logout", res.status, res.reason conn.close() I don't know what to do! :-( -- http://mail.python.org/mailman/listinfo/python-list
Re: str(bytes) in Python 3.0
On Apr 12, 5:51 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: > On 12 Apr., 16:29, Carl Banks <[EMAIL PROTECTED]> wrote: > > > > And making an utf-8 encoding default is not possible without writing a > > > new function? > > > I believe the Zen in effect here is, "In the face of ambiguity, refuse > > the temptation to guess." How do you know if the bytes are utf-8 > > encoded? > > How many "encodings" would you define for a Rectangle constructor? > > Making things infinitely configurable is very nice and shows that the > programmer has worked hard. Sometimes however it suffices to provide a > mandatory default and some supplementary conversion methods. This > still won't exhaust all possible cases but provides a reasonable > coverage. There is no sensible default because many incompatible encodings are in common use; programmers need to take responsibility for tracking ot guessing string encodings according to their needs, in ways that depend on application architecture, characteristics of users and data, and various risk and quality trade-offs. In languages that, like Java, have a default encoding for convenience, documents are routinely mangled by sloppy programmers who think that they live in an ASCII or UTF-8 fairy land and that they don't need tight control of the encoding of all text that enters and leaves the system. Ceasing to support this obsolete attitude with lenient APIs is the only way forward; being forced to learn that encodings are important is better than, say, discovering unrecoverable data corruption in a working system. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-schema 'best practice' question
On 18 Set, 08:28, Frank Millman <[EMAIL PROTECTED]> wrote: > I am thinking of adding a check to see if a document has changed since > it was last validated, and if not, skip the validation step. However, > I then do not get the default values filled in. > > I can think of two possible solutions. I just wondered if this is a > common design issue when it comes to xml and schemas, and if there is > a 'best practice' to handle it. > > 1. Don't use default values - create the document with all values > filled in. > > 2. Use python to check for missing values and fill in the defaults > when processing the document. > > Or maybe the best practice is to *always* validate a document before > processing it. The stated problem rings a lot of premature optimization bells; performing the validation and default-filling step every time, unconditionally, is certainly the least crooked approach. In case you really want to avoid unnecessary schema processing, if you are willing to use persistent data to check for changes (for example, by comparing a hash or the full text of the current document with the one from the last time you performed validation) you can also store the filled-in document that you computed, either as XML or as serialized Python data structures. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-schema 'best practice' question
On 20 Set, 07:59, Frank Millman <[EMAIL PROTECTED]> wrote: > I want to introduce an element of workflow management (aka Business > Process Management) into the business/accounting system I am > developing. I used google to try to find out what the current state of > the art is. After several months of very confusing research, this is > the present situation, as best as I can figure it out. What is the state of the art of existing, working software? Can you leverage it instead of starting from scratch? For example, the existing functionality of your accounting software can be reorganized as a suite of components, web services etc. that can be embedded in workflow definitions, and/or executing a workflow engine can become a command in your application. > There is an OMG spec called BPMN, for Business Process Modeling > Notation. It provides a graphical notation [snip] > there is no standard way > of exchanging a diagram between different vendors, or of using it as > input to a workflow engine. So BPMN is mere theory. This "spec" might be a reference for evaluating actual systems, but not a standard itself. > There is an OASIS spec called WS-BPEL, for Web Services Business > Process Execution Language. It defines a language for specifying > business process behavior based on Web Services. This does have a > formal xml-based specification. However, it only covers processes > invoked via web services - it does not cover workflow-type processes > within an organisation. To try to fill this gap, a few vendors got > together and submitted a draft specification called BPEL4People. This > proposes a series of extensions to the WS-BPEL spec. It is still at > the evaluation stage. Some customers pay good money for buzzword compliance, but are you sure you want to be so bleeding edge that you care not only for WS- something specifications, but for "evaluation stage" ones? There is no need to wait for BPEL4People before designing workflow systems with human editing, approval, etc. Try looking into case studies of how BPEL is actually used in practice. > The BPMN spec includes a section which attempts to provide a mapping > between BPMN and BPEL, but the authors state that there are areas of > incompatibility, so it is not a perfect mapping. Don't worry, BPMN does not exist: there is no incompatibility. On the other hand, comparing and understanding BPMN and BPEL might reveal different purposes and weaknesses between the two systems and help you distinguish what you need, what would be cool and what is only a bad idea or a speculation. > Eventually I would like to make sense of all this, but for now I want > to focus on BPMN, and ignore BPEL. I can use wxPython to design a BPMN > diagram, but I have to invent my own method of serialising it so that > I can use it to drive the business process. For good or ill, I decided > to use xml, as it seems to offer the best chance of keeping up with > the various specifications as they evolve. If you mean to use workflow architectures to add value to your business and accounting software, your priority should be executing workflows, not editing workflow diagrams (which are a useful but unnecessary user interface layer over the actual workflow engine); making your diagrams and definitions compliant with volatile and unproven specifications should come a distant last. > I don't know if this is of any interest to anyone, but it was > therapeutic for me to try to organise my thoughts and get them down on > paper. I am not expecting any comments, but if anyone has any thoughts > to toss in, I will read them with interest. 1) There are a number of open-source or affordable workflow engines, mostly BPEL-compliant and written in Java; they should be more useful than reinventing the wheel. 2) With a good XML editor you can produce the workflow definitions, BPEL or otherwise, that your workflow engine needs, and leave the interactive diagram editor for a phase 2 that might not necessarily come; text editing might be convenient enough for your users, and for graphical output something simpler than an editor (e.g a Graphviz exporter) might be enough. 3) Maybe workflow processing can grow inside your existing accounting application without the sort of "big bang" redesign you seem to be planning; chances are that the needed objects are already in place and you only need to make workflow more explicit and add appropriate new features. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-schema 'best practice' question
Sorry for pressing the send button too fast. On 20 Set, 07:59, Frank Millman <[EMAIL PROTECTED]> wrote: > I want to introduce an element of workflow management (aka Business > Process Management) into the business/accounting system I am > developing. I used google to try to find out what the current state of > the art is. After several months of very confusing research, this is > the present situation, as best as I can figure it out. What is the state of the art of existing, working software? Can you leverage it instead of starting from scratch? For example, the existing functionality of your accounting software can be reorganized as a suite of components, web services etc. that can be embedded in workflow definitions, and/or executing a workflow engine can become a command in your application. > There is an OMG spec called BPMN, for Business Process Modeling > Notation. It provides a graphical notation [snip] > there is no standard way > of exchanging a diagram between different vendors, or of using it as > input to a workflow engine. So BPMN is mere theory. This "spec" might be a reference for evaluating actual systems, but not a standard itself. > There is an OASIS spec called WS-BPEL, for Web Services Business > Process Execution Language. It defines a language for specifying > business process behavior based on Web Services. This does have a > formal xml-based specification. However, it only covers processes > invoked via web services - it does not cover workflow-type processes > within an organisation. To try to fill this gap, a few vendors got > together and submitted a draft specification called BPEL4People. This > proposes a series of extensions to the WS-BPEL spec. It is still at > the evaluation stage. Some customers pay good money for buzzword compliance, but are you sure you want to be so bleeding edge that you care not only for WS- something specifications, but for "evaluation stage" ones? There is no need to wait for BPEL4People before designing workflow systems with human editing, approval, etc. Try looking into case studies of how BPEL is actually used in practice. > The BPMN spec includes a section which attempts to provide a mapping > between BPMN and BPEL, but the authors state that there are areas of > incompatibility, so it is not a perfect mapping. Don't worry, BPMN does not exist: there is no incompatibility. On the other hand, comparing and understanding BPMN and BPEL might reveal different purposes and weaknesses between the two systems and help you distinguish what you need, what would be cool and what is only a bad idea or a speculation. > Eventually I would like to make sense of all this, but for now I want > to focus on BPMN, and ignore BPEL. I can use wxPython to design a BPMN > diagram, but I have to invent my own method of serialising it so that > I can use it to drive the business process. For good or ill, I decided > to use xml, as it seems to offer the best chance of keeping up with > the various specifications as they evolve. If you mean to use workflow architectures to add value to your business and accounting software, your priority should be executing workflows, not editing workflow diagrams (which are a useful but unnecessary user interface layer over the actual workflow engine); making your diagrams and definitions compliant with volatile and unproven specifications should come a distant last. > I don't know if this is of any interest to anyone, but it was > therapeutic for me to try to organise my thoughts and get them down on > paper. I am not expecting any comments, but if anyone has any thoughts > to toss in, I will read them with interest. 1) There are a number of open-source or affordable workflow engines, mostly BPEL-compliant and written in Java; they should be more useful than reinventing the wheel. 2) With a good XML editor you can produce the workflow definitions, BPEL or otherwise, that your workflow engine needs, and leave the interactive diagram editor for a phase 2 that might not necessarily come; text editing might be convenient enough for your users, and for graphical output something simpler than an editor (e.g a Graphviz exporter) might be enough. 3) Maybe workflow processing can grow inside your existing accounting application without the sort of "big bang" redesign you seem to be planning; chances are that the needed objects are already in place and you only need to make workflow more explicit and add appropriate new features. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
LAST CALL FOR PAPERS: TOOLS EUROPE 2010
== LAST CALL FOR PAPERS (Deadline: January 22, 2010) TOOLS EUROPE 2010 48th International Conference Objects, Models, Components, Patterns Co-located with *** International Conference on Model Transformation (ICMT 2010) *** *** International Conference on Software Composition (SC 2010) *** *** International Conference on Tests and Proofs (TAP 2010) *** Málaga - Spain, 28 June - 02 July 2010 http://malaga2010.lcc.uma.es/ == TOOLS EUROPE is devoted to the combination of technologies that have emerged as a result of object technology becoming "mainstream". Like its predecessors, TOOLS EUROPE combines an emphasis on quality with a strong practical focus. Started in 1989, TOOLS conferences, held in Europe, the USA, Australia, China and Eastern Europe, have played a major role in the development of object technology; many of seminal concepts were first presented at TOOLS. After an interruption of four years, the conference was revived in 2007 to reflect the maturing of the field and the new challenges ahead and has become a yearly event. Contributions are solicited on all aspects of object technology and related fields, in particular model-based development, component-based development, and patterns (design, analysis and other applications); more generally, any contribution addressing topics in advanced software technology fall within the scope of TOOLS. Reflecting the practical emphasis of TOOLS, contributions showcasing applications along with a sound conceptual contribution are particularly welcome. Topics include: * Object technology, including programming techniques, languages, tools * Testing of object-oriented systems * Patterns, pattern languages, tool support for patterns * Distributed and concurrent object systems * Real-time object-oriented programming and design * Experience reports, including efforts at standardisation * Applications to safety- and security-related software * Component-based programming, modelling, tools * Aspects and aspect-oriented programming and modelling * Frameworks for component-based development * Trusted and reliable components * Model-driven development and Model-Driven Architecture * Domain specific languages and language design * Tools and frameworks for supporting model-driven development * Language implementation techniques, compilers, run-time systems * Practical applications of program verification and analysis * Open source solutions & Reproduction studies All contributions will be subject to a rigorous selection process by the international Program Committee, with a stress on originality, practicality and overall quality. The proceedings will be published in Springer LNBIP. For detailed submission information see the conference page. Important Dates: Papers submission deadline: January 22, 2010 Acceptance notification: March 24, 2010 Camera-ready final copy: April 5, 2010 Conference: June 28 -- July 02, 2010 Conference Chair: Bertrand Meyer, ETH Zürich and Eiffel Software Program Chair: Jan Vitek, Purdue University Publicity Chair: Osmar Santos, University of York Program Committee: Uwe Assman, University of Dresden, Germany Elisa Baniassad, Chinese University of Hong Kong, Hong Kong Alexandre Bergel, University of Chile, Chile Lorenzo Bettini, University of Torino, Italy Judith Bishop, Microsoft Research, USA William Cook, University of Texas Austin, USA Sophia Drossopolou, Imperial College London, UK Catherine Dubois, ENSIIE, France Stéphane Ducasse, INRIA Lille, France Manuel Fahndrich, Microsoft Research, USA Harald Gall, University of Zurich, Switzerland Benoit Garbinato, University of Lausanne, Switzerland Angelo Gargantini, University of Bergamo, Italy Jeff Gray, University of Alabama Birmingham, USA Kathryn Gray, University of Cambridge, UK Thomas Gschwind, IBM Research, Switzerland Matthias Hauswith, University of Lugano, Switzerland Nigel Horspool, University of Victoria, Canada Tomas Kalibera, Charles University, Czech Republic Gerti Kappel, Vienna University of Technology, Austria Doug Lea, State University of New York Oswego, USA Shane Markstrum, Brucknell University, USA Peter Müller, ETH Zurich, Switzerland Oscar Nierstrasz, University of Bern, Switzerland James Noble, Victoria University of Wellington, New Zealand Nate Nystrom, University of Texas Arlington, USA Manuel Oriol, University of York, UK Jonathan Ostroff, York University, Canada Richard Paige, University of York, UK Shaz Qadeer, Microsoft Research, USA Awais Rashid, Lancaster University, UK Vivek Sarkar, Rice University, USA Doug Schmidt, Vanderbilt University, USA Manuel Serrano, INRIA Sophia Antipolis, France Peter Thiemann, Universi
CALL FOR PAPERS: TOOLS EUROPE 2010
== CALL FOR PAPERS (Deadline: January 22, 2010) TOOLS EUROPE 2010 48th International Conference Objects, Models, Components, Patterns Co-located with *** International Conference on Model Transformation (ICMT 2010) *** *** International Conference on Software Composition (SC 2010) *** *** International Conference on Tests and Proofs (TAP 2010) *** Málaga - Spain, 28 June - 02 July 2010 http://malaga2010.lcc.uma.es/ == TOOLS EUROPE is devoted to the combination of technologies that have emerged as a result of object technology becoming "mainstream". Like its predecessors, TOOLS EUROPE combines an emphasis on quality with a strong practical focus. Started in 1989, TOOLS conferences, held in Europe, the USA, Australia, China and Eastern Europe, have played a major role in the development of object technology; many of seminal concepts were first presented at TOOLS. After an interruption of four years, the conference was revived in 2007 to reflect the maturing of the field and the new challenges ahead and has become a yearly event. Contributions are solicited on all aspects of object technology and related fields, in particular model-based development, component-based development, and patterns (design, analysis and other applications); more generally, any contribution addressing topics in advanced software technology fall within the scope of TOOLS. Reflecting the practical emphasis of TOOLS, contributions showcasing applications along with a sound conceptual contribution are particularly welcome. Topics include: * Object technology, including programming techniques, languages, tools * Testing of object-oriented systems * Patterns, pattern languages, tool support for patterns * Distributed and concurrent object systems * Real-time object-oriented programming and design * Experience reports, including efforts at standardisation * Applications to safety- and security-related software * Component-based programming, modelling, tools * Aspects and aspect-oriented programming and modelling * Frameworks for component-based development * Trusted and reliable components * Model-driven development and Model-Driven Architecture * Domain specific languages and language design * Tools and frameworks for supporting model-driven development * Language implementation techniques, compilers, run-time systems * Practical applications of program verification and analysis * Open source solutions & Reproduction studies All contributions will be subject to a rigorous selection process by the international Program Committee, with a stress on originality, practicality and overall quality. The proceedings will be published in Springer LNBIP. For detailed submission information see the conference page. Important Dates: Papers submission deadline: January 22, 2010 Acceptance notification: March 24, 2010 Camera-ready final copy: April 5, 2010 Conference: June 28 -- July 02, 2010 Conference Chair: Bertrand Meyer, ETH Zürich and Eiffel Software Program Chair: Jan Vitek, Purdue University Publicity Chair: Osmar Santos, University of York Program Committee: Uwe Assman, University of Dresden, Germany Elisa Baniassad, Chinese University of Hong Kong, Hong Kong Alexandre Bergel, University of Chile, Chile Lorenzo Bettini, University of Torino, Italy Judith Bishop, University of Pretoria, South Africa William Cook, University of Texas Austin, USA Sophia Drossopolou, Imperial College London, UK Catherine Dubois, ENSIIE, France Stéphane Ducasse, INRIA Lille, France Manuel Fahndrich, Microsoft Research, USA Harald Gall, University of Zurich, Switzerland Benoit Garbinato, University of Lausanne, Switzerland Angelo Gargantini, University of Bergamo, Italy Jeff Gray, University of Alabama Birmingham, USA Kathryn Gray, University of Cambridge, UK Thomas Gschwind, IBM Research, Switzerland Matthias Hauswith, University of Lugano, Switzerland Nigel Horspool, University of Victoria, Canada Tomas Kalibera, Charles University, Czech Republic Gerti Kappel, Vienna University of Technology, Austria Doug Lea, State University of New York Oswego, USA Shane Markstrum, Brucknell University, USA Peter Müller, ETH Zurich, Switzerland Oscar Nierstrasz, University of Bern, Switzerland James Noble, Victoria University of Wellington, New Zealand Nate Nystrom, University of Texas Arlington, USA Manuel Oriol, University of York, UK Jonathan Ostroff, York University, Canada Richard Paige, University of York, UK Shaz Qadeer, Microsoft Research, USA Awais Rashid, Lancaster University, UK Vivek Sarkar, Rice University, USA Doug Schmidt, Vanderbilt University, USA Manuel Serrano, INRIA Sophia Antipolis, France Peter Thiemann,
Re: Pyfora, a place for python
On Nov 1, 8:06 am, Saketh wrote: > Hi everyone, > > I am proud to announce the release of Pyfora (http://pyfora.org), an > online community of Python enthusiasts to supplement comp.lang.python > and #python. While the site is small right now, please feel free to > register and post any questions or tips you may have. I'll feel free to not even bookmark it. I'm sorry, but it is just a bad idea. Your forum cannot (and should not) compete either with Python's official newsgroup, IRC channel and mailing list or with popular, well- made and well-frequented general programming sites like stackoverflow.com. It would be the Internet equivalent of looking for a poker tournament in a desert valley instead of driving half an hour less and going to Las Vegas: there are no incentives to choose your forum, except perhaps for isolationists who value being a big fish in a small pond over being part of a community. If you want to claim a small Python-related corner of the web, you should write a blog: if it is any good, and probably even if it isn't, it would be linked and read by someone and it would add to collective knowledge instead of fragmenting it. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
On Nov 3, 11:37 am, Steven D'Aprano wrote: > On Tue, 03 Nov 2009 02:11:59 -0800, Lorenzo Gatti wrote: [...] > Are you saying that now that comp.lang.python and stackoverflow exists, > there no more room in the world for any more Python forums? > > I think that's terrible. Although there is a high barrier to entry for general Python forums, it is not a problem because the door is always open for specialized forums that become the natural "home" of some group or thought leader or of some special interest, for example the forum of a new software product or of the fans of an important blog. Unfortunately, pyfora.org has neither a distinct crowd behind it nor an unique topic, and thus no niche to fill; it can only contribute fragmentation, which is unfortunate because Saketh seems enthusiastic. What in some fields (e.g. warez forums or art boards) would be healthy redundancy and competition between sites and forums becomes pure fragmentation if the only effect of multiple forums is to separate the same questions and opinions that would be posted elsewhere from potential readers and answerers. Reasonable people know this and post their requests for help and discussions either in the same appropriate places as everyone else or in random places they know and like; one needs serious personal issues to abandon popular forums for obscure ones. > Saketh, would you care to give a brief explanation for sets your forum > apart from the existing Python forums, and why people should choose to > spend time there instead of (or as well as) the existing forums? What > advantages does it have? That's the point, I couldn't put it better. > > It would be the Internet equivalent of looking for a poker tournament in > > a desert valley instead of driving half an hour less and going to Las > > Vegas: > > [...] > How about avoiding the noise and obtrusive advertising and bright lights > of Las Vegas, the fakery, the "showmanship", > [...] > if you're interested in poker without all the mayonnaise, maybe > that poker tournament away from the tourists is exactly what you need. I didn't explain my similitude clearly: I was comparing the fitness for purpose of going to Las Vegas with a plan to gamble with the absurdity of stopping, say, at an isolated gas station in the hope of finding a poker tournament there. If you are hinting that popular newsgroups and forums might be so full of fakery, showmanship, mayonnaise, etc. to deserve secession, it's another topic. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing GUI Module for Python
On Nov 9, 9:01 pm, Simon Hibbs wrote: > The main objection to using PyQT untill now was that for commercial > development you needed to buy a license (it was free for GPL > projects). That's rapidly becoming a non-issue as the core QT > framework is now LGPL and Nokia have a project underway to produce > PyQT compatible LGPL python bindings under the PySide project. I also would like to use PySide, but unlike PyQt and Qt itself it doesn't seem likely to support Windows in the foreseeable future. A pity, to put it mildly. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing GUI Module for Python
On Nov 10, 11:08 pm, Simon Hibbs wrote: > Since QT runs on Windows, > porting to the Windows version of QT shouldn't be hard. The PySide developers, who are better judges of their own project than you and me, consider a Windows port so hard (and time consuming) that they didn't even try; a second iteration of the already working binding generator has a higher priority than supporting a large portion of the potential user base with a Windows port, so don't hold your breath. On a more constructive note, I started to follow the instructions at http://www.pyside.org/docs/pyside/howto-build/index.html (which are vague and terse enough to be cross-platform) with Microsoft VC9 Express. Hurdle 0: recompile Qt because the provided DLLs have hardcoded wrong paths that confuse CMake. How should Qt be configured? My first compilation attempt had to be aborted (and couldn't be resumed) after about 2 hours: trial and error at 1-2 builds per day could take weeks. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing GUI Module for Python
On Nov 11, 9:48 am, Lorenzo Gatti wrote: > On a more constructive note, I started to follow the instructions > athttp://www.pyside.org/docs/pyside/howto-build/index.html(which are > vague and terse enough to be cross-platform) with Microsoft VC9 > Express. > Hurdle 0: recompile Qt because the provided DLLs have hardcoded wrong > paths that confuse CMake. > How should Qt be configured? My first compilation attempt had to be > aborted (and couldn't be resumed) after about 2 hours: trial and error > at 1-2 builds per day could take weeks. Update: I successfully compiled Qt (with WebKit disabled since it gives link errors), as far as I can tell, and I'm now facing apiextractor. Hurdle 1a: convince CMake that I actually have Boost headers and compiled libraries. The Boost directory structure is confusing (compiled libraries in two places), and CMake's script (FindBoost.cmake) is inconsistent (should I set BOOST_INCLUDEDIR or BOOST_INCLUDE_DIR?), obsolete (last known version is 1.38 rather than the requisite 1.40) and rather fishy (e.g. hardcoded "c:\boost" paths). Would the Cmake-based branch of Boost work better? Any trick or recipe to try? Hurdle 1b: the instructions don't mention a dependency from libxml2. Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: random number including 1 - i.e. [0,1]
On 10 Giu, 06:23, Esmail wrote: > Here is part of the specification of an algorithm I'm implementing that > shows the reason for my original query: > > vid = w * vid + c1 * rand( ) * ( pid – xid ) + c2 * Rand( ) * (pgd –xid ) (1a) > > xid = xid + vid (1b) > > where c1 and c2 are two positive constants, > rand() and Rand() are two random functions in the range [0,1], > ^ > and w is the inertia weight. 1) I second John Yeung's suggestion: use random integers between 0 and N-1 or N inclusive and divide by N to obtain a maximum value of (N-1)/ N or 1 as you prefer. Note that N doesn't need to be very large. 2) I'm not sure a pseudo-closed range is different from a pseudo-open one. You are perturbing vid and xid by random amounts, scaled by arbitrary coefficients c1 and c2: if you multiply or divide these coefficients by (N-1)/N the minimum and maximum results for the two choices can be made identical up to floating point mangling. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: Komodo(!)
Kee Nethery wrote: I've heard there is a nice add-on to Eclipse but Eclipse has even more setup variables than Wings and I've avoided it for that reason. Hi I've just started using python and since I've been an eclipse user for many years I tried http://pydev.sourceforge.net/ and I really enjoyed that! :-) cheers Lorenzo -- Lorenzo Bettini, PhD in Computer Science, DI, Univ. Torino ICQ# lbetto, 16080134 (GNU/Linux User # 158233) HOME: http://www.lorenzobettini.it MUSIC: http://www.purplesucker.com http://www.myspace.com/supertrouperabba BLOGS: http://tronprog.blogspot.com http://longlivemusic.blogspot.com http://www.gnu.org/software/src-highlite http://www.gnu.org/software/gengetopt http://www.gnu.org/software/gengen http://doublecpp.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Global variables in a C extension for Python
Hello, I've written a C extension for Python which works so far, but now I've stumbled onto a simple problem for which I just can't find any example on the web, so here I am crying for help ;-) I'll trying to reduce the problem to a minimal example. Let's say I need to call from Python functions of a C program like: static int counter = 0; void do_something(...) { ... counter++; ... } void do_something_else(...) { ... counter++; ... } So they access a common global variable. I've written the wrappers for the functions, but I'd like to place "counter" in the module's space and have wrappers accessing it like self->counter. I do not need to make "counter" visible to Python, I just need the global static variable available for C. I've got somehow a clue of how this should work, but not much more than a clue, and I'd appreciate to see a simple example. Best Regards, Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
"once" assigment in Python
Hello, I've been using Python for some DES simulations because we don't need full C speed and it's so much faster for writing models. During coding I find it handy to assign a variable *unless it has been already assigned*: I've found that this is often referred to as "once" assigment. The best I could come up with in Python is: try: variable except NameError: variable = method() I wonder if sombody has a solution (trick, whatever ...) which looks more compact in coding. Something like: once(variable, method) doesn't work, but it would be perfect. Of course I can preprocess the Python code but an all-Python solution would be more handy. Any suggestions? Thx in advance, Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: "once" assigment in Python
Thank you very much for your suggestions! I'll try in the next days to elaborate a bit on the last two ones. By the way, the "once" assignment is not that evil if you use it for hardware modeling. Most hardware models look like: wire1 = function() instance component(input=wire1,output=wire2) result = function(wire2) When employing Python it's pretty straightforward to translate the instance to an object. instance = Component(input=wire1,output=wire2) Then you don't use "instance" *almost* anymore: it's an object which gets registered with the simulator kernel and gets called by reference and event-driven only by the simulator kernel. We might reuse the name for calling some administrative methods related to the instance (e.g. for reporting) but that's a pretty safe thing to do. Of course all this can be done during initialization, but there are some good reasons (see Verilog vs VHDL) why it's handy do be able to do it *anywhere*. The annoying problem was that every time the program flow goes over the assignment, the object gets recreated. Indeed Python itself is not a hardware modeling language, but I built some infrastructure to fill what I was missing and for quickly building up a functional prototype and testing some ideas Python is really excellent. Best Regards, Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: "once" assigment in Python
On 17 Sep., 16:54, Larry Bates <[EMAIL PROTECTED]> wrote: > > IMHO variables like what you describe are really data not program variables. > You might consider putting variables like these in a dictionary and then check > to see if the keys exist before assignment: > > var_dict={} > > # > # See if 'varname' initialized, if not it needs to be > # > if 'varname' not in var_dict: > var_dict[varname]=somevalue This is a good point! I could write something like: instantiate('component',function) and have instantiate() to conditionally do: instance['component']=Module(function) Of course this means using: instance['component'].method() instead of just: component.method() A more annoying difficulty is with the fact that, while the scope of ordinary variables is limited (function, package), the scope of 'component' would be global (the whole instance[]): having global names could be pretty annoying in modeling a hierarchy. Anyway, some scoping mechanism could be implemented over the global dictionary and this could be a good price to pay to avoid other tricks. Further suggestions? Thank you! Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing user input?
On Thu, 2007-11-15 at 09:03 -0800, Mohammed_M wrote: > Hi, > I'm v.new to Python, so please don't be too harsh :) > I get a NameError with the code below - All I want to do is store some > input taken from the user in a variable called name, & then print name > > # START CODE == > # Print name demo > > > def PersonsDetails(): > name = input("What's your name?") > PersonsDetails() > > print(name) > > > # END CODE == > > Thanks for reading & any help on this You will need to return the input from the function. def PersonsDetails(): return raw_input("What is your name? ") name = PersonsDetails() print name Notice that in your code the variable name is created inside the function PersonsDetails(), so it is scoped to the function. This means that the variable is not accessible outside of PersonsDetails() and the attempt to print it with print(name) will fail. Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for a light weighted library/tool to write simple GUI above the text based application
[EMAIL PROTECTED] wrote: >>> is already solved). >> what you are looking for is curse :) >> http://docs.python.org/lib/module-curses.html >> http://www.ibm.com/developerworks/linux/library/l-python6.html >> >> renaud > > Renaud, thanks for your reply. > > I think I was not specific/clear enough in my first posting. I know > the curses library ( http://pyncurses.sourceforge.net ). It AFIK > provides TUI (short for: Text User Interface or Textual User > Interface). My needs are GUI, I mean "a nice VGA pictures" on the VGA > LCD 10" display. > > Petr What you need then is something like SVGAlib (http;//svgalib.org). Only really old people like myself know that it exists. I've never heard of any Python bindings for it, but that might be where you come in. I haven't looked at SVGAlib for years, and I'm not sure about the state of the video drivers. I suggest you look at that first. You could also look at GGI (http://ggi-project.org). GGI has different output targets. IIRC, one of them is directfb. To tell you the truth I've never really used GGI. There seems to be a python wrapper for GGI, although it is fairly old. Maybe you could look at the code for some ideas. You should also be able to compile SDL to be able to use directfb as a target. If your libSDL handles it, then that should apply to wrapper libraries as well, including pygame. I've never tried running SDL apps this way, but if it works well, that would probably be your 'best' option. Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
How to print zero-padded floating point numbers in python 2.6.1
Hello, I thought that I could zero-pad a floating point number in 'print' by inserting a zero after '%', but this does not work. I get: print '%2.2F' % 3.5 3.50 print '%02.2F' % 3.5 3.50 How can I get print (in a simple way) to print 03.50? Best Regards, Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Inheritance and forward references (prototypes)
Hi, I'm wondering what would be the preferred way to solve the following forward reference problem: --- class BaseA(object): def __init__(self): return class DebugA(BaseA): def __init__(self): return # here I would have a prototype of class A which is the same as class BaseA class B(object): def __init__(self): self.obj = A() return if __name__ == "__main__": #class A(BaseA): # Uncomment this for using BaseA objects # pass class A(DebugA): # Uncomment this for using DebugA objects pass --- I can figure out some ways to fix this but none seems satisfying. Either they are too specific or too cumbersome. A runtime redefinition of class A does not seem to work either. What would be the most "pythonesque" solution other than sorting out the class order? Best Regards, Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance and forward references (prototypes)
On Jun 20, 8:43 pm, Dave Angel wrote: > Lorenzo Di Gregorio wrote: > > Hi, > > > I'm wondering what would be the preferred way to solve the following > > forward reference problem: > > > --- > > class BaseA(object): > > def __init__(self): > > return > > > class DebugA(BaseA): > > def __init__(self): > > return > > > # here I would have a prototype of class A which is the same as class > > BaseA > > > class B(object): > > def __init__(self): > > self.obj = A() > > return > > > if __name__ == "__main__": > > # class A(BaseA): # Uncomment this for using BaseA objects > > # pass > > class A(DebugA): # Uncomment this for using DebugA objects > > pass > > --- > > > I can figure out some ways to fix this but none seems satisfying. > > Either they are too specific or too cumbersome. > > A runtime redefinition of class A does not seem to work either. > > What would be the most "pythonesque" solution other than sorting out > > the class order? > > > Best Regards, > > Lorenzo > > You haven't shown us any problem. class B works fine with a forward > reference to A. Now if you were trying to subclass A before defining > it, that'd be a problem. Or if you were trying to make an instance of B > before defining A. > > Better put some code together with enough meat to actually show a > symptom. And tell us what sys.version says. I'm testing with 2.6.2 > (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)], running > on Win XP.- Hide quoted text - > > - Show quoted text - Thank you for your help: I'm working on a rather large source, but I think I have isolated the problem now. This listing generates an error: --- class BaseA(object): def __init__(self): return class DebugA(BaseA): def __init__(self): return class B(object): def __init__(self,test=A()): self.obj = A() return if __name__ == "__main__": #class A(BaseA): # Uncomment this for using BaseA objects #pass class A(DebugA): # Uncomment this for using DebugA objects pass ------- The error happens because Python apparently evaluates the named arguments before running the script. I think I have read something about this some (long) time ago but I can't find it anymore. Suggestions? BTW, my Python version is 2.6.1 (with latest PyDev). Thx! Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance and forward references (prototypes)
On 21 Jun., 01:54, Dave Angel wrote: > LorenzoDiGregoriowrote: > > On Jun 20, 8:43 pm, Dave Angel wrote: > > >>LorenzoDiGregoriowrote: > > >>> Hi, > > >>> I'm wondering what would be the preferred way to solve the following > >>> forward reference problem: > > >>> --- > >>> class BaseA(object): > >>> def __init__(self): > >>> return > > >>> class DebugA(BaseA): > >>> def __init__(self): > >>> return > > >>> # here I would have a prototype of class A which is the same as class > >>> BaseA > > >>> class B(object): > >>> def __init__(self): > >>> self.obj =() > >>> return > > >>> if __name__ ="__main__": > >>> # class A(BaseA): # Uncomment this for using BaseA objects > >>> # pass > >>> class A(DebugA): # Uncomment this for using DebugA objects > >>> pass > >>> --- > > >>> I can figure out some ways to fix this but none seems satisfying. > >>> Either they are too specific or too cumbersome. > >>> A runtime redefinition of class A does not seem to work either. > >>> What would be the most "pythonesque" solution other than sorting out > >>> the class order? > > >>> Best Regards, > >>>Lorenzo > > >> You haven't shown us any problem. class B works fine with a forward > >> reference to A. Now if you were trying to subclass A before defining > >> it, that'd be a problem. Or if you were trying to make an instance of B > >> before defining A. > > >> Better put some code together with enough meat to actually show a > >> symptom. And tell us what sys.version says. I'm testing with 2.6.2 > >> (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)], running > >> on Win XP.- Hide quoted text - > > >> - Show quoted text - > > > Thank you for your help: I'm working on a rather large source, but I > > think I have isolated the problem now. > > This listing generates an error: > > > --- > > class BaseA(object): > > def __init__(self): > > return > > > class DebugA(BaseA): > > def __init__(self): > > return > > > class B(object): > > def __init__(self,test=A()): > > self.obj =() > > return > > > if __name__ ="__main__": > > # class A(BaseA): # Uncomment this for using BaseA objects > > # pass > > class A(DebugA): # Uncomment this for using DebugA objects > > pass > > --- > > > The error happens because Python apparently evaluates the named > > arguments before running the script. > > I think I have read something about this some (long) time ago but I > > can't find it anymore. > > > Suggestions? > > > BTW, my Python version is 2.6.1 (with latest PyDev). > > > Thx! > >Lorenzo > > This error is caused because a default argument uses class A. Default > arguments of class methods are evaluated during the definition of the > class, and not later when the class is instantiated. Thus the problem. > > To work around that specific problem, you may want to use the following: > > class B(object): > def __init__(self,test=None): > if test==None: > test = A() > self.obj =() > return > > This is actually different than what you had, since what you had would > have used the same A() object for all instances of B that didn't supply > their own test() parameter. Maybe that's what you wanted, and maybe > not, but default arguments set to mutable values are frequently a bug. > > But I'm wondering if you're just looking for problems. Why not put the > commented switch early in the file, and test for it wherever you need to > use it? > > import x, y, z > _debug = False > #_debug = True > > then as soon as BaseA and DebugA are defined, do the following: > > if _debug: > class A(DebugA): > pass > else: > class A(BaseA) > pass- Zitierten Text ausblenden - > > - Zitierten Text anzeigen - I had also thought of using "None" (or whatever else) as a marker but I was curious to find out whether there are better ways to supply an object with standard values as a default argument. In this sense, I was looking for problems ;-) Of course the observation that "def" is an instruction and no declaration changes the situation: I would not have a new object being constructed for every instantiation with no optional argument, because __init__ gets executed on the instantiation but test=A() gets executed on reading 'def'. At this point I think there is no other way than using a marker as suggested above multiple times, if I want to supply a new object with default values for non-passed arguments. Anybody with a better idea? -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance and forward references (prototypes)
On 21 Jun., 22:51, Scott David Daniels wrote: > LorenzoDiGregoriowrote: > > On 21 Jun., 01:54, Dave Angel wrote: > >> ... > >> class B(object): > >> def __init__(self,test=None): > >> if test==None: > >> test = A() > >> self.obj =() > >> return > > ... > > I had also thought of using "None" (or whatever else) as a marker but > > I was curious to find out whether there are better ways to supply an > > object with standard values as a default argument. > > In this sense, I was looking for problems ;-) > > > Of course the observation that "def" is an instruction and no > > declaration changes the situation: I would not have a new object being > > constructed for every instantiation with no optional argument, because > > __init__ gets executed on the instantiation but test=A() gets executed > > on reading 'def' > > If what you are worrying about is having a single default object, you > could do something like this: > > class B(object): > _default = None > > def __init__(self, test=None): > if test is None: > test = self._default > if test is None: > B._default = test = A() > ... > > --Scott David Daniels > scott.dani...@acm.org- Zitierten Text ausblenden - > > - Zitierten Text anzeigen - Well, I could also declare (ups, define ;-)) __init__(self,**kwargs) and within the __init__, if kwargs['test'] exists, do test = kwargs ['test'], if it does not exist, do test = A(). The point is that it would have been cleaner to place it straight in the __init__, but due to the semantic of 'def' this does not seem possible. -- http://mail.python.org/mailman/listinfo/python-list