Re: lambda in list comprehension acting funny
Hi. funcs = [ lambda x: x**i for i in range( 5 ) ] print funcs[0]( 2 ) This gives me 16 When I was excepting 1 Does anyone know why? Just the way Python lambda expressions bind their variable references. Inner 'i' references the outer scope's 'i' variable and not its value 'at the time the lambda got defined'. And more importantly, what's the simplest way to achieve the latter? :) Try giving the lambda a default parameter (they get calculated and have their value stored at the time the lambda is defined) like this: funcs = [ lambda x, i=i: x**i for i in range( 5 ) ] Hope this helps. Best regards, Jurko Gospodnetić -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
>>> funcs = [ lambda x: x**i for i in range( 5 ) ] >>> print funcs[0]( 2 ) >>> >>> This gives me >>> 16 >>> >>> When I was excepting >>> 1 >>> >>> Does anyone know why? > >Just the way Python lambda expressions bind their variable > references. Inner 'i' references the outer scope's 'i' variable and not > its value 'at the time the lambda got defined'. > > >> And more importantly, what's the simplest way to achieve the latter? :) > >Try giving the lambda a default parameter (they get calculated and > have their value stored at the time the lambda is defined) like this: >funcs = [ lambda x, i=i: x**i for i in range( 5 ) ] Thanks a lot! I worked around it by def p(i): return lambda x: x**i funcs = [ p(i) for i in range(5) ] But your variant is nicer (matter of taste of course). Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter.event.widget: handler gets name instead of widget.
On Tue, 2012-07-10 at 18:06 -0700, Rick Johnson wrote:
> Also:
>
> Q3: Why are you explicitly setting the name of your "subFrame" widgets
> instead of allowing Tkinter to assign a unique name?...AND are you
> aware of the conflicts that can arise from such changes[1]?
>
I find custom-named widgets easier to work with during development. I can tell
what this is; ".main-frame.data-frame.title-hit-list.-10-". If I didn't assign
names it would look something line this:".2837029.283725.283762.2848308".
Once my program works I can drop custom-naming.
I understand that conflicts may arise if one assigns numeric names.
To find out whether the digits in the label names ('-10-' above) might
be implicated, I changed to spelled-out names ('ten'). The change had no
effect. The reference you list blow (x147-more-on-widget-names.htm)
indeed says "don't use names which only contain digits".
> Q4: Are you aware of the built-in function "enumerate"[2]? I see you
> are passing around indexes to iterables AND simultaneously needing the
> obj reference itself. I prefer to keep indexing to a minimum. If
> there is no bleeding edge performance issue to worry about (and there
> almost *always* never is) why not use enumerate?
>
Aware, yes. In the habit of, no. Thanks for the reminder.
> [1]
> http://www.pythonware.com/library/tkinter/introduction/x147-more-on-widget-names.htm
> [2] http://docs.python.org/release/3.0.1/library/functions.html#enumerate
Frederic
--
http://mail.python.org/mailman/listinfo/python-list
introduction and first question about multithreading
Greetings, My name is Vojta and I am blind student. I am slowly learning Python for about 4 years and I like it alot, mostly its ability to run on various platforms. My primary system is Ubuntu 12.04, but I have Windows XP at hand. I am using python 2.7. I have learned basics from the book A byte of Python (for version 2.X) and something from Dive into Python. But most things I learned by trial and error and thanks to solutions on stackoverflow.com. I Don't know much about good programming concepts in Python, just in general, so feel free to educate me about them. I haven't created anything great yet, but I am working on a game for blind people. It is a simple game of reaction, but I have to start with something, my next plan is Sudoku game. I am using Pygame for handling of sounds and keyboard events, speech dispatcher under Linux and pyttsx under Windows to provide speech output, numpy for sound cutting and my two little and simple modules for providing menu system and unified interface for both speech engines. During the development, I discovered, that I have to use multithreading to be able to check for key presses and manage the game at the same time. I tried threading module but this wasn't enough for me, because function running in the separate thread needed to access variables in the main thread at least I couldn't find the way how to do that. So I switched to multiprocessing and started using pipes for communication between processes. All is working well, except for one thing. My menu module uses a loop to check for keyboard events through pygame. I don't import pygame into my module directly, but rather pass it through my main module like this: menu.pygame = pygame All was working well until I started using multiprocessing. I may have a probable cause but I need your help. In my main module I am running a similar loop for checking keyboard input in separate process. When a player loses, the loop finishes and I join the process. Then the menu module kicks in and should launch its own loop checking for pygame keyboard events, but right after doing it it prints: [xcb] Unknown sequence number while processing queue [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called [xcb] Aborting, sorry about that. python: ../../src/xcb_io.c:273: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed received SigAbrt - core dumped Are atachments allowed here? I can send you my whole code. Please help me, if you can. Thank you very much, Vojta -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On 11/07/2012 2:41 AM, Daniel Fetchinson wrote: funcs = [ lambda x: x**i for i in range( 5 ) ] print funcs[0]( 2 ) print funcs[1]( 2 ) print funcs[2]( 2 ) This gives me 16 16 16 When I was excepting 1 2 4 Does anyone know why? Cheers, Daniel I don't understand why you would expect 1, 2, 4. Perhaps parentheses will help the order of evaluation: funcs = [(lambda x: x**i) for i in range( 5 )] This gives: 1 16 81 Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: introduction and first question about multithreading
In article , Vojt®Ãch Pol®¢â°ek wrote: > Then the menu module kicks in and should launch its > own loop checking for pygame keyboard events, but right after doing it > it prints: > [xcb] Unknown sequence number while processing queue > [xcb] Most likely this is a multi-threaded client and XInitThreads has > not been called > [xcb] Aborting, sorry about that. I googled for "Unknown sequence number while processing queue" and found: http://www.gtkforums.com/viewtopic.php?f=3&t=55708 sounds like it addresses your problem. -- http://mail.python.org/mailman/listinfo/python-list
ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator
I've held off announcing this until I was sure it was really stable; it's been 19 days since I made the last change to it, so here goes. PollyReports is my Python module for report generation. It is designed to be, quite literally, the "simplest thing that can possibly work" in the field of PDF generation from a database record set. There is a somewhat vague resemblance to GeraldoReports; I had problems with Geraldo's pagination which led me to develop PollyReports in a brief flurry of intense activity. It's on PyPI: http://pypi.python.org/pypi/PollyReports and on Github: https://github.com/Solomoriah/PollyReports and I have a blog where I talk about it (like anyone cares): http://opensource.gonnerman.org/?cat=4 Here's the README: PollyReports.py Copyright (c) 2012 Chris Gonnerman All Rights Reserved See the LICENSE file for more information. (Note: BSD licensed) - PollyReports.py provides a set of classes for database report writing. It assumes that you are using Reportlab to do PDF generation, but can work with any "canvas-like" object as desired. PollyReports provides the following framework for report generation: A Report object has a data source bound to it at instantiation. One or more Band objects (at least, a detail Band) must be added to it, and then the generate() method will be called to process the data source. The data source must be an iterator that produces objects that can be accessed via [] operations, meaning mainly dict, list, and tuple types, i.e. the most common types of records returned by standard database modules. The detail band is generated() once for each row. Band objects contain a list of Elements (generally at least one) which define how data from the row should be printed. An Element may print any normal data item or label and may be subclassed to handle other things like images. Generating a band in turn calls Element.generate() for each element, producing a list of Renderers with the first item in the list being the overall height of the band. The height is used to decide if the band will fit on the current page; if not, a new page will be created first. When the page is finally ready for the band, Renderer.render() will be called for each Renderer in the element list in order to actually render the data. As noted above, PollyReports expects a Reportlab-like canvas interface. The module has been kept as clean as possible, so that, though I don't actually recommend it, it would not be insane to say from PollyReports import * Importing only what you expect to use is still a better idea, of course. -- --- Chris Gonnerman Owner, New Century Computers Phone 660-213-3822 Fax 660-213-3339 -- http://mail.python.org/mailman/listinfo/python-list
[newbie] Python and Qt4 Designer
I'm trying to combine python-code made with QT4 designer with plain
python statements like
file = open("test","w")
Can anyone tell me what I have to add to the following code just to
open a file when clicking on the load-button and closing it by
clicking on the save button.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created: Wed Jul 11 17:21:35 2012
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(400, 300)
self.widget = QtGui.QWidget(Form)
self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25))
self.widget.setObjectName(_fromUtf8("widget"))
self.horizontalLayout = QtGui.QHBoxLayout(self.widget)
self.horizontalLayout.setMargin(0)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.pushButton_2 = QtGui.QPushButton(self.widget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.horizontalLayout.addWidget(self.pushButton_2)
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout.addWidget(self.pushButton)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form",
"Form", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton_2.setText(QtGui.QApplication.translate("Form",
"Save file", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("Form",
"Load file", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
thanks in advance
jean
--
http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Wed, Jul 11, 2012 at 4:28 AM, Colin J. Williams wrote: > I don't understand why you would expect 1, 2, 4. Because: funcs[0](2) == 2 ** 0 == 1 funcs[1](2) == 2 ** 1 == 2 funcs[2](2) == 2 ** 2 == 4 > Perhaps parentheses will help the order of evaluation: > > funcs = [(lambda x: x**i) for i in range( 5 )] > > This gives: > 1 > 16 > 81 No, that gives 16, 16, 16 just like the original. I don't understand why you would expect 1, 16, 81, unless you have misread the code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Opening multiple Files in Different Encoding
On Tuesday, July 10, 2012 11:16:08 PM UTC+5:30, Subhabrata wrote: > Dear Group, > > I kept a good number of files in a folder. Now I want to read all of > them. They are in different formats and different encoding. Using > listdir/glob.glob I am able to find the list but how to open/read or > process them for different encodings? > > If any one can help me out.I am using Python3.2 on Windows. > > Regards, > Subhabrata Banerjee. Dear Group, No generally I know the glob.glob or the encodings as I work lot on non-ASCII stuff, but I recently found an interesting issue, suppose there are .doc,.docx,.txt,.xls,.pdf files with different encodings. 1) First I have to determine on the fly the file type. 2) I can not assign encoding="..." whatever be the encoding I have to read it. Any idea. Thinking. Thanks in Advance, Regards, Subhabrata Banerjee. -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
Exactly. It's threads like these which remind me why I never use lambda. I would rather give a function an explicit name and adhere to the familiar Python syntax, despite the two extra lines of code. I don't even like the name "lambda". It doesn't tell you what it is (unless you're John McCarthy), a function that you won't re-use and so you don't really need to give it a persistent name. I haven't seen any lambdas in any Python library code, or in any of the third-party modules I use (numpy, matplotlib, Biopython). Do they exist? Because I have not been forced to do so, I haven't retained a space in the top drawer of my programming brain for lambda. I know the historical reason that Python ended up with lambda, it was requested by people in the Lisp community. While I appreciate some of the Lisp-like features which did find their way into Python (especially being able to treat code as data, and functions as objects), I've found that lambda does nothing for me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Opening multiple Files in Different Encoding
On 11 July 2012 19:15, wrote:
> On Tuesday, July 10, 2012 11:16:08 PM UTC+5:30, Subhabrata wrote:
> > Dear Group,
> >
> > I kept a good number of files in a folder. Now I want to read all of
> > them. They are in different formats and different encoding. Using
> > listdir/glob.glob I am able to find the list but how to open/read or
> > process them for different encodings?
> >
> > If any one can help me out.I am using Python3.2 on Windows.
> >
> > Regards,
> > Subhabrata Banerjee.
> Dear Group,
>
> No generally I know the glob.glob or the encodings as I work lot on
> non-ASCII stuff, but I recently found an interesting issue, suppose there
> are .doc,.docx,.txt,.xls,.pdf files with different encodings.
Some of the formats you have listed are not text-based. What do you mean by
the encoding of e.g. a .doc or .xls file?
My understanding is that these are binary files. You won't be able to read
them without the help of a special module (I don't know of one that can).
> 1) First I have to determine on the fly the file type.
> 2) I can not assign encoding="..." whatever be the encoding I have to read
> it.
>
Perhaps you just want to open the file as binary? The following will read
the contents of any file binary or text regardless of encoding or anything
else:
f = open('spreadsheet.xls', 'rb')
data = f.read() # returns binary data rather than text
>
> Any idea. Thinking.
>
> Thanks in Advance,
> Regards,
> Subhabrata Banerjee.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On 11/07/12 20:38:18, woooee wrote: > You should not be using lambda in this case > .for x in [2, 3]: > .funcs = [x**ctr for ctr in range( 5 )] > .for p in range(5): > .print x, funcs[p] > .print The list is called "funcs" because it is meant to contain functions. Your code does not put functions in the list, so it doesn't do what he wants. He could do: funcs = [] for i in range(5): def f(x): return x**i funcs.append(f) print funcs[0]( 2 ) print funcs[1]( 2 ) print funcs[2]( 2 ) and it will print 16, 16, 16 for the same reason as the lambda version. On the other hand, this does what he wants: funcs = [] for i in range(5): def f(x, i=i): return x**i funcs.append(f) print funcs[0]( 2 ) print funcs[1]( 2 ) print funcs[2]( 2 ) The lambda keyword is a red herring. The question is really about functions, and how they handle non-local variables. The good news is that 'lambda' and 'def' work exactly the same in that regards. So once you understand the finer points about 'def', you no longer have a reason to avoid 'lambda'. Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: Opening multiple Files in Different Encoding
On Wed, 11 Jul 2012 11:15:02 -0700, subhabangalore wrote:
> On Tuesday, July 10, 2012 11:16:08 PM UTC+5:30, Subhabrata wrote:
>> Dear Group,
>>
>> I kept a good number of files in a folder. Now I want to read all of
>> them. They are in different formats and different encoding. Using
>> listdir/glob.glob I am able to find the list but how to open/read or
>> process them for different encodings?
>>
>> If any one can help me out.I am using Python3.2 on Windows.
>>
>> Regards,
>> Subhabrata Banerjee.
> Dear Group,
>
> No generally I know the glob.glob or the encodings as I work lot on
> non-ASCII stuff, but I recently found an interesting issue, suppose
> there are .doc,.docx,.txt,.xls,.pdf files with different encodings.
You can have text files with different encodings, but not the others.
.doc .docx .xls and .pdf are all binary files. You don't specify an
encoding when you read them, because they aren't text -- encodings are
for mapping bytes to text, not bytes to binary formats.
In particular, .docx is compressed XML, so once you have uncompressed it,
the contents XML, which is *always* UTF-8.
> 1) First I have to determine on the fly the file type.
Which is a different problem from your first post.
On Windows, you determine the file type using the file extension.
import os
name, ext = os.path.splitext("my_file_name.bmp")
will give you ext = ".bmp".
Then what do you expect to do? You can open the file as a binary blob,
but what do you expect then?
f = open("my_file_name.bmp", "rb")
Now what do you want to do with it?
> 2) I can not assign
> encoding="..." whatever be the encoding I have to read it.
You can't set the encoding when you open files in binary mode, but binary
files don't have an encoding.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Wed, 11 Jul 2012 11:38:18 -0700, woooee wrote: > You should not be using lambda in this case > .for x in [2, 3]: > .funcs = [x**ctr for ctr in range( 5 )] > .for p in range(5): > .print x, funcs[p] > .print If you change the requirements, it's always easy to solve problems. But it is the wrong problem that you have solved. The problem we have been asked to solve is to create a sequence of function objects, so that they can be called later, when needed, *not* to pre-calculate the results. In this case, the most obvious solution is to store a local variable in each function object with the value you want. funcs = [(lambda x, i=i: x**i) for i in range(5)] creates a list of five functions: lambda x, i=0: x**i lambda x, i=1: x**i lambda x, i=2: x**i and so on. In this case, each function has two local variables, x and i, with i having a default value. The function parameter i is bound to the value of i when the function was created. Because parameter defaults are calculated once, when the function is created, this causes the value of i to stick to the newly created function, and we get the result we need. What happens if you don't use a parameter with a default value? funcs = [(lambda x: x**i) for i in range(5)] In this case, each function body contains one local variable, x, and one non-local or global variable, i. Because i is a non-local, the function doesn't store a value for it. Instead, the function stores a lump of data pointing to just enough of the environment to fetch the current value of the non-local i when needed. Since all five functions are in the same environment, they all see the same value of i when you call them, regardless of what the value of i was when they were created. This is little different from doing this: i = 1 def f1(x): return x**i i = 2 def f2(x): return x**i i = 3 def f3(x): return x**i Is there any surprise that all three functions return the same value? They all point to the same global variable i. I'm not sure what it is about lambda that fools people into thinking that it is different (I've even been fooled myself!) but it is not. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator
On 12/07/12 00:06, Chris Gonnerman wrote: I've held off announcing this until I was sure it was really stable; it's been 19 days since I made the last change to it, so here goes. PollyReports is my Python module for report generation. It is designed to be, quite literally, the "simplest thing that can possibly work" in the field of PDF generation from a database record set. There is a somewhat vague resemblance to GeraldoReports; I had problems with Geraldo's pagination which led me to develop PollyReports in a brief flurry of intense activity. It's on PyPI: http://pypi.python.org/pypi/PollyReports and on Github: https://github.com/Solomoriah/PollyReports and I have a blog where I talk about it (like anyone cares): http://opensource.gonnerman.org/?cat=4 "I've noticed that acceptance of a new software module or package for developers in the Open Source/Free Software world is greatly affected by the availability of a good tutorial. I mean, it seems obvious, doesn't it? But I've also noticed that the original author of a project rarely writes a good tutorial." http://packages.python.org/PollyReports/tutorial.html Well I thought it was a good tutorial. It certainly empowers me with enough confidence to give it a try. That said... with more than a passing interest in software and content licensing I looked at how the work was licensed. A none-standard license like this makes most people stop and think "will this be a problem if I use this in my work?" How compatible is your license with the main software licenses currently available? -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Pythonhttp://www.fossworkflowguides.com/scripting -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Wed, 11 Jul 2012 13:21:34 -0700, John Ladasky wrote:
> Exactly. It's threads like these which remind me why I never use
> lambda. I would rather give a function an explicit name and adhere to
> the familiar Python syntax, despite the two extra lines of code.
lambda is familiar Python syntax, or at least it should be if you
consider yourself an expert Python programmer.
And besides, this is not a problem with lambda. You get the *exact* same
problem with "ordinary" function definitions. Of course you do -- lambdas
*are* ordinary functions, they just have a more compact syntax.
funcs = []
for i in range(5):
def pwr(x):
return x**i
print("Testing 3**%d:" % i, pwr(3))
funcs.append(pwr)
for j in range(5):
print("Expected", 3**j, "got", funcs[j](3))
gives you *exactly* the same issue as with the lambda. This is not a
problem with lambdas, this is a scoping issue.
> I don't even like the name "lambda". It doesn't tell you what it is
Whereas "def" does?
If you can learn that "def" defines a function (as opposed to a class, a
module, or anything else really) than it's not that hard to learn that
"lambda" also defines a function.
Although I do wonder whether people would be less scared of lambda, and
less likely to imagine that it creates something with strange mysterious
properties different from "regular functions", if the keyword was called
"function" instead of lambda?
> (unless you're John McCarthy), a function that you won't re-use and so
> you don't really need to give it a persistent name.
Whether or not a function has a persistent name has nothing to do with
reuse. Anonymous functions can be reused. The driving motivation for
lambdas is for callback functions, which are frequently reused, but you
don't need or want to fill your global namespace up with potentially
hundreds of callback functions.
Lambda syntax is only incidentally good for saving a line or two. If the
only benefit of lambda was to save a line of code, that would be stupid.
The real reason for lambda is to avoid polluting your namespace with
unnecessary names.
Python allows us to easily and simply use anonymous strings, anonymous
ints, anonymous objects of all types. Why should functions be treated as
second-class?
> I haven't seen any lambdas in any Python library code, or in any of the
> third-party modules I use (numpy, matplotlib, Biopython). Do they
> exist? Because I have not been forced to do so, I haven't retained a
> space in the top drawer of my programming brain for lambda.
There are over 800 uses of lambda in the standard library:
[steve@ando ~]$ cd /usr/local/lib/python3.2
[steve@ando python3.2]$ grep lambda *.py */*.py | wc -l
829
(although some of the above are comments, doctests, etc.)
See, for example, configparser, decimal, functools, gettext, inspect,
pydoc, symtable, uuid, and others. pydoc and idlelib in particular make
heavy use of lambda, and the test suite is overflowing with them -- over
600 uses in total.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] Python and Qt4 Designer
On 11/07/12 17:37, Jean Dubois wrote:
> I'm trying to combine python-code made with QT4 designer with plain
> python statements like
> file = open("test","w")
> Can anyone tell me what I have to add to the following code just to
> open a file when clicking on the load-button and closing it by
> clicking on the save button.
>
> #!/usr/bin/env python
> # -*- coding: utf-8 -*-
>
> # Form implementation generated from reading ui file 'test.ui'
> #
> # Created: Wed Jul 11 17:21:35 2012
> # by: PyQt4 UI code generator 4.8.3
> #
> # WARNING! All changes made in this file will be lost!
>
> from PyQt4 import QtCore, QtGui
>
> try:
> _fromUtf8 = QtCore.QString.fromUtf8
> except AttributeError:
> _fromUtf8 = lambda s: s
>
> class Ui_Form(object):
> def setupUi(self, Form):
> Form.setObjectName(_fromUtf8("Form"))
> Form.resize(400, 300)
> self.widget = QtGui.QWidget(Form)
> self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25))
> self.widget.setObjectName(_fromUtf8("widget"))
> self.horizontalLayout = QtGui.QHBoxLayout(self.widget)
> self.horizontalLayout.setMargin(0)
>
> self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
> self.pushButton_2 = QtGui.QPushButton(self.widget)
> self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
> self.horizontalLayout.addWidget(self.pushButton_2)
> self.pushButton = QtGui.QPushButton(self.widget)
> self.pushButton.setObjectName(_fromUtf8("pushButton"))
> self.horizontalLayout.addWidget(self.pushButton)
>
> self.retranslateUi(Form)
> QtCore.QMetaObject.connectSlotsByName(Form)
>
> def retranslateUi(self, Form):
> Form.setWindowTitle(QtGui.QApplication.translate("Form",
> "Form", None, QtGui.QApplication.UnicodeUTF8))
> self.pushButton_2.setText(QtGui.QApplication.translate("Form",
> "Save file", None, QtGui.QApplication.UnicodeUTF8))
> self.pushButton.setText(QtGui.QApplication.translate("Form",
> "Load file", None, QtGui.QApplication.UnicodeUTF8))
>
>
> if __name__ == "__main__":
> import sys
> app = QtGui.QApplication(sys.argv)
> Form = QtGui.QWidget()
> ui = Ui_Form()
> ui.setupUi(Form)
> Form.show()
> sys.exit(app.exec_())
>
>
> thanks in advance
> jean
Connect the signal clicked of your's buttons to your's functions.
self.pushButton.clicked.connect(self.my_func)
Here's all the truth:
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_signals_slots.html
--
Vincent V.V.
Oqapy . Qarte+7
. PaQager
--
http://mail.python.org/mailman/listinfo/python-list
Automatic setup of meta path hooks?
Hi, I'm working on a meta path hook that performs compilation of C extension modules on import ( github.com/jwp/py-c ; pip install c ). It mostly works, but I'm having a hard time finding a standard way to automatically install the hook upon interpreter startup. I've thought about just having depending projects install the loader themselves, but I was hoping to make it seamless...Not to mention, there's the possibility of the case where the extension module is compiled and installed with setup.py. In which case, the loader isn't necessary, so it seems inappropriate to reference and install the meta path hook in an outer package module. Am I missing something? Is there some setuptools/distribute magicalawesome that I can use? -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
>> You should not be using lambda in this case >> .for x in [2, 3]: >> .funcs = [x**ctr for ctr in range( 5 )] >> .for p in range(5): >> .print x, funcs[p] >> .print > > If you change the requirements, it's always easy to solve problems. But > it is the wrong problem that you have solved. > > The problem we have been asked to solve is to create a sequence of > function objects, so that they can be called later, when needed, *not* to > pre-calculate the results. > > In this case, the most obvious solution is to store a local variable in > each function object with the value you want. > > funcs = [(lambda x, i=i: x**i) for i in range(5)] > > creates a list of five functions: > > lambda x, i=0: x**i > lambda x, i=1: x**i > lambda x, i=2: x**i > and so on. > > In this case, each function has two local variables, x and i, with i > having a default value. The function parameter i is bound to the value of > i when the function was created. > > Because parameter defaults are calculated once, when the function is > created, this causes the value of i to stick to the newly created > function, and we get the result we need. > > What happens if you don't use a parameter with a default value? > > funcs = [(lambda x: x**i) for i in range(5)] > > In this case, each function body contains one local variable, x, and one > non-local or global variable, i. > > Because i is a non-local, the function doesn't store a value for it. > Instead, the function stores a lump of data pointing to just enough of > the environment to fetch the current value of the non-local i when > needed. Since all five functions are in the same environment, they all > see the same value of i when you call them, regardless of what the value > of i was when they were created. > > This is little different from doing this: > > i = 1 > def f1(x): return x**i > > i = 2 > def f2(x): return x**i > > i = 3 > def f3(x): return x**i > > Is there any surprise that all three functions return the same value? > They all point to the same global variable i. I'm not sure what it is > about lambda that fools people into thinking that it is different (I've > even been fooled myself!) but it is not. Thank you Steve! Precise and clear, as always! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
ANN: Zeus - Windows IDE for Python
The latest Zeus IDE Version 3.97o is now available: http://www.zeusedit.com/python.html This latest Zeus release adds improved Python debugger support. Other Pyhon language features include syntax highlighting, code completion, smart indenting, class browsing and code folding. Zeus is also fully scriptable in Python. NOTE: Zeus is shareware, runs natively on the Windows platform and can be run on Linux using Wine. Jussi Jumppanen Author: Zeus Editor -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Thursday, July 12, 2012 12:34:33 AM UTC+8, Ian wrote: > On Wed, Jul 11, 2012 at 4:28 AM, Colin J. Williamswrote: > > I don't understand why you would expect 1, 2, 4. > > Because: > > funcs[0](2) == 2 ** 0 == 1 > funcs[1](2) == 2 ** 1 == 2 > funcs[2](2) == 2 ** 2 == 4 > > > Perhaps parentheses will help the order of evaluation: > > > > funcs = [(lambda x: x**i) for i in range( 5 )] > > > > This gives: > > 1 > > 16 > > 81 > > No, that gives 16, 16, 16 just like the original. I don't understand > why you would expect 1, 16, 81, unless you have misread the code. I'll contribute my way of python programming: def powerb(x, b): # return x**b One functor is enough! -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Wed, 11 Jul 2012 21:05:30 -0400, Dennis Lee Bieber wrote:
> {non sequitur: I still recall my archaic C++ class with the OOAD
> assignment of designing said calculator -- we never had to implement
> one, just design the basic classes/methods/attributes [on 3x5 cards] for
> a four-banger. I managed to persuade the team I was on that an RPN
> calculator would be simpler to (potentially) implement... And THEN
> persuaded them to NOT use the equivalent of an ALU class, but to put the
> math work into each operation button...
"ALU class"?
Googling gives me no clue.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Wed, 11 Jul 2012 20:39:45 -0700, 8 Dihedral wrote: > I'll contribute my way of python programming: > > def powerb(x, b): # > return x**b Here's a shorter version: py> pow > One functor is enough! Nothing we have been discussing in this thread has been a functor, either in the Haskell sense or the C++ sense. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Wed, 11 Jul 2012 08:41:57 +0200, Daniel Fetchinson wrote: > funcs = [ lambda x: x**i for i in range( 5 ) ] Here's another solution: from functools import partial funcs = [partial(lambda i, x: x**i, i) for i in range(5)] Notice that the arguments i and x are defined in the opposite order. That's because partial only applies positional arguments from the left. If there was a "right partial" that applies from the right, we could use the built-in instead: funcs = [rpartial(pow, i) for i in range(5)] -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On 7/11/2012 11:53 PM, Steven D'Aprano wrote:
On Wed, 11 Jul 2012 21:05:30 -0400, Dennis Lee Bieber wrote:
{non sequitur: I still recall my archaic C++ class with the OOAD
assignment of designing said calculator -- we never had to implement
one, just design the basic classes/methods/attributes [on 3x5 cards] for
a four-banger. I managed to persuade the team I was on that an RPN
calculator would be simpler to (potentially) implement... And THEN
persuaded them to NOT use the equivalent of an ALU class, but to put the
math work into each operation button...
"ALU class"?
Googling gives me no clue.
4th hit: Arithmetic Logic Unit (hardware) -- Wikipedia
ALU class -- software version or simulation thereof.
The hardware version of Dennis's distributed design would be
interesting. Spreadsheets are based in part on the same idea of
distributed logic and arithmetic.
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Thursday, July 12, 2012 11:51:04 AM UTC+8, Steven D'Aprano wrote: > On Wed, 11 Jul 2012 20:39:45 -0700, 8 Dihedral wrote: > > > I'll contribute my way of python programming: > > > > def powerb(x, b): # > > return x**b > > Here's a shorter version: > > py> pow >> > > > One functor is enough! > > Nothing we have been discussing in this thread has been a functor, either > in the Haskell sense or the C++ sense. > > > > -- > Steven Well, I encountered this kind of problems before in OOP. I have to make sure my functor to keep the state variable values for different objects that call the same functor to behave correctly in order to avoid passing extra parameters in various objects using the same functor. -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Wed, 11 Jul 2012 13:21:34 -0700 (PDT) John Ladasky wrote: > Exactly. It's threads like these which remind me why I never use lambda. I > would rather give a function an explicit name and adhere to the familiar > Python syntax, despite the two extra lines of code. I don't even like the > name "lambda". It doesn't tell you what it is (unless you're John McCarthy), > a function that you won't re-use and so you don't really need to give it a > persistent name. > > I haven't seen any lambdas in any Python library code, or in any of the > third-party modules I use (numpy, matplotlib, Biopython). Do they exist? > Because I have not been forced to do so, I haven't retained a space in the > top drawer of my programming brain for lambda. [...] +1 about the name, -1 about the usefulness. For example it's a clear and concise way to pass a key argument to min, max, sort and friends: sort(seq, key=lambda x: x.a) The alternative is to have trivial function definitions floating around the namespace which readers of the code have to search for. -- John -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator
On Thu, 12 Jul 2012 10:41:52 +1000 Simon Cropper wrote: > That said... with more than a passing interest in software and > content licensing I looked at how the work was licensed. A > none-standard license like this makes most people stop and think > "will this be a problem if I use this in my work?" How compatible is > your license with the main software licenses currently available? Do you mean this license?: http://packages.python.org/PollyReports/license.html It's the standard license for NetBSD projects and approved by OSI: http://www.opensource.org/licenses/bsd-license.php and GPL-compatible: http://www.gnu.org/licenses/license-list.html#FreeBSD Bye, Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
On Wed, 11 Jul 2012 22:04:51 -0700, 8 Dihedral wrote: > I have to make sure my functor to keep the state variable values for > different objects that call the same functor to behave correctly in > order to avoid passing extra parameters in various objects using the > same functor. Yo dawg, I heard you liked functors, so I put a functor in your functor so you can train your markov chains with extra functor parameters to functor objects that are functor factory decorator functors. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Qt4 Designer
On 12 jul, 02:59, Vincent Vande Vyvre
wrote:
> On 11/07/12 17:37, Jean Dubois wrote:
>
>
>
>
>
>
>
> > I'm trying to combine python-code made with QT4 designer with plain
> > python statements like
> > file = open("test","w")
> > Can anyone tell me what I have to add to the following code just to
> > open a file when clicking on the load-button and closing it by
> > clicking on the save button.
>
> > #!/usr/bin/env python
> > # -*- coding: utf-8 -*-
>
> > # Form implementation generated from reading ui file 'test.ui'
> > #
> > # Created: Wed Jul 11 17:21:35 2012
> > # by: PyQt4 UI code generator 4.8.3
> > #
> > # WARNING! All changes made in this file will be lost!
>
> > from PyQt4 import QtCore, QtGui
>
> > try:
> > _fromUtf8 = QtCore.QString.fromUtf8
> > except AttributeError:
> > _fromUtf8 = lambda s: s
>
> > class Ui_Form(object):
> > def setupUi(self, Form):
> > Form.setObjectName(_fromUtf8("Form"))
> > Form.resize(400, 300)
> > self.widget = QtGui.QWidget(Form)
> > self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25))
> > self.widget.setObjectName(_fromUtf8("widget"))
> > self.horizontalLayout = QtGui.QHBoxLayout(self.widget)
> > self.horizontalLayout.setMargin(0)
>
> > self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
> > self.pushButton_2 = QtGui.QPushButton(self.widget)
> > self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
> > self.horizontalLayout.addWidget(self.pushButton_2)
> > self.pushButton = QtGui.QPushButton(self.widget)
> > self.pushButton.setObjectName(_fromUtf8("pushButton"))
> > self.horizontalLayout.addWidget(self.pushButton)
>
> > self.retranslateUi(Form)
> > QtCore.QMetaObject.connectSlotsByName(Form)
>
> > def retranslateUi(self, Form):
> > Form.setWindowTitle(QtGui.QApplication.translate("Form",
> > "Form", None, QtGui.QApplication.UnicodeUTF8))
> > self.pushButton_2.setText(QtGui.QApplication.translate("Form",
> > "Save file", None, QtGui.QApplication.UnicodeUTF8))
> > self.pushButton.setText(QtGui.QApplication.translate("Form",
> > "Load file", None, QtGui.QApplication.UnicodeUTF8))
>
> > if __name__ == "__main__":
> > import sys
> > app = QtGui.QApplication(sys.argv)
> > Form = QtGui.QWidget()
> > ui = Ui_Form()
> > ui.setupUi(Form)
> > Form.show()
> > sys.exit(app.exec_())
>
> > thanks in advance
> > jean
>
> Connect the signal clicked of your's buttons to your's functions.
>
> self.pushButton.clicked.connect(self.my_func)
>
> Here's all the truth:
>
> http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_...
>
> --
> Vincent V.V.
> Oqapy . Qarte+7
> . PaQager
thanks for the reference, could you just supply a small example for
the code above to get me started?
thanks in advance
jean
--
http://mail.python.org/mailman/listinfo/python-list
Re: lambda in list comprehension acting funny
In article , Daniel Fetchinson wrote: > > funcs = [ lambda x: x**i for i in range( 5 ) ] > > print funcs[0]( 2 ) > > print funcs[1]( 2 ) > > print funcs[2]( 2 ) > > > > This gives me > > > > 16 > > 16 > > 16 > > > > When I was excepting > > > > 1 > > 2 > > 4 > > > > Does anyone know why? In Python 3.x : funcs = [lambda x: x**i for i in range(5)] list(map(lambda f: f(2),funcs)) --> [16, 16, 16, 16, 16] Ooops, cool semantics :-) In Racket Scheme (http://racket-lang.org), they seem to know lambdas : #lang racket ;;; quick and dirty list comprehension syntax as a macro, for fun : (define-syntax-rule (list-of expr for x in L) (map (lambda (x) expr) L)) (list-of (sqr x) for x in (range 5)) --> (0 1 4 9 16) (define funcs (list-of (lambda (x) (expt x i)) for i in (range 5))) (map (lambda (f) (f 2)) funcs) --> (1 2 4 8 16) franck -- http://mail.python.org/mailman/listinfo/python-list
