Re: Running a command line program and reading the result as it runs
Chris Angelico wrote: On Fri, Aug 23, 2013 at 1:26 AM, Ian Simcock wrote: Chris Angelico wrote: A lot of programs, when their output is not going to the console, will buffer output. It's more efficient for many purposes. With Unix utilities, there's often a parameter like --pipe or --unbuffered that says "please produce output line by line", but Windows ping doesn't have that - and so I'm seeing the same thing you are. You should be able to see the time delay in dir by looking for some particular directory name, and searching from the root directory. Unless you're on a BLAZINGLY fast drive, that'll take Windows a good while! ChrisA I tried it again with the dir command and, while my drive is pretty fast, it does look like it works. I've done come looking around and found that the standard C libraries apparently automatically buffer output when the output is being redirected to a file handle unless specifically told not to. I did a further test and created a unique file name in the root of my D drive and then use dir to search the entire drive for that name. In the command window the name appears instantly and then after a slight pause the command prompt reappears. When run from python however the pause comes first and then the name appears and then the command prompt returns. So yep, seems like I'm screwed :-) Thanks for your help with this. At least now I know it's not that I'm doing something wrong. Ian Simcock. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEPs should be included with the documentation download
Chris Angelico writes: > Hence the question: How many people actually do use the downloaded > docs? Maybe it'd turn out to be quite high, but it's not an > unreasonable question. I think it's an unreasonable question. What would you accept as an answer? Who could possibly be autoritative at estimating such a number? How would you choose between competing authorities and estimates? It should be sufficient to realise that the reality of internet infrastructure in most countries makes it preferable – at least some of the time, for some significant, even if small, number of users – to read the documentation on local storage instead of on the internet. -- \“I took a course in speed waiting. Now I can wait an hour in | `\ only ten minutes.” —Steven Wright | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
On Thu, Aug 22, 2013, at 18:22, Dennis Lee Bieber wrote: > Well... The main thing to understand is that this particular "forum" is > NOT JUST a mailing-list. It is cross-linked with the Usenet > comp.lang.python news-group (and that, unfortunately, is cross-linked to > Google-Groups). And to compound things, Gmane makes the mailing-list > source > available as a news-group on their server. > > So it isn't being viewed using just email clients -- I view it using a > newsreader. I don't see how that's relevant, since newsreaders in general, and (based on a quick google search for information about it) Forte Agent in particular, have mime implementations as full-featured as any mail client. -- http://mail.python.org/mailman/listinfo/python-list
Current trends in python
Dear friends, can anybody help me to know latest trends in python...back,middle,front end softwares...frameworks etc also how exactly python based projects are developed? thank u -- http://mail.python.org/mailman/listinfo/python-list
Re: c# async, await
On Thu, Aug 22, 2013 at 5:29 AM, Neal Becker wrote: > So my son is now spending his days on c# and .net. He's enthusiastic about > async and await, and said to me last evening, "I don't think python has > anything > like that". I'm not terribly knowledgeable myself regarding async programming > (since I never need to use it). I did look at this: > > http://tirania.org/blog/archive/2013/Aug-15.html > > I wonder what response the python community might have. I've done something sort of similar to await in Python using restartable functions. The code looks like this (using Twisted Deferreds, but any sort of promise could be substituted in): from functools import wraps from twisted.internet import defer def restartable(func): def resume(result, is_failure, results, args, kws): def await(get_deferred, *args, **kws): try: is_failure, result = reversed_results.pop() except IndexError: raise Await(get_deferred(*args, **kws)) if is_failure: result.raiseException() return result def do_once(func, *args, **kws): return await(defer.maybeDeferred, func, *args, **kws) await.do_once = do_once if results is None: results = [] else: results.append((is_failure, result)) reversed_results = list(reversed(results)) try: func(await, *args, **kws) except Await as exc: deferred = exc.args[0] deferred.addCallback(resume, False, results, args, kws) deferred.addErrback(resume, True, results, args, kws) @wraps(func) def wrapper(*args, **kws): return resume(None, None, None, args, kws) return wrapper class Await(BaseException): pass The usage of restartable and await then looks something like this: @restartable def random_sum(await): try: a = await(random_number) b = await(random_number) c = await(random_number) d = await(random_number) except ValueError as exc: print("Couldn't get four numbers: " + exc.message) return print('{} + {} + {} + {} = {}'.format(a, b, c, d, a + b + c + d)) The "await" argument is passed in by the restartable machinery, not by the caller. The argument passed to await is a callable that is expected to return a Deferred, and any additional arguments are passed along to the callable. A boring implementation of the "random_number" callable might look like this: def random_number(): from random import randrange from twisted.internet import defer, reactor deferred = defer.Deferred() if randrange(4) > 0: number = randrange(42) print("Generated {}".format(number)) reactor.callLater(1, deferred.callback, number) else: print("Failed") reactor.callLater(1, deferred.errback, ValueError("Not available")) return deferred Of course the big caveat to all this is that since the function is restartable, the "random_sum" function above actually gets called five times, and so if there are any side effects before the last await, they'll end up happening multiple times. This can be averted using await.do_once: @restartable def random_sum(await): try: await.do_once(print, 1) a = await(random_number) await.do_once(print, 2) b = await(random_number) await.do_once(print, 3) c = await(random_number) await.do_once(print, 4) d = await(random_number) except ValueError as exc: print("Couldn't get four numbers: " + exc.message) return print('{} + {} + {} + {} = {}'.format(a, b, c, d, a + b + c + d)) The result of running this is: 1 Generated 35 2 Generated 28 3 Generated 32 4 Generated 16 35 + 28 + 32 + 16 = 111 -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
On Thu, 22 Aug 2013 13:54:14 +0200, Ulrich Eckhardt wrote: > Firstly, there is one observation: The Python object of type Thread is > one thing, the actual thread is another thing. This is similar to the > File instance and the actual file. The Python object represents the > other thing (thread or file) but it "is not" this thing. It is rather a > handle to the file or thread. This is different for e.g. a string, where > the Python object is the string. Well, not quite. To users coming from other languages, "string" has a clear and common meaning; it's an array of characters, possibly fixed- width in older languages, but these days usually variable-width but prefixed with the length (as in Pascal) or suffixed with a delimiter (usually \0, as in C). Or occasionally both. So as far as those people are concerned, Python strings aren't just a string. They are rich objects, with an object header. For example, we can see that there is a whole bunch of extra "stuff" required of a Python string before you even get to the array-of-characters: py> sys.getsizeof('') 25 25 bytes to store an empty string. Even if it had a four-byte length, and a four-byte NUL character at the end, that still leaves 17 bytes unaccounted for. So obviously Python strings contain a whole lot more than just low-level Pascal/C strings. So while I agree that it is sometimes useful to distinguish between a Python Thread object and the underlying low-level thread data structure it wraps, we can do the same with strings (and floats, and lists, and everything really). In any case, it's rare to need to do so. > Due to this pairing between the actual thing and the handle, there is > also some arity involved. For a single thread or file, there could be > multiple Python objects for handling it, or maybe even none. I don't think this is correct for threads. I don't believe there is any way to handle a low-level thread in Python except via an object of some sort. (With files, you can use the os module to work with low-level OS file descriptors, which are just integers.) > When the > Python object goes away, it doesn't necessarily affect the thread or > file it represents. That's certainly not true with file objects. When the file object goes out of scope, the underlying low-level file is closed. > This already casts a doubt on the habit of deriving > from the Thread type, just like deriving from the File type is highly > unusual, as you are just deriving from a handle class. In Python 3, there is no "File" type. There are *multiple* file types, depending on whether you open a file for reading or writing in binary or text mode: py> open('/tmp/junk', 'wb') <_io.BufferedWriter name='/tmp/junk'> py> open('/tmp/junk', 'rb') <_io.BufferedReader name='/tmp/junk'> py> open('/tmp/junk', 'w') <_io.TextIOWrapper name='/tmp/junk' mode='w' encoding='UTF-8'> But even if we limit the discussion to Python 2, it is unusual to inherit from File because File already does everything we normally want from a file. There's no need to override methods, so why make your own subclass? On the other hand, threads by their very nature have to be customized. The documentation is clear that there are two acceptable ways to do this: This class represents an activity that is run in a separate thread of control. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. http://docs.python.org/2/library/threading.html#thread-objects So to some degree, it is just a matter of taste which you use. [...] > In summary, I find that modelling something to "use a thread" is much > clearer than modelling it as "is a thread". The rest of your arguments seem good to me, but not compelling. I think they effectively boil down to personal taste. I write lots of non-OOP code, but when it comes to threads, I prefer to subclass Thread. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
On Thu, 22 Aug 2013 09:45:43 -0400, Ned Batchelder wrote: > So that I understand what's going on, what's the bad thing that happens > with a multi-part message? I would have thought that mail readers would > choose the preferred part, or is it something to do with the message > quoting? This is not just a mailing list, it is also a newsgroup, and sending HTML content to a text newsgroup is considered rude. Just to add insult to injury, one of the most popular (and otherwise excellent) news readers, Pan, treats HTML as "plain text", and displays junk like this at the end of your HTML posts: On 8/21/13 6:50 PM, Fábio Santos wrote: On 21 Aug 2013 20:07, "Johannes Bauer"
Re: New book: Python in Practice
On Thu, 22 Aug 2013 02:39:01 -0700, Mark Summerfield wrote: > Hi, > > My new Python 3-based book, "Python in Practice", is due out next week. > > The book is aimed at people who can already program in Python and want > to take their coding further. > > The book's web page (http://www.qtrac.eu/pipbook.html) has the table of > contents and a link to a free PDF of Chapter 1 so you can see if it > appeals to you. The book's examples are also available for download from > that page. > > I hope you'll take a look:-) Looks good! -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation unpythonic?
On Saturday, August 17, 2013 8:26:32 AM UTC-4, Fernando Saldanha wrote: > I am new to Python, with experience in Java, C++ and R. > > > > As I understand encapsulation is not a big thing in the Python world. I read > that you can put two underscores before the name of a variable within a class > declaration but in the many examples of code I looked at this is not widely > used. I also read that encapsulation is "unpythonic." > > > > Questions: > > > > 1) Is there a good text where I can read about the language philosophy? What > practices are "pythonic" or "unpythonic"? > > > > 2) If it is in fact true that encapsulation is rarely used, how do I deal > with the fact that other programmers can easily alter the values of members > of my classes? > > > > Thanks for any insights. > > > > FS Hi FS, I'm taking the Python Cert series w/ O'Reilly School of Technology, which I recommend if you've got a good handle on OO programming. In any event, according to what I've learned, "encapsulation is the idea that the only way to access or change the data inside an object is by calling its methods. This idea has never really gained much ground in the Python world, and it is normally considered acceptable to both read and set an object's attributes from anywhere in a program." Not being an expert OO programmer, I take this at face value. There are ways to protect class attributes from having their values reset from outside. That is, they can be made "internal use only" and an AttributeError raised when someone tries to change the attribute(s). This involves __setattr__ and checking if the key of the attribute is in a/the list of attributes you've chose to protect. If so, raise AttributeError. Hope that helps in some small measure. In the interest of full disclosure, answering a Python question is part of my homework for the O'Reilly Python 4 class I'm taking. Good luck! -- http://mail.python.org/mailman/listinfo/python-list
Re: PEPs should be included with the documentation download
On Fri, Aug 23, 2013 at 11:47 AM, Ben Finney wrote: > Chris Angelico writes: > >> Also, how many people actually depend on the downloadable >> documentation, rather than simply reading things online? > > Many countries do not have infrastructure that allows reliable, fast, > low-latency internet access 24-hours-a-day. Most countries's internet > infrastructure, in fact, does not satisfy all of those. I'm aware of that. However, I'm also aware that many people still read things online, even with a less-than-reliable internet connection. Hence the question: How many people actually do use the downloaded docs? Maybe it'd turn out to be quite high, but it's not an unreasonable question. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: PEPs should be included with the documentation download
Chris Angelico writes: > Also, how many people actually depend on the downloadable > documentation, rather than simply reading things online? Many countries do not have infrastructure that allows reliable, fast, low-latency internet access 24-hours-a-day. Most countries's internet infrastructure, in fact, does not satisfy all of those. And without all of those being satisfied simultaneously, accessing programmer documentation online is frustratingly inconsistent. It is much more convenient and reliable, in those cases, to have the documentation downloaded and accessible on one's development workstation. -- \ “We must find our way to a time when faith, without evidence, | `\disgraces anyone who would claim it.” —Sam Harris, _The End of | _o__) Faith_, 2004 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Replace blanks with letter
eschneide...@comcast.net wrote: > I wanted the program to stop only after all the letters were typed; why in > the world would I try to write a program with blanks for each letter that > seem intended to be filled, only to have it stop if the last letter is typed, > or have to type each letter so many times until its processed? If you ran the > code, my problems, as well as the intended goal, should become obvious. Also, > why wouldn't someone who's willing to help me not run the code (takes a few > seconds btw) I'm having trouble with in order to diagnose its faults, yet you > have the time to write how you won't run it? If I did have a teacher to help > me, this would be the last place I'd come to for help. It should be easy to > deduce what I intended this program to do. Please no one respond being as I > am done here, I just had to vent, > but instead report it if you want. It would have been much fewer words to describe the goal of the program. I ran the code, and showed the results of running it. But I still have no spec for what your assignment was. Like maybe the user is supposed to type one character at each prompt, even though it tells him to type 7. And the program should refuse any attempt to type more than one letter. And the user can type the characters in any order, not just A to G, and it'll keep prompting him till all 7 of the original letters is found. And it'll score him based on how many tries before he finishes. Or about 40 other possibilities. If you do have a teacher, have him tell you about comments. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Using PyQT with QT Designer
On Thursday, August 22, 2013 3:26:17 AM UTC-5, Phil Thompson wrote: > It looks like you aren't using a layout to arrange your widgets. > > Explicitly specifying geometries is a bad idea. > > > > Phil Thanks.QT Designer uses set geometry and I'm totally lost as how to implement it. I've tried using a layout on the central widget. I've tried specifically referencing the Ui_MainWindow in the window.py ui file... This is what I tried: from PyQt4.QtCore import * from PyQt4.QtGui import * from window import Ui_MainWindow THUMBNAIL_SIZE = 128 SPACING= 10 IMAGES_PER_ROW = 4 class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() #self.setWindowTitle("Image Gallery") centralWidget=QWidget(self) l=QVBoxLayout(centralWidget) self.tableWidget=TableWidget(self) l.addWidget(self.tableWidget) self.listWidget=ListWidget(self) l.addWidget(self.listWidget) Ui_MainWindow.pushButton = QPushButton(self) l.addWidget(Ui_MainWindow.pushButton) self.pushButton_2 = QPushButton(self) l.addWidget(self.pushButton_2) self.pushButton_3 = QPushButton(self) l.addWidget(self.pushButton_3) self.setCentralWidget(centralWidget) picturesPath=QDesktopServices.storageLocation(QDesktopServices.PicturesLocation) pictureDir=QDir(picturesPath) pictures=pictureDir.entryList(['*.jpg','*.png','*.gif']) rowCount=len(pictures)//IMAGES_PER_ROW if len(pictures)%IMAGES_PER_ROW: rowCount+=1 self.tableWidget.setRowCount(rowCount) row=-1 for i,picture in enumerate(pictures): col=i%IMAGES_PER_ROW if not col: row+=1 self.tableWidget.addPicture(row, col, pictureDir.absoluteFilePath(picture)) class ListWidget(QListWidget): def __init__(self, parent=MainWindow, **kwargs): QListWidget.__init__(self, parent, **kwargs) self.setGeometry(QRect(70, 400, 661, 181)) class TableWidget(QTableWidget): def __init__(self, parent=MainWindow, **kwargs): QTableWidget.__init__(self, parent, **kwargs) self.setIconSize(QSize(128,128)) self.setColumnCount(IMAGES_PER_ROW) self.setGridStyle(Qt.NoPen) # Set the default column width and hide the header self.verticalHeader().setDefaultSectionSize(THUMBNAIL_SIZE+SPACING) self.verticalHeader().hide() # Set the default row height and hide the header self.horizontalHeader().setDefaultSectionSize(THUMBNAIL_SIZE+SPACING) self.horizontalHeader().hide() # Set the table width to show all images without horizontal scrolling self.setMinimumWidth((THUMBNAIL_SIZE+SPACING)*IMAGES_PER_ROW+(SPACING*2)) def addPicture(self, row, col, picturePath): item=QTableWidgetItem() # Scale the image by either height or width and then 'crop' it to the # desired size, this prevents distortion of the image. p=QPixmap(picturePath) if p.height()>p.width(): p=p.scaledToWidth(THUMBNAIL_SIZE) else: p=p.scaledToHeight(THUMBNAIL_SIZE) p=p.copy(0,0,THUMBNAIL_SIZE,THUMBNAIL_SIZE) item.setIcon(QIcon(p)) self.setItem(row,col,item) if __name__=="__main__": from sys import argv, exit a=QApplication(argv) m=MainWindow() m.show() m.raise_() exit(a.exec_()) and I'm getting this (not even starting at 800x600): http://i.imgur.com/Xg4Qnzl.png instead of this as it was designed in QT Designer: http://i.imgur.com/ULRolq8.png Here is the ui file window.py that I got by running pyuic4 on window.ui: # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'window.ui' # # Created by: PyQt4 UI code generator 4.9.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(800, 600) MainWindow.setAnimated(False) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.tableWidget = QtGui.QTableWidget(self.centralwidget) self.tableWidget.setGeometry(QtCore.QRect(70, 20, 661, 381)) self.tableWidget.setObjectName(_f
Re: c# async, await
On 8/22/2013 9:57 AM, Michael Torrie wrote: On 08/22/2013 05:29 AM, Neal Becker wrote: So my son is now spending his days on c# and .net. He's enthusiastic about async and await, and said to me last evening, "I don't think python has anything like that". I'm not terribly knowledgeable myself regarding async programming (since I never need to use it). I did look at this: http://tirania.org/blog/archive/2013/Aug-15.html The iterator protocol, introduced in 2.2, was explicitly intended (by Tim Peters) to replace many uses of synchonous callbacks. This example from the blog, of callback replacement, int sum_values (Hashtable hash) { int sum = 0; hash.foreach ((key, value) => { sum += value; }); return sum; } is written in Python *much more generally* as def sum(iterable): sum = 0 for item in iterable: sum += item return sum Notice that this is not limited to summing ints, nor to summing values in a hash. sum(somedic.values()) does the specific task of summing hash values. Any time you use a GUI library, you can often use its own async primitives (in fact you probably need to). For example glib from Gtk+ provides io wait primitives. Or if you want a completely asynchronous programming experience from top to bottom, you can use python twisted. There are also other libraries to do this. Having first-class language support is certainly nice, and it would be nice if Python had this. GvR himself agrees. http://www.youtube.com/watch?v=sOQLVm0-8Yg C#'s await was part of the early discussion about Python's new asynch library. Last I knew, 'Tulip' uses callbacks at the lowest level, but the user level uses generators and 'yield from'. I hope this makes in into 3.4. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: PEPs should be included with the documentation download
On 8/22/2013 4:39 AM, Aseem Bansal wrote: I do depend on offline documentation. I have both Python2 and 3's documentation offline. A lot of people have 24-hour access to internet but a lot of people don't have. And while moving around it isn't always possible to have internet then offline documentation is really helpful. If you have mercurial installed, you can easily download a read-only clone of the peps repository (hg.python.org/peps, I believe). You can even pull updates whenever you feel like it. One can also clone the main repository and build the regular docs, including the html version thereof. Again, pull and rebuild when you expect to be offline. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Replace blanks with letter
I wanted the program to stop only after all the letters were typed; why in the world would I try to write a program with blanks for each letter that seem intended to be filled, only to have it stop if the last letter is typed, or have to type each letter so many times until its processed? If you ran the code, my problems, as well as the intended goal, should become obvious. Also, why would someone who's willing to help me not run the code (takes a few seconds btw) I'm having trouble with in order to diagnose its faults, yet you have the time to write how you won't run it? If I did have a teacher to help me, this would be the last place I'd come to for help. It should be easy to deduce what I intended this program to do. Please no one respond being as I am done here, I just had to vent, but instead report it if you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: Replace blanks with letter
I wanted the program to stop only after all the letters were typed; why in the world would I try to write a program with blanks for each letter that seem intended to be filled, only to have it stop if the last letter is typed, or have to type each letter so many times until its processed? If you ran the code, my problems, as well as the intended goal, should become obvious. Also, why wouldn't someone who's willing to help me not run the code (takes a few seconds btw) I'm having trouble with in order to diagnose its faults, yet you have the time to write how you won't run it? If I did have a teacher to help me, this would be the last place I'd come to for help. It should be easy to deduce what I intended this program to do. Please no one respond being as I am done here, I just had to vent, but instead report it if you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a child access parent attributes if that child added post-hoc as an attribute to the parent?
On Thursday, August 22, 2013 4:26:24 PM UTC-5, Prasad, Ramit wrote: > Bitswapper wrote: > > > > > > So I have a parent and child class: > > > > > > > > > class Map(object): > > > def __init__(self, name=''): > > > self.mapName = name > > > self.rules = {} > > > > > > class Rule(Map): > > > def __init__(self, number): > > > Map.__init__(self) > > > self.number = number > > > > This means that rules will never have a name. I think you need > > def __init__(self, name='', number=None): > > Map.__init__(self, name) > > self.number = number > > > > > > def __repr__(self): > > > return "Map " + self.mapName + " rule number " + str(self.number) > > > > > > if __name__ == "__main__": > > > map = Map("thismap") > > > rule = Rule(1) > > > map.rules[rule.number] = rule > > > > > > > > > > > > with the above: > > > $ python -i inherit.py > > > >>> map > > > <__main__.Map object at 0xb7e889ec> > > > >>> map.rules > > > {1: Map rule number 1} > > > >>> map.rules[1] > > > Map rule number 1 > > > >>> > > > > > > > > > I have tried adding: > > > map.rules[2] = Rule(2) > > > > > > but that still gets: > > > > > > $ python -i inherit.py > > > >>> map.rules > > > {1: Map rule number 1, 2: Map rule number 2} > > > >>> > > > > > > and: > > > map.rule = Rule(3) > > > > > > which also doesn't really get me what I'm looking for: > > > > > > >>> map.rules > > > {1: Map rule number 1, 2: Map rule number 2} > > > >>> map.rule > > > Map rule number 3 > > > >>> > > > > > > > > > It seems to me what I'm trying to do is link an arbitrary child instance to > > an arbitrary instance of a > > > parent class, which in this case would be handy Because I'd like to > > populate a map with rules and > > > print the rules including the parent map name for each rule. I'm just not > > sure how I would go about > > > doing this in python. > > > > > > Any thoughts are welcome, and thanks in advance > > > > I not sure what you mean by the above. Can you provide an example of what you > want to occur and the output for it? > I was thinking of: map = Map('myMap') map.rules[1] = Rule[1] map.rules[2] = Rule[2] >>> print map.rules[1] >>> Map myMap rule number 1 >>> print map.rules[2] >>> Map myMap rule number 2 >>> >>> map.mapName = "newname" >>> print map.rules[1] >>> Map newname rule number 1 >>> print map.rules[2] >>> Map newname rule number 2 -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a child access parent attributes if that child added post-hoc as an attribute to the parent?
On Thu, Aug 22, 2013 at 3:26 PM, Prasad, Ramit wrote: > Bitswapper wrote: >> >> So I have a parent and child class: >> >> >> class Map(object): >> def __init__(self, name=''): >> self.mapName = name >> self.rules = {} >> >> class Rule(Map): >> def __init__(self, number): >> Map.__init__(self) >> self.number = number > > This means that rules will never have a name. I think you need > def __init__(self, name='', number=None): > Map.__init__(self, name) > self.number = number No, that's still wrong. The OP talks abut maps having names, not rules having names. Unless a Rule is-a Map, which sounds unlikely, Rule should not be inheriting from Map in the first place. >> It seems to me what I'm trying to do is link an arbitrary child instance to >> an arbitrary instance of a >> parent class, which in this case would be handy Because I'd like to >> populate a map with rules and >> print the rules including the parent map name for each rule. I'm just not >> sure how I would go about >> doing this in python. You'll need to keep a reference to the Map on each Rule instance. So instead of self.mapName you'll have self.map.mapName. Your Rule class should probably look something like this: class Rule(object): def __init__(self, map, number): self.map = map self.number = number And then when you construct it you'll need to tell it what map it belongs to: rule = Rule(map, 1) -- http://mail.python.org/mailman/listinfo/python-list
RE: Can a child access parent attributes if that child added post-hoc as an attribute to the parent?
Bitswapper wrote: > > So I have a parent and child class: > > > class Map(object): > def __init__(self, name=''): > self.mapName = name > self.rules = {} > > class Rule(Map): > def __init__(self, number): > Map.__init__(self) > self.number = number This means that rules will never have a name. I think you need def __init__(self, name='', number=None): Map.__init__(self, name) self.number = number > > def __repr__(self): > return "Map " + self.mapName + " rule number " + str(self.number) > > if __name__ == "__main__": > map = Map("thismap") > rule = Rule(1) > map.rules[rule.number] = rule > > > > with the above: > $ python -i inherit.py > >>> map > <__main__.Map object at 0xb7e889ec> > >>> map.rules > {1: Map rule number 1} > >>> map.rules[1] > Map rule number 1 > >>> > > > I have tried adding: > map.rules[2] = Rule(2) > > but that still gets: > > $ python -i inherit.py > >>> map.rules > {1: Map rule number 1, 2: Map rule number 2} > >>> > > and: > map.rule = Rule(3) > > which also doesn't really get me what I'm looking for: > > >>> map.rules > {1: Map rule number 1, 2: Map rule number 2} > >>> map.rule > Map rule number 3 > >>> > > > It seems to me what I'm trying to do is link an arbitrary child instance to > an arbitrary instance of a > parent class, which in this case would be handy Because I'd like to populate > a map with rules and > print the rules including the parent map name for each rule. I'm just not > sure how I would go about > doing this in python. > > Any thoughts are welcome, and thanks in advance I not sure what you mean by the above. Can you provide an example of what you want to occur and the output for it? ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a command line program and reading the result as it runs
Ian Simcock writes: > Greetings all. > > I'm using Python 2.7 under Windows and am trying to run a command line > program and process the programs output as it is running. A number of > web searches have indicated that the following code would work. > > import subprocess > > p = subprocess.Popen("D:\Python\Python27\Scripts\pip.exe list -o", > stdout=subprocess.PIPE, > stderr=subprocess.STDOUT, > bufsize=1, > universal_newlines=True, > shell=False) > for line in p.stdout: > print line > > When I use this code I can see that the Popen works, any code between > the Popen and the for will run straight away, but as soon as it gets > to the for and tries to read p.stdout the code blocks until the > command line program completes, then all of the lines are returned. > > Does anyone know how to get the results of the program without it blocking? When file object is used in a for loop it works like an iterator and then it uses a hidden read-ahead buffer. It might cause this kind of blocking. You can read more details here (description of method ``next``): http://docs.python.org/lib/bltin-file-objects.html So basically non-blocking loop might look like this: while True: line = p.stdout.readline() if not line: break print line HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Can a child access parent attributes if that child added post-hoc as an attribute to the parent?
So I have a parent and child class: class Map(object): def __init__(self, name=''): self.mapName = name self.rules = {} class Rule(Map): def __init__(self, number): Map.__init__(self) self.number = number def __repr__(self): return "Map " + self.mapName + " rule number " + str(self.number) if __name__ == "__main__": map = Map("thismap") rule = Rule(1) map.rules[rule.number] = rule with the above: $ python -i inherit.py >>> map <__main__.Map object at 0xb7e889ec> >>> map.rules {1: Map rule number 1} >>> map.rules[1] Map rule number 1 >>> I have tried adding: map.rules[2] = Rule(2) but that still gets: $ python -i inherit.py >>> map.rules {1: Map rule number 1, 2: Map rule number 2} >>> and: map.rule = Rule(3) which also doesn't really get me what I'm looking for: >>> map.rules {1: Map rule number 1, 2: Map rule number 2} >>> map.rule Map rule number 3 >>> It seems to me what I'm trying to do is link an arbitrary child instance to an arbitrary instance of a parent class, which in this case would be handy Because I'd like to populate a map with rules and print the rules including the parent map name for each rule. I'm just not sure how I would go about doing this in python. Any thoughts are welcome, and thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: python3-sqlalchemy and debian repo
Chris Angelico writes: > It may be that the -ext accelerator isn't available for Py3 in package > form, or it might be incorporated, I don't know. AFAICT, the Py3 accelerators will be available with SA 0.9. ciao, lele. -- nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia. l...@metapensiero.it | -- Fortunato Depero, 1929. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
On Thu, Aug 22, 2013, at 9:45, Ned Batchelder wrote: > So that I understand what's going on, what's the bad thing that happens > with a multi-part message? I would have thought that mail readers would > choose the preferred part, or is it something to do with the message > quoting? The bad thing that happens is baby Jesus cries. In other words, some people just don't like it, for no better reason than personal ideology (and/or they have a non-mime email client and don't like seeing the extra encoded stuff, and/or they have a fully HTML capable email client, don't like it, and can't be bothered learning how to turn off HTML viewing). There's really no way to have a productive discussion about it (though it might be worthwhile to ask whoever is in charge of the list to make it automatically strip html from messages, if enough people have a strong preference) -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
On 8/22/13 1:43 AM, Bob Martin wrote: in 704175 20130822 010625 Ned Batchelder wrote: This is a multi-part message in MIME format. Please post in plain text, not HTML. Sorry, Bob, I will try to remember in the future. I think Thunderbird is sending in the same format as the replied-to message, and I didn't notice. So that I understand what's going on, what's the bad thing that happens with a multi-part message? I would have thought that mail readers would choose the preferred part, or is it something to do with the message quoting? --Ned. PS: Bob: email to you is bouncing, as excite.com says you don't exist. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, VST and Csound
Have you tried the csound mailing list? There's a lot of strong talent there. To subscribe, send an e-mail to: sy...@lists.bath.ac.uk On 08/22/2013 08:32 AM, esnho esnho wrote: Hello to all, I have a question for you: is possible to develop VST using Python interfaced with Csound? In case it is possible, there are any resources that can help in the developing? Thank you very much. -- http://mail.python.org/mailman/listinfo/python-list
Python, VST and Csound
Hello to all, I have a question for you: is possible to develop VST using Python interfaced with Csound? In case it is possible, there are any resources that can help in the developing? Thank you very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a command line program and reading the result as it runs
On Fri, Aug 23, 2013 at 1:26 AM, Ian Simcock wrote: > Chris Angelico wrote: >> >> Is the program actually producing output progressively? I just tried >> your exact code with "dir /ad /s /b" and it worked fine, producing >> output while the dir was still spinning (obviously setting shell=True >> to make that work, but I don't think that'll make a difference). It >> may be that pip buffers its output. Is there a parameter to pip to >> make it pipe-compatible? >> >> ChrisA >> > > If I run pip in the command window I can see it's output appearing line by > line rather than on one block. > > I tried the code with the dir command but it's too fast for me to be sure if > it's working or not. > > I tried again using the command "ping google.com" instead since I know that > output's slowly and it something that everyone should have. In the command > window I can see that the output appears over time, but from python I get > nothing for a while and then suddenly get all the output in one rapid go. > > > Can you think of anything else I can look at? A lot of programs, when their output is not going to the console, will buffer output. It's more efficient for many purposes. With Unix utilities, there's often a parameter like --pipe or --unbuffered that says "please produce output line by line", but Windows ping doesn't have that - and so I'm seeing the same thing you are. You should be able to see the time delay in dir by looking for some particular directory name, and searching from the root directory. Unless you're on a BLAZINGLY fast drive, that'll take Windows a good while! ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a command line program and reading the result as it runs
Chris Angelico wrote: Is the program actually producing output progressively? I just tried your exact code with "dir /ad /s /b" and it worked fine, producing output while the dir was still spinning (obviously setting shell=True to make that work, but I don't think that'll make a difference). It may be that pip buffers its output. Is there a parameter to pip to make it pipe-compatible? ChrisA If I run pip in the command window I can see it's output appearing line by line rather than on one block. I tried the code with the dir command but it's too fast for me to be sure if it's working or not. I tried again using the command "ping google.com" instead since I know that output's slowly and it something that everyone should have. In the command window I can see that the output appears over time, but from python I get nothing for a while and then suddenly get all the output in one rapid go. Can you think of anything else I can look at? Ian Simcock. -- http://mail.python.org/mailman/listinfo/python-list
Re: I wonder if I would be able to collect data from such page using Python
On Fri, Aug 23, 2013 at 1:03 AM, Comment Holder wrote: > As I am new, I won't ask for assistance before I get some general idea about > Python. I shall dedicate the weekend for this purpose, or at least Sunday. > Once I am done, I will post my results back in here. Smart move :) I strongly recommend the inbuilt tutorial, if you haven't seen it already: http://docs.python.org/3/tutorial/ And you're using the current version, which is good. Saves the hassle of figuring out what's different in an old version. All the best! ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: I wonder if I would be able to collect data from such page using Python
Dear Piet, Many thanks for your assistance. It is much appreciated. I have just installed Python 3.3.2 and BeautifulSoup 4.3.1. I tried running the code, but run into some syntax errors. > I wonder how you would want that with multiparagraph contents. I am looking to save all the paragraphs of an article in one field, so that, the afterwards-analysis becomes easier. As I am new, I won't ask for assistance before I get some general idea about Python. I shall dedicate the weekend for this purpose, or at least Sunday. Once I am done, I will post my results back in here. Thanks again & all best// -- http://mail.python.org/mailman/listinfo/python-list
Re: I wonder if I would be able to collect data from such page using Python
Dear Terry, Many thanks for your comments. Actually I was, because the target-page doesn't have a neat structure. But, after all of your contributions, I think the task can be achieved very well with Python. Thanks again & all best// -- http://mail.python.org/mailman/listinfo/python-list
Re: c# async, await
On 2013-08-22, Neal Becker wrote: > So my son is now spending his days on c# and .net. He's enthusiastic about > async and await, and said to me last evening, "I don't think python has > anything > like that". I'm not terribly knowledgeable myself regarding async > programming > (since I never need to use it). I did look at this: > > http://tirania.org/blog/archive/2013/Aug-15.html > > I wonder what response the python community might have. GVR and a team of top people is working on the problem: http://www.python.org/dev/peps/pep-3156/ There's also Twisted: http://twistedmatrix.com/trac/ -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: c# async, await
On 08/22/2013 05:29 AM, Neal Becker wrote: > So my son is now spending his days on c# and .net. He's enthusiastic about > async and await, and said to me last evening, "I don't think python has > anything > like that". I'm not terribly knowledgeable myself regarding async > programming > (since I never need to use it). I did look at this: > > http://tirania.org/blog/archive/2013/Aug-15.html Any time you use a GUI library, you can often use its own async primitives (in fact you probably need to). For example glib from Gtk+ provides io wait primitives. Or if you want a completely asynchronous programming experience from top to bottom, you can use python twisted. There are also other libraries to do this. Having first-class language support is certainly nice, and it would be nice if Python had this. GvR himself agrees. http://www.youtube.com/watch?v=sOQLVm0-8Yg -- http://mail.python.org/mailman/listinfo/python-list
Re: pydoc vs. non-def'd methods
On Thu, 22 Aug 2013 06:39:48 +, Steven D'Aprano wrote: > On Thu, 22 Aug 2013 05:13:03 +, Dan Sommers wrote: >> class Spam1: >> >> def eggs(self): >> '''Return the Meaning of Life.''' >> return 42 >> >> ham = eggs >> >> >> help(Spam1) shows that ham = eggs(self), which isn't all bad, but it >> could be better. help(Spam1.ham) shows the help for eggs; I know >> why, but this could be better as well. > I'm not entirely sure how it could possibly be better. Since ham is > just another name for eggs, it makes sense that they show the same > docstring. Yes, help(Spam1.eggs) and help(Spam1.ham) show the same docstring. help(Spam1), however, doesn't show any docstring for ham; it shows that ham = eggs(self). >> And in any case, eggs looks somehow better than ham, because eggs has >> its own def statement and ham doesn't. > > I don't think I agree, but perhaps that's just an aesthetic judgement > where we disagree. Yep, just the aesthetics. > class Spam: > def eggs(self): > """eggs docstring""" > return "ham and eggs" > def ham(self): > return self.eggs() > ham.__doc__ = eggs.__doc__.replace('eggs', 'ham') > > This allows you two distinct docstrings, at the cost of duplicating > the information in them. Spam.ham will be a *tiny* bit less efficient, > due to the extra method call, but if you're worried about that, you're > probably up to no good :-) That I am up to no good goes without saying! ;-) > But really, I would find that a confusing API. I would wonder what > subtle difference in semantics there was between ham and eggs. I would > much prefer to see that ham was just an alias: > > class Spam: > def eggs(self): > """eggs docstring""" > pass > ham = eggs > > which brings us back to the beginning of your post :-) Yeah, okay, I'll go with that, despite the asymmetry. The names in question are encrypt and decrypt, which for a stream cipher, are the same. Thanks, Steven, for confirming my ability to read the documentation and play around in my interactive shell. ;-) And Thanks, Fábio, for your suggestions, too. -- Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: A data transformation framework. A presentation inviting commentary.
On 08/21/2013 06:29 PM, F.R. wrote: Hi all, In an effort to do some serious cleaning up of a hopelessly cluttered working environment, I developed a modular data transformation system that pretty much stands. I am very . . . etc Chris, Terry, Dieter, thanks for your suggestions. Chris: If my Transformer looks like a function, that's because it is (__call__). My idea was to have something like an erector set of elementary transformation machines that can be assembled into chains. There may be some processing overhead in managing the data flow, but I'm not even sure of that, because the flow needs to be managed somehow and throwing one's stones into someone else's garden doesn't get rid of the stones. My idea was to simplify, generalize and automate in order to deal with the kind of overhead that matters most to me: my own mental overhead. Terry: I am aware of the memory-load aspect. It is no constraint for the things I do. If it became one, I'd develop a translation assembly using a small data sample and when it reaches the stage of reliability, I'd add a line to have each Translator delete its input the moment it is done. I shall certainly look at itertools. Thanks for your suggestions and explanations. Dieter: I wish I could respond to the points you raise. I am unfamiliar with the details and they don't seem like they can be looked up in five minutes. I do make a note of your thoughts. Frederic -- http://mail.python.org/mailman/listinfo/python-list
Re: python3-sqlalchemy and debian repo
On Thu, Aug 22, 2013 at 4:41 AM, Mohsen Pahlevanzadeh wrote: > Dear all, > > I want to use sqlalchemy library, When i use "apt-cashe search > sqlalchemy" , get the following result(part of result): > /// > python-sqlalchemy - SQL toolkit and Object Relational Mapper for Python > python-sqlalchemy-doc - documentation for the SQLAlchemy Python library > python-sqlalchemy-ext - SQL toolkit and Object Relational Mapper for > Python - C extension > python3-sqlalchemy - SQL toolkit and Object Relational Mapper for Python > 3 > > > Question: I want to use python 3, So i didn't doc and ext suffix for > sqlalchemy compatiable with python 3. The given suffix removed in python > 3 or merged in python3-sqlalchemy package? I don't know about -ext, but -doc applies to both: rosuav@sikorsky:~$ apt-cache show python3-sqlalchemy Package: python3-sqlalchemy Source: sqlalchemy Version: 0.7.8-1 Installed-Size: 2824 Maintainer: Piotr Ożarowski Architecture: all Depends: python3 (>= 3.1.3-13~) Suggests: python-sqlalchemy-doc It may be that the -ext accelerator isn't available for Py3 in package form, or it might be incorporated, I don't know. Certainly python-sqlalchemy-ext demands the Py2 version (and python2.7 | python2.6). ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
Am 21.08.2013 20:58, schrieb Johannes Bauer: On 21.08.2013 11:11, Ulrich Eckhardt wrote: That said, there is never a need for deriving from the Thread class, you can also use it to run a function without that. That way is IMHO clearer because the threading.Thread instance is not the thread, just like a File instance is not a file. Both just represent handles for manipulating the actual thing. Huh? That I find most curious. I *always* derive from threading.Thread and really like the way that thread setup works (instanciate Thread handle, call start). Very intuitive, never had the problems with clarity that you mentioned. Could you elaborate on your suggestion? I don't seem to quite get it I'm afraid. What is clear, convenient or not is largely a matter of taste. I'll try to explain my motivations though, maybe it helps... Firstly, there is one observation: The Python object of type Thread is one thing, the actual thread is another thing. This is similar to the File instance and the actual file. The Python object represents the other thing (thread or file) but it "is not" this thing. It is rather a handle to the file or thread. This is different for e.g. a string, where the Python object is the string. Due to this pairing between the actual thing and the handle, there is also some arity involved. For a single thread or file, there could be multiple Python objects for handling it, or maybe even none. When the Python object goes away, it doesn't necessarily affect the thread or file it represents. This already casts a doubt on the habit of deriving from the Thread type, just like deriving from the File type is highly unusual, as you are just deriving from a handle class. Secondly, a thread is even less a "thing" than a file but rather a process or an ongoing operation. As such, it runs code and uses data but it is neither code nor data. Also, it doesn't care which code or data it currently uses. Similarly, the code and data don't care which thread uses them (synchronization problems in multithreaded apps aside). You will find that most of the code called in a thread doesn't use the thread handle, which is another sign that it doesn't care. For that reason, it is unnecessary that "self" references a Thread object. This reduces coupling, as the same code could be called synchronously and asynchronously. The code shouldn't know or care from which thread it is called. In some cases, I even find it unnecessary to have a "self" at all, a thread can just as well run a non-member function. Also, even if it runs a memberfunction initially, it doesn't have to eventually. I find that forcing an OOP approach on things is flawed (OOP is a tool and not a goal) and prefer to make this a decision, but that is a different (although slightly related) issue. Thirdly, when you derive a class from Thread, you are exposing this baseclass' interface to the public, too, even if you don't intend to. This has both the unwanted aspect that you expose all public functions of the baseclass and that even if you mean "is a thread", it actually means "is a handle to a thread", which is even less expressive. Curously, you do that in order to override a single function that is only invoked once. I prefer passing "instance.function" as callable argument to a plain Thread instance for running this, which keeps the two nicely separate. For example, I have a TCP client class here that uses a service thread to handle the data transfer. The fact that there is a background thread should not be of concern to the user of my TCP client class. If I extended this to use two threads, it would even be impossible to derive from Thread for both of them. In summary, I find that modelling something to "use a thread" is much clearer than modelling it as "is a thread". Greetings from Hamburg! Uli -- http://mail.python.org/mailman/listinfo/python-list
c# async, await
So my son is now spending his days on c# and .net. He's enthusiastic about async and await, and said to me last evening, "I don't think python has anything like that". I'm not terribly knowledgeable myself regarding async programming (since I never need to use it). I did look at this: http://tirania.org/blog/archive/2013/Aug-15.html I wonder what response the python community might have. -- http://mail.python.org/mailman/listinfo/python-list
New book: Python in Practice
Hi, My new Python 3-based book, "Python in Practice", is due out next week. The book is aimed at people who can already program in Python and want to take their coding further. The book's web page (http://www.qtrac.eu/pipbook.html) has the table of contents and a link to a free PDF of Chapter 1 so you can see if it appeals to you. The book's examples are also available for download from that page. I hope you'll take a look:-) -- http://mail.python.org/mailman/listinfo/python-list
Re: pydoc vs. non-def'd methods
On 22 Aug 2013 06:17, "Dan Sommers" wrote: > > Greetings, > > I'm hava a class in which there are two equally useful names for one > method. Consider this design (there are other approaches, but that's > not what my question is about): > > class Spam1: > > def eggs(self): > '''Return the Meaning of Life.''' > return 42 > > ham = eggs > > help(Spam1) shows that ham = eggs(self), which isn't all bad, but it > could be better. help(Spam1.ham) shows the help for eggs; I know why, > but this could be better as well. And in any case, eggs looks somehow > better than ham, because eggs has its own def statement and ham doesn't. > > Now consider this design, designed to overcome the previous issues: > > class Spam2: > > def _private(self): > '''Return the Meaning of Life.''' > return 42 > > ham = _private > eggs = _private > > Now help(Spam2.ham) and help(Spam2.eggs) show the same thing, but > help(Spam2) hides _private and its docstring and shows that ham and eggs > both call _private. That's no good. I can expose _private (e.g., by > renaming it to public), but that defeats the purpose of making it > private in the first place. I can go ahead and define ham to invoke > eggs, but then I have to duplicate the docstring, and it's not > being-hit-on-the-head obvious that ham and eggs are simply synonyms for > the same functionality. > > I could put the documentation at the class level, but then it doesn't > show up as part of help(Spam2.eggs) or help(Spam1.ham). > > So is there a clean way to define SpamN such that help(SpamN), > help(SpamN.ham), and help(SpamN.eggs) all do the Right Thing, and the > symmetry of ham and eggs is perfectly obvious to the most casual > observer? > > Thanks, > Dan If if one of them is the canonical method name, you could define the other with a docstring indicating it is an alias for the other. If you don't want to spend code lines you can just define a helper function for that. Heck, you can even warn a DeprecationWarning if the alias is just backwards compatibility. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
On 22.08.2013 02:06, Ned Batchelder wrote: >> I cannot tell whether you are trolling or are just new to this, but >> you don't always have to use threads. You use threads when you need >> multiple parts of your program running concurrently. Don't inherit >> Thread if all you are doing is a simple object with state, nor if your >> program does not need concurrency. >> > I think it is safe to assume that Johannes meant, "when I use threads, I > never do it the way you suggested, I always derive from threading.Thread." Yup, that's what I was aiming for. Best regards, Johannes -- >> Wo hattest Du das Beben nochmal GENAU vorhergesagt? > Zumindest nicht öffentlich! Ah, der neueste und bis heute genialste Streich unsere großen Kosmologen: Die Geheim-Vorhersage. - Karl Kaos über Rüdiger Thomas in dsa -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
On 22.08.2013 00:50, Fábio Santos wrote: >>> That said, there is never a need for deriving >>> from the Thread class, you can also use it to run a function without >>> that. That way is IMHO clearer because the threading.Thread instance is >>> not the thread, just like a File instance is not a file. Both just >>> represent handles for manipulating the actual thing. >> >> Huh? That I find most curious. >> >> I *always* derive from threading.Thread and really like the way that >> thread setup works (instanciate Thread handle, call start). Very >> intuitive, never had the problems with clarity that you mentioned. Could >> you elaborate on your suggestion? I don't seem to quite get it I'm afraid. >> > I cannot tell whether you are trolling or are just new to this, Neither! > but you > don't always have to use threads. Obviously, I meant "I always derive from threading.Thread when I need to work with a thread". Thought this was blatantly obvious. That said, I think I also grossly misunderstood Ulrichs posting. He was talking about there no need deriving from threading.Thread when you don't need threads. What I understood was that, in order to use Threads, you could also just pass a closure to some static function of threading in order to fire up a thread. That may or may not be true. However, I find deriving from Thread, instanciating an object and firing up the thread by using ".start()" much more intuitive. Hope that clears it all up. Best regards, Johannes -- >> Wo hattest Du das Beben nochmal GENAU vorhergesagt? > Zumindest nicht öffentlich! Ah, der neueste und bis heute genialste Streich unsere großen Kosmologen: Die Geheim-Vorhersage. - Karl Kaos über Rüdiger Thomas in dsa -- http://mail.python.org/mailman/listinfo/python-list
Re: PEPs should be included with the documentation download
On Wednesday, August 21, 2013 11:25:44 PM UTC+5:30, rand...@fastmail.us wrote: > I think, though, that if there's any useful information that can be > obtained by reading accepted PEPs but not the documentation, or if > things are explained less clearly than in the PEPs, that's a bug in the > documentation, and should be remedied by adding to the documentation. PEP8 is referenced a lot but only a very small portion is included in the documentation (in the tutorial). I am a Python newbie and there may be other PEPs usually referenced which I might not be aware about. Maybe add selected PEPs to the documentation? I agree that adding rejected PEPs is no good but there may be PEPs worthy of addition to the documentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Query
On 22 Aug 2013 08:58, "chandan kumar" wrote: > > Hi all, > > Sorry for not explaining question properly.Here Its not about threading and dont worry about any indentations.Please see below example > > class Call_Constructor(): > def __init__(self): > print "In __init__ " > > class Test_Constructor(Call_Constructor): > def method(self): >print " In Test_Constructor Class" > > ConstructInstance = Test_Constructor() > > When an instace is created for Test_Constructor class ,The code flows starts __init__ in Call_Constructor class.Whys is it like that. > > > class Call_Constructor(): > def __init__(self): > print "In __init__ " > > > class Test_Constructor(Call_Constructor): > def __init__(self): >print " In Test_Constructor Class" > > ConstructInstance = Test_Constructor() > > But for the above case Code flows starts from Test_Constructor(). > > Whats is the difference for both cases described above. > > Best Regards, > Chandan. When creating an instance, Python will call __init__. In the first example there was only an __init__ method in the base class, so that one was used. On the second example, there were __init__ methods on both classes, but since you instantiated the subclass, the subclass's __init__ method was executed. Subclass methods have precedence over base class methods. If you want the __init__ method of the base class in the second example to be called, you can either remove the subclass __init__ method or call super(TestConstructor, self).__init__() in that method. That will call the base class's __init__. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEPs should be included with the documentation download
I do depend on offline documentation. I have both Python2 and 3's documentation offline. A lot of people have 24-hour access to internet but a lot of people don't have. And while moving around it isn't always possible to have internet then offline documentation is really helpful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using PyQT with QT Designer
On Wed, 21 Aug 2013 21:04:47 -0500, Michael Staggs wrote: > I'm learning Python and I have a problem. I've asked the question > everywhere > and no one helps me, so I'm hoping someone here will. I am making a > program > that shows album covers and you click on the album cover in the top > window. In > the bottom window, the list of songs appear and you can click the > individual > song to play it. It's going to be a media player for children. I'm > thinking > I'll be able to use a dict and have the album as the key and the list of > songs > as the value to accomplish this. > > Right now, I'm just using my picture directory to try and get the basic > layout > right. I designed a form in QT Designer: http://i.imgur.com/Wrp1zHW.png > > Here is my gui file I got from running pyuic4 on the ui file: > > > # -*- coding: utf-8 -*- > > # Form implementation generated from reading ui file 'window.ui' > # > # Created by: PyQt4 UI code generator 4.9.6 > # > # WARNING! All changes made in this file will be lost! > > from PyQt4 import QtCore, QtGui > > try: > _fromUtf8 = QtCore.QString.fromUtf8 > except AttributeError: > def _fromUtf8(s): > return s > > try: > _encoding = QtGui.QApplication.UnicodeUTF8 > def _translate(context, text, disambig): > return QtGui.QApplication.translate(context, text, disambig, > _encoding) > except AttributeError: > def _translate(context, text, disambig): > return QtGui.QApplication.translate(context, text, disambig) > > class Ui_MainWindow(object): > def setupUi(self, MainWindow): > MainWindow.setObjectName(_fromUtf8("MainWindow")) > MainWindow.resize(800, 600) > self.centralwidget = QtGui.QWidget(MainWindow) > self.centralwidget.setObjectName(_fromUtf8("centralwidget")) > self.tableWidget = QtGui.QTableWidget(self.centralwidget) > self.tableWidget.setGeometry(QtCore.QRect(70, 20, 661, 381)) > self.tableWidget.setObjectName(_fromUtf8("tableWidget")) > self.tableWidget.setColumnCount(0) > self.tableWidget.setRowCount(0) > self.listWidget = QtGui.QListWidget(self.centralwidget) > self.listWidget.setGeometry(QtCore.QRect(70, 400, 661, 181)) > self.listWidget.setObjectName(_fromUtf8("listWidget")) > MainWindow.setCentralWidget(self.centralwidget) > > self.retranslateUi(MainWindow) > QtCore.QMetaObject.connectSlotsByName(MainWindow) > > def retranslateUi(self, MainWindow): > MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", > None)) > > Now, according to websites I read, I should just have to add the following > to > my program to get it to use the form: > > from window import Ui_MainWindow > class MainWindow(QMainWindow, Ui_MainWindow): > def __init__(self, parent=None, **kwargs): > super(MainWindow, self).__init__(parent) > self.setupUi(self) > > and here is my program: > > from PyQt4.QtCore import * > from PyQt4.QtGui import * > from window import Ui_MainWindow > > THUMBNAIL_SIZE = 128 > SPACING= 10 > IMAGES_PER_ROW = 5 > > class TableWidget(QTableWidget): > def __init__(self, parent=None, **kwargs): > QTableWidget.__init__(self, parent, **kwargs) > > self.setIconSize(QSize(128,128)) > self.setColumnCount(IMAGES_PER_ROW) > self.setGridStyle(Qt.NoPen) > > # Set the default column width and hide the header > self.verticalHeader().setDefaultSectionSize(THUMBNAIL_SIZE+SPACING) > self.verticalHeader().hide() > > # Set the default row height and hide the header > self.horizontalHeader().setDefaultSectionSize(THUMBNAIL_SIZE+SPACING) > self.horizontalHeader().hide() > > # Set the table width to show all images without horizontal > scrolling > self.setMinimumWidth((THUMBNAIL_SIZE+SPACING)*IMAGES_PER_ROW+(SPACING*2)) > > def addPicture(self, row, col, picturePath): > item=QTableWidgetItem() > > # Scale the image by either height or width and then 'crop' it to > the > # desired size, this prevents distortion of the image. > p=QPixmap(picturePath) > if p.height()>p.width(): p=p.scaledToWidth(THUMBNAIL_SIZE) > else: p=p.scaledToHeight(THUMBNAIL_SIZE) > p=p.copy(0,0,THUMBNAIL_SIZE,THUMBNAIL_SIZE) > item.setIcon(QIcon(p)) > > self.setItem(row,col,item) > > class MainWindow(QMainWindow, Ui_MainWindow): > def __init__(self, parent=None, **kwargs): > super(MainWindow, self).__init__(parent) > self.setupUi(self) > > centralWidget=QWidget(self) > l=QVBoxLayout(centralWidget) > > self.tableWidget=TableWidget(self) > l.addWidget(self.tableWidget) > > self.setCentralWidget(centralWidget) >
Re: Basic Python Query
Hi all, Sorry for not explaining question properly.Here Its not about threading and dont worry about any indentations.Please see below example class Call_Constructor(): def __init__(self): print "In __init__ " class Test_Constructor(Call_Constructor): def method(self): print " In Test_Constructor Class" ConstructInstance = Test_Constructor() When an instace is created for Test_Constructor class ,The code flows starts __init__ in Call_Constructor class.Whys is it like that. class Call_Constructor(): def __init__(self): print "In __init__ " class Test_Constructor(Call_Constructor): def __init__(self): print " In Test_Constructor Class" ConstructInstance = Test_Constructor() But for the above case Code flows starts from Test_Constructor(). Whats is the difference for both cases described above. Best Regards, Chandan. On Thu, 22/8/13, Johannes Bauer wrote: Subject: Re: Basic Python Query To: python-list@python.org Date: Thursday, 22 August, 2013, 12:28 AM On 21.08.2013 11:11, Ulrich Eckhardt wrote: > That said, there is never a need for deriving > from the Thread class, you can also use it to run a function without > that. That way is IMHO clearer because the threading.Thread instance is > not the thread, just like a File instance is not a file. Both just > represent handles for manipulating the actual thing. Huh? That I find most curious. I *always* derive from threading.Thread and really like the way that thread setup works (instanciate Thread handle, call start). Very intuitive, never had the problems with clarity that you mentioned. Could you elaborate on your suggestion? I don't seem to quite get it I'm afraid. Best regards, Johannes -- >> Wo hattest Du das Beben nochmal GENAU vorhergesagt? > Zumindest nicht öffentlich! Ah, der neueste und bis heute genialste Streich unsere großen Kosmologen: Die Geheim-Vorhersage. - Karl Kaos über Rüdiger Thomas in dsa -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list