Re: __getattribute__ meta class?
Carl Banks [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Feb 27, 12:44 am, bambam [EMAIL PROTECTED] wrote: In retrospect, the project has three parts: remove side effects, push side effects to a common location, modify code so that changes only affect areas that encapsulate side effects. This code allows top level code to pretend that the intermediate code has not changed. Gah. Libraries that helpfully do things on behalf of the user strike again, and the mess bambam posted is what you have to do to disable these helpful effects. I'll grant that it's possible that the library wasn't trying to be helpful and was just indicriminately letting side effects loose. Shame on the writer in any case. Carl Banks (smile). The hardware has been implemented in a conversational style: you ask a question, something happens, you get a response. It's only when you try the conversational style in a lecture theatre that you realise the constraints. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattribute__ meta class?
Thank you both. If I understand correctly, I have two new ways to creating my new classes: class _Communicate(commandset2.CommandSet_Communicate): __metaclass__ = My_meta or _Communicate = create_wrapper_class |('_Communicate',commandset2.CommandSet_Communicate) and also two new ways to check for callable methods :~) hasattr(attr,__call__) or inspect.isfunction(attr) Gerard points out that I can re-define the callable methods instead of using dynamic over-ride at each method call. It's left as an exercise for the reader to determine the behaviour of derived classes :~) Carl points out that unless the methods are required to be static methods, I can use a wrapper function from the parent object, instead of a wrapper function from the parent class. And I can use a variable for my wrapper_function base class: self, or self.parent Two new words are introduced: 'type' and 'super'. ...That part is still opaque to me... I also don't know why the example meta class is derived from 'type'. The project is to interchangeably replace an object with a similar group of objects. The original project was not built with this in mind: there is no-one here qualified to design that kind of project. So I'm retrofitting the original model by modification. Successive attempts have involved more and more complex modifications. In retrospect, the project has three parts: remove side effects, push side effects to a common location, modify code so that changes only affect areas that encapsulate side effects. This code allows top level code to pretend that the intermediate code has not changed. regards (david) bambam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have a class containing a series of classes like this: class Th(Externaldevice): class _Communicate(commandset2.CommandSet_Communicate): def __getattribute__(self,attrname): attr = commandset2.CommandSet_Communicate.__getattribute__(self,attrname) if __call__ in dir(attr): return functools.partial(Th._wrapper_function, self.parent, attr) else: return attr class _System(commandset2.CommandSet_System): def __getattribute__(self,attrname): attr = commandset2.System_Communicate.__getattribute__(self,attrname) if __call__ in dir(attr): return functools.partial(Th._wrapper_function, self.parent, attr) else: return attr That is, a a wrapper function is applied to a bunch of methods in a bunch of classes. The class declarations are simple, but even so, repetitive. Can anyone suggest a more compact representation for the class declarations? Also, because the parent class name is given explicitly in the class declarations, I can't over-ride the _wrapper_function in a child class, except by over-riding each of the class declarations. Is there a way to reference the _wrapper_function just to the containing class? Steve -- http://mail.python.org/mailman/listinfo/python-list
exchange service side rules
Junk E-Mail Options, Protection is set to High. All of my messages are coming through with a SCL of 9 (I checked), but none of them are going to the Junk E-Mail folder. I thought this was a server-side rule? Can anyone explain, and also tell me what I need to do? -- http://mail.python.org/mailman/listinfo/python-list
__getattribute__ meta class?
I have a class containing a series of classes like this: class Th(Externaldevice): class _Communicate(commandset2.CommandSet_Communicate): def __getattribute__(self,attrname): attr = commandset2.CommandSet_Communicate.__getattribute__(self,attrname) if __call__ in dir(attr): return functools.partial(Th._wrapper_function, self.parent, attr) else: return attr class _System(commandset2.CommandSet_System): def __getattribute__(self,attrname): attr = commandset2.System_Communicate.__getattribute__(self,attrname) if __call__ in dir(attr): return functools.partial(Th._wrapper_function, self.parent, attr) else: return attr That is, a a wrapper function is applied to a bunch of methods in a bunch of classes. The class declarations are simple, but even so, repetitive. Can anyone suggest a more compact representation for the class declarations? Also, because the parent class name is given explicitly in the class declarations, I can't over-ride the _wrapper_function in a child class, except by over-riding each of the class declarations. Is there a way to reference the _wrapper_function just to the containing class? Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: exchange service side rules
Wrong message, wrong group. Sorry. bambam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Junk E-Mail Options, Protection is set to High. All of my messages are coming through with a SCL of 9 (I checked), but none of them are going to the Junk E-Mail folder. I thought this was a server-side rule? Can anyone explain, and also tell me what I need to do? -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question, function returning object.
Second try (correction) I started with ths: -- def open_pipe(): pipe=PIPE() print pipe return pipe pipe=open_pipe() pipe.parent = self.parent print pipe -- It didn't do what I wanted: when I printed the pipe the second time it was not the same object as the first time. So I changed it to this: def open_pipe(pipe): pipe=PIPE() print pipe pipe = None open_pipe(pipe) pipe.parent = self.parent print pipe It still doesn't do what I wanted: I can't assign the parent property because pipe type is None. I'm not sure enough of what I am doing to tell if I have another error in my code causing the problem. Is either of these examples supposed to work as shown? Is it clear that either example is obviously wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner question, function returning object.
Thank you. So example 2 was clearly wrong, and example 1 was not clear :~). pipe is a serial port object: when I print pipe it shows first that it is connected to port 5, then that it is connected to port 6. I'll discard the clearly wrong code, and concentrate on the unclear code: probably by the time I have clarified the problem, the solution will also be clear. Thanks again.. -- http://mail.python.org/mailman/listinfo/python-list
beginner question, function returning object.
I started with ths: -- def open_pipe(): pipe=PIPE() print pipe return pipe pipe=open_pipe() pipe.parent = self.parent print pipe -- It didn't do what I wanted: when I printed the pipe the second time it was not the same object as the first time. So I changed it to this: def open_pipe(): pipe=PIPE() print pipe return pipe pipe = None pipe=open_pipe(pipe) pipe.parent = self.parent print pipe It still doesn't do what I wanted: I can't assign the parent property because pipe type is None. I'm not sure enough of what I am doing to tell if I have another error in my code causing the problem. Is either of these examples supposed to work as shown? Is it clear that either example is obviously wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie design question
Original languages were line oriented, newer languages were block oriented. Original languages has line comments. Newer languages had block comments, and had line comments added back in. So I would read that as line comments being more fundamental, but people who used line comments got so sick of them that they thought block comments would be a good idea. (david) [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I've designed a language, Decaf, for beginners. I've got block comments but not multi-line strings. If you can only have one or the other, which is more helpful? Should I have both? (Make a strong argument here: my design principal is, Designed by a backpacker: when in doubt, leave it out.) -- http://mail.python.org/mailman/listinfo/python-list
programming container object
I wish to create a generic container object, devlist, such that devlist.method(arguments) runs as for each dev in devlist.pool: dev.method(arguments) and s = devlist.method(arguments) runs as for each dev in devlist.pool: s.append(dev.method(arguments)) ...but it is outside my ability to do so. Can anyone provide an example of how to do that? Thanks, Steve -- http://mail.python.org/mailman/listinfo/python-list
basic threading question
Are function variables thread safe? def f(a): # whatever return float(a) Is that OK? def f(a): #whatever b=a: #whatever: return float(b) Is that OK? Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: Static variable vs Class variable
Steven D'Aprano [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Wed, 17 Oct 2007 13:41:06 +0200, Hrvoje Niksic wrote: The current implementation of += uses __add__ for addition and __iadd__ for addition that may or may not be in-place. I'd like to know the rationale for that design. Everything you need is in the PEP: http://www.python.org/dev/peps/pep-0203/ -- Steven. Which illustrates that the proposal, while simplified for implementation, is not exactly what was desired* is both more readable and less error prone, because it is instantly obvious to the reader that it is x that is being changed, and not x that is being replaced As we see from this thread, it is not instantly obvious to the reader; the meaning of changed, not replaced is ambiguous. [david] * That is, unless ambiguity was the desideratum -- http://mail.python.org/mailman/listinfo/python-list
function to do dynamic import?
import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global) scope. Questions: (1) Where can I read an explanation of this? (2) Is there a work around? BTW, sys.modules(filename) shows that the module is loaded, I just don't know how to use it when loaded that way. Also, if I import again at the global scope, the module name becomes available. Steve. --- def gim(): ... exec import gamel ... gim() sys.modules[gamel] module 'gamel' from 'c:\gamel.pyc' gamel NameError: name 'gamel' is not defined exec import gamel gamel module 'gamel' from 'c:\gamel.pyc' -- http://mail.python.org/mailman/listinfo/python-list
Re: function to do dynamic import?
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Sep 10, 10:52 pm, bambam [EMAIL PROTECTED] wrote: import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global) scope. Questions: (1) Where can I read an explanation of this? (2) Is there a work around? BTW, sys.modules(filename) shows that the module is loaded, I just don't know how to use it when loaded that way. Also, if I import again at the global scope, the module name becomes available. Steve. (snipped) This was recently discussed: http://groups.google.com/group/comp.lang.python/msg/f6fcdf49710cb833 -- Hope this helps, Steven def gim(): exec global gamel exec import gamel Unfortunately, does not have the desired effect. Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: function to do dynamic import?
J. Cliff Dyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam wrote: import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global) scope. Questions: (1) Where can I read an explanation of this? (2) Is there a work around? BTW, sys.modules(filename) shows that the module is loaded, I just don't know how to use it when loaded that way. Also, if I import again at the global scope, the module name becomes available. Steve. --- def gim(): ... exec import gamel ... All you have done in this function is bind the module to the name gamel within the scope of the function. As soon as the function exits, the module goes out of scope. If you want to use it externally, return the module. def: gim(): import gamel return gamel gim() This will have to change to gamel = gim() and the rest should work as expected. sys.modules[gamel] module 'gamel' from 'c:\gamel.pyc' gamel NameError: name 'gamel' is not defined exec import gamel gamel module 'gamel' from 'c:\gamel.pyc' def: gim(): import gamel return gamel Unfortunately, it needs to do dynamic import: I can't list all of the possible import modules because they are unknown until runtime. Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: function to do dynamic import?
Steve Holden [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam wrote: import works in the main section of the module, but does not work as I hoped when run inside a function. That is, the modules import correctly, but are not visible to the enclosing (global) scope. Questions: (1) Where can I read an explanation of this? (2) Is there a work around? BTW, sys.modules(filename) shows that the module is loaded, I just don't know how to use it when loaded that way. Also, if I import again at the global scope, the module name becomes available. There's not much wrong with doing this, since it gives you the best of both worlds. But you mean sys.modules[filename], don't you? def gim(): ... exec import gamel ... gim() sys.modules[gamel] module 'gamel' from 'c:\gamel.pyc' gamel NameError: name 'gamel' is not defined exec import gamel gamel module 'gamel' from 'c:\gamel.pyc' Whoa there! There's a lot of difference between importing a module inside a function and executing an import statement inside a function. If you want to do dynamic imports then the __import__ function is what you need. Trying to use exec like that is a bad idea unless you clearly understand the relationship between the different namespaces involved. In fact, trying to use exec at all is a bad idea until you understand Python better, and even then it's not often a terrific idea. Think of exec more as a hack of last resort than the first tool to reach for to solve a problem. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - Yes, sys.modules[filename], unfortunately, same mistake made already 4 or 5 times before I typed this, and still hadn't learned...many years working in an environment where the distinction was not important. Sorry. def gim(self): for gamel in self.gamel_list: __import__(gamel['file']) Works as hoped for. I did a web search for 'dynamic import' and the only examples I found used exec. Thanks Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
I have a number of news readers here, but all of them work better with top-posting, and in none of them is top posting a problem. What software are you using? Steve. Lawrence D'Oliveiro [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] In message [EMAIL PROTECTED], bambam wrote: Thank you, Don't top-post. -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
Removing from a list while you iterate will had quadratic performance Anecdote: I was doing a route-finding program for a railway ticketing system. My replacement explained to my boss that it couldn't be done: the problem was one of that class of problems that has no good optimum solution. My replacement told me this while we were doing the hand-over. I told him that the route-finding optimiser was already complete. It did a search of possible routes over the 3 loops, 15 branches and 75 stations in less time than it took to redraw the screen, and that was without even bothering to recode the tail recursion. In my present case, the lists I am working with have ~10 elements. Defined behaviour, even if it was inapropriate for my needs, would be welcome. Language enhancement that make the code clearer and easier would be welcome. Optimisers for large sets I could continue to do by other means. Raw cPython is probably not a good choice for real-time signal processing, but that's not what I am doing. O(n) to find the element you wish to remove and move over everything after it, Is that how lists are stored in cPython? It seems unlikely? Steve. Rhamphoryncus [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Sep 6, 1:56 pm, Karthik Gurusamy [EMAIL PROTECTED] wrote: That said, it may be a good future language enhancement to define a reasonable consistent behavior for an iterator over a changing collection. This occurs quite common when we walk a collection and usually delete the current item. -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
I'm testing a series of scripts. The scripts are testing a series of hardware devices. The scripts are a sequence of device commands. The scripts have sequence numbers. I am adding exception handling to the to the 'inner platform' that executes sequences. I am doing this because testing of error cases has demonstrated that the 'inner platform' is fragile. http://worsethanfailure.com/Articles/The_Inner-Platform_Effect.aspx on the other hand: http://www.amazon.com/gp/cdp/member-reviews/A2M9XZ2UD8ZM40?ie=UTF8display=publicsort_by=MostRecentReviewpage=5 and http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/207645 In any case, the hardware test instruments are not programmable in python, and most of them do not have loop constructs in the platform language. I'm not sure how you are reading these messages. Can you see the thread history? Steve. Steven D'Aprano [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Fri, 07 Sep 2007 12:03:26 +1000, bambam wrote: Hi Steven. Looking at your code, why are you naming the value __all__? It looks like a built-in variable? When you say: from module import * Python looks in the module for a list of names called __all__, and imports only the names in that list. It is recommended that your modules take advantage of that feature. I'm just using the same name. Unless there is an automatic way to correctly get the function list, I will probably be better off giving the lines sequence numbers, and generating the function list from that. I don't understand what you mean by giving the lines sequence numbers. Where do they come from? How do you go from sequence numbers to functions? As far as I am concerned, the right behavior is for the module containing the functions to define which functions need to be tested. Since modules aren't actually intelligent, that means some person needs to list the functions. Why list the function NAME when you can list the function itself? -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
I can try that, but I'm not sure that it will work. The problem is that devList is just a pointer to a list owned by someone else. Making devList point to a new list won't work: I need to make the parent list different. I could do this by adding an extra level of indirection, but I think at the risk making the call environment more complex. Still, the main thing is that I hadn't even thought of doing it that way. Thank you, Steve. Lawrence D'Oliveiro [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] In message [EMAIL PROTECTED], bambam wrote: The devices are in a list, and are removed by using pop(i). This messes up the loop iteration, so it is actually done by setting a flag on each device in the exception handler, with ANOTHER loop after each write/read/calculate sequence. Why not just build a new list? E.g. newdevs = [] for dev in devs : ... if not removing_dev : newdevs.append(dev) #end if #end for devs = newdevs -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
Hi Steven. Looking at your code, why are you naming the value __all__? It looks like a built-in variable? Unless there is an automatic way to correctly get the function list, I will probably be better off giving the lines sequence numbers, and generating the function list from that. Steve. Steven D'Aprano [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Thu, 06 Sep 2007 15:44:57 +1000, bambam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Try something like this: define a module holding the device functions. # module script __all__ = [a0010, a002, a0030, a0040, a0050] ... # module test1 import script class Test1(pl_test.Pl_test) ADC calibration and Battery Voltage calibration def run(self,devlist): for line in script.__all__: for self.dev in devlist if self.dev.active and not self.dev.failed try line(self) except Exception,e: print e self.dev.active=False print The following devices passed: for dev in devlist if dev.active and not dev.failed print dev print The following devices need to be re-tested for dev in devlist if not dev.active print dev print The remaining devices failed for dev in delist if dev.active and dev.failed print dev -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
concise code (beginner)
I have about 30 pages (10 * 3 pages each) of code like this (following). Can anyone suggest a more compact way to code the exception handling? If there is an exception, I need to continue the loop, and continue the list. Steve. --- for dev in devs try: dev.read1() except print exception remove dev from devs for dev in devs try: dev.read2() except print exception remove dev from devs for dev in devs try: dev.read3() except print exception remove dev from devs etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
First, thank you. All of the suggestions match what we want to do much better than what we are doing. We have a script, written in python, which is doing testing. But the python script doesn't look anything like the test script, because the python script is written in python, and the test script is a series of instrument command macros. By putting the script sequence into a collection that is separate from the python code, we will get script list that general engineering will find much easier to understand: def script(self) def a0010(): global self; self.power_on([self.dev]); def a0020(): global self; self.dev.addLog([self.name, ' started']); def a0030(): global self; self.resetMinuteReg([self.dev]); def a0040(): global self; self.disablePLmessages([self.dev]); def a0050(): global self; self.dev.testH.writePLram((PL.BCAL128)); Most of these won't generate exceptions: exceptions are expected only on the calculations following the reads, but of course the problem is that the exceptions are unexpected... The semi-colons were already there, I've just stripped out the loops and exception handlers. The original code is a mixture of functions with internal and external [dev] loops. Because of the sequence names, I have a choice of using generated call names (James), or a static list of some sort. Other possibilities might be 1) Using dir(script) to get a list of line functions 2) Using frame.f_lineno instead of line functions 3) Use an expression list instead of line functions 4) Multiple script objects with yield on each line. The devices are in a list, and are removed by using pop(i). This messes up the loop iteration, so it is actually done by setting a flag on each device in the exception handler, with ANOTHER loop after each write/read/calculate sequence. I left that out also because I wanted to show the intended logic. I'm not wedded to the idea of using sequence numbers for line functions. Comments are welcome. Sorry I didn't include this level of detail in the original, but I am interested in the question at all levels. Note that this achieves synchronous parallel processing -- another area I know nothing about -- but I'm just starting with the code as I got it, and coding so far was focused on hardware integration. Steve. bambam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have about 30 pages (10 * 3 pages each) of code like this (following). Can anyone suggest a more compact way to code the exception handling? If there is an exception, I need to continue the loop, and continue the list. Steve. --- for dev in devs try: dev.read1() except print exception remove dev from devs for dev in devs try: dev.read2() except print exception remove dev from devs for dev in devs try: dev.read3() except print exception remove dev from devs etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idomatic python 2
Thank you. I'm glad to see that I don't need to choose between two opposing viewpoints :~) Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idomatic python 2
Bruno Desthuilliers [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] As a side note, in Python, inheritance ... ... should usually not be used for typing. :~( I'm sorry, I don't even know what that means... The code I have inherited from someone only a little more knowledgeable than me, and is still full of development artifacts anyway. The Pwr and Psp classes inherit from the Device class not neccessarily because that is a Good Thing, more because the development process led to them being thought of that way. All devices have a mixture of common and differing attributes. What is 'typing'? Steve. -- http://mail.python.org/mailman/listinfo/python-list
Re: Co-developers wanted: document markup language
virtually the only ones that feel the need to rub our nationality into I'd always assumed (I never spent much time) that Germans were another culture that had the habit of greeting groups on entrance. Australians, English, and most of North America just don't have that habit. Steve. Wildemar Wildenburger [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Torsten Bronger wrote: Hallöchen! Yes, you're German. Have you ever noticed that (we) Germans are virtually the only ones that feel the need to rub our nationality into everyones faces? ;) Paul Rubin writes TeX/LateX have been around forever and are well established standards, as awful as they are. Why do we want ANOTHER markup language? Well, because they are awful. ;-) I don't see that there is a bunch of already existing projects, in fact, I don't see anyone challenging LaTeX at all. However, competition is a good thing, and I think there are enough aspects about LaTeX that can be done better so that this project is worth being done. Well there is ConTeXt URL:http://wiki.contextgarden.net/. I've never actually used it, but from reading the docs I deem it a very attractive alternative to LaTeX. /W -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
That looks good, and perhaps a difference operator would be too simple to be useful anyway. Steve. Mikael Olofsson [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam wrote: In this case it doesn't matter - my lists don't contain duplicate elements this time - but I have worked with lists in money market and in inventory, and finding the intersection and difference for matching off and netting out are standard operations. I would use a list comprehension for that case: A = ['a','b','c','a','c','d'] U = ['a','b','e'] B = [x for x in A if x in U] The result would be B==['a','b','a'] /MiO -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
c = sorted(set(a)-set(b)) although for me :~( that is another step more obscure than c = list(set(a)-set(b)) c.sort() Bags don't seem to be built in to my copy of Python, and although I'm interested in why lists don't support the difference operation, I don't want to get away from standard Python. Steve. Scott David Daniels [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam wrote: The reason that lists don't have set-like methods is because lists aren't sets -- lists can contain duplicate elements and they are ordered. I'd have used sets if I was sure you meant [1,2,3] to mean the same thing as [3,1,2] and no duplicates. Interesting point -- if that's all there is in it, then lists should have difference and intersection methods. Not because they are the same as sets -- because they are slightly different than sets. In this case it doesn't matter - my lists don't contain duplicate elements this time - but I have worked with lists in money market and in inventory, and finding the intersection and difference for matching off and netting out are standard operations. Here you seem to be talking about multisets (also called bags). They have more fully defined algebraic properties analogous to sets. bag([1,2,3,3,4]) == bag([3,1,2,4,3]) != bag([1,2,3,4]) bag([1,2,2,3]) - bag([1,2]) == bag([2,3]) bag([1,2,3]) - bag([3,4]) == bag([1]) Excellent. By symmetry, I see that list casts the set back into a list. Some will say 'sorted' is a better conversion of a set to list, since the result is well-defined. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Ok, many environments are capable of cached evaluation of functions without variable parameters so range(5) is cached, but range(v) is re-evaluated every time. Is this defined behaviour? That is, is it defined what Python does for for i in f() I'm sure it must be, but I haven't seen it yet. If I have a user defined function returning a range, is it defined that the range function is called on every loop? If I have a function returning a range taking a parameter, for i in f(v) is it defined that the variable is evaluated for every loop? Steve. Paul McGuire [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Aug 23, 11:50 pm, bambam [EMAIL PROTECTED] wrote: Thank you, so generallizing: (1) Python re-evaluates the loop range on every loop, and (2) Python does short-circuit evaluation of conditions, in predictable order. Sorry about the bad question. A beginner would do well to work through the Python Tutorial (http:// docs.python.org/tut/tut.html). I think your first insight is actually incorrect, if I understand your wording. If I wrote: for i in range(10): # do something with i I'm quite certain that range(10) is not evaluated on every loop iteration. In fact, the range call generates a list containing the values [0, 1, 2, ..., 9], and then for iterates over this list. You can read this at http://docs.python.org/tut/node6.html#SECTION00630. On the other hand, if you are talking about a while loop, of course the condition is evaluated on every loop - otherwise such a loop, once entered, would never exit. Your second generalization is stated pretty plainly in http://docs.python.org/tut/node7.html#SECTION00770. In fact, conditional short-circuiting is a consistent theme in most Python functions and structures. The new any() and all() built-ins in Python 2.5 for example, evaluate a list of values for their boolean True/False-ness, any() returning True if any list entry is True, otherwise False; and all() returning True if all entries are True, otherwise False. Both short-circuit their evaluation, so that if the first element of a billion element list gives a True value for any() (or a False value for all()), then the evaluation of the remaining billion-1 items is skipped. Best of luck in your new Python learning process, -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Thank you, I have been through the tutorial several times, I guess I'm just not smart enough. Perhaps I have been led astray by what I read here? My code started like this: for i in range(self.parent.GetPageCount()): I was asked: Does page count change? i.e. is it necessary to retrieve it in every loop Is self.parent.GetPageCount() 'retrieved every loop'? Steve. Gabriel Genellina [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] En Sun, 26 Aug 2007 22:58:35 -0300, bambam [EMAIL PROTECTED] escribi?: Ok, many environments are capable of cached evaluation of functions without variable parameters so range(5) is cached, but range(v) is re-evaluated every time. Is this defined behaviour? The range builtin function returns a list, and lists are mutable objects, so it must return a *different* list each time. That is, is it defined what Python does for for i in f() I'm sure it must be, but I haven't seen it yet. If I have a user defined function returning a range, is it defined that the range function is called on every loop? If I have a function returning a range taking a parameter, for i in f(v) is it defined that the variable is evaluated for every loop? Find all the (mostly negative) answers yourself in http://docs.python.org/ref/for.html -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Thank you, I have been through the tutorial several times, I guess I'm just not smart enough. Python is quite different from the languages I am familiar with. My code sample started like this: for i in range(self.parent.GetPageCount()): I was asked: Does page count change? i.e. is it necessary to retrieve it in every loop Is self.parent.GetPageCount() 'retrieved every loop'? Steve. Scott David Daniels [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam wrote: That is, is it defined what Python does for for i in f() I'm sure it must be, but I haven't seen it yet. If I have a user defined function returning a range, is it defined that the range function is called on every loop? If I have a function returning a range taking a parameter, for i in f(v) is it defined that the variable is evaluated for every loop? Nope. Take the tutorial. for i in f(v): suite is the same as: iterator = iter(f(v)) for i in iterator: suite -Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Is it safe to write A = [x for x in A if x in U] or is that undefined? I understand that the slice operation can be used to make a temporary copy, so I could write A=[x for x in A[:] if x in U] but I've just copied that without any understanding. Steve. bambam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] That looks good, and perhaps a difference operator would be too simple to be useful anyway. Steve. Mikael Olofsson [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam wrote: In this case it doesn't matter - my lists don't contain duplicate elements this time - but I have worked with lists in money market and in inventory, and finding the intersection and difference for matching off and netting out are standard operations. I would use a list comprehension for that case: A = ['a','b','c','a','c','d'] U = ['a','b','e'] B = [x for x in A if x in U] The result would be B==['a','b','a'] /MiO -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idomatic python 2
Thank you. I didn't reply earlier because I was trying to get my head around what you wrote, which was strange and foreign to me. It seems to me that the dictionary object you suggested is a direct replacement for the function code, only more efficient because the case table is internalised with a hash table, and the original if/elif/else case table was unlikely to be implemented as a hash table. And presumably, it is idiomatic because Python programmers expect to use dictionaries for their lookup tables. You have answered a question I didn't know enough to ask :~) --which is why I started with the general question, so I don't feel too stupid about that --. And now I wonder about the 'other' question. Should I consider dynamically overriding the methods in my 'Device' class, instead of creating separate classes for the Psp and Pwr devices? I could create an object of the base Device class, and at init I could make sure the methods were connected for a Psp or a Pwr device. When (if ever) is that a good idea? Steve. Dan Bishop [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Aug 23, 10:21 pm, bambam [EMAIL PROTECTED] wrote: Would someone like to suggest a replacement for this? This is a function that returns different kinds of similar objects, depending on what is asked for. PSP and PWR are classes. I don't really want to re-write the calling code very much: I'm just wondering if the function can be replaced with some kind of OOP pattern. def Device(DeviceType): if DeviceType=='PSP': return PSP() elif DeviceType==Power Supply return PWR() etc... Thanks! Typically, you'd use a dictionary: DEVICE_DICT = { 'PSP': PSP. 'Power Supply': PWR, # etc. } and your function would simply return DEVICE_DICT[device_type]() -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Thank you. Steve. Alex Martelli [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam [EMAIL PROTECTED] wrote: Is it safe to write A = [x for x in A if x in U] or is that undefined? I understand that the slice operation It's perfectly safe and well-defined, as the assignment rebinds the LHS name only AFTER the RHS list comprehension is done. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Thank you. I figured the set would probably be faster, but the lists are small, and I'm concerned that the code is going to look Byzantine if I keep swapping between lists, sets and dictionaries :~). At the moment there are no sets or dictionaries in the entire code base I am working with. I'm not sure if the place I am looking at right now is supposed to support duplicates or not: duplicates are permitted, but they cause report anomalies. Steve. Paul Rubin http://[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam [EMAIL PROTECTED] writes: Is it safe to write A = [x for x in A if x in U] or is that undefined? I understand that the slice operation can be used to make a temporary copy, so I could write A=[x for x in A[:] if x in U] but I've just copied that without any understanding. You get a temporary copy either way; note you're going to linearly search U on every pass. Maybe you want: SU = set(u) A = [a for x in A if x in SU] or possibly A = list(set(A) set(U)) which will remove duplicate elements from A and not necessarily keep them in the same order, but is likely to be fastest of the bunch. -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idomatic python 2
trying to be idiomatic ...I hope that if a python programmer looks at my code it won't be an excuse to discard it. Less of an issue with Python than with C/C++, but since I'm just starting... def device(DeviceType): if DeviceType=='PSP': return Psp() elif DeviceType==Power Supply return Pwr() What about the parameter DeviceType? Also, I see what you mean now, DEVICE_DICT is upper case because it is a 'constant' -- I'd missed that point. Steve. Bruno Desthuilliers [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam a écrit : Would someone like to suggest a replacement for this? This is a function that returns different kinds of similar objects, depending on what is asked for. PSP and PWR are classes. I don't really want to re-write the calling code very much: I'm just wondering if the function can be replaced with some kind of OOP pattern. Dan already answered to this. Just as a side note, and since you're trying to be idiomatic, Python's naming convention is to use all_lower for functions, MixedCaps for classes (except - mostly for historical reasons - the builtin types...), and ALL_LOWER for symbolic (pseudo) constants. def Device(DeviceType): if DeviceType=='PSP': return PSP() elif DeviceType==Power Supply return PWR() etc... Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
This isn't a cast in the sense of some less-strongly-typed languages; it's just a conversion. The `list` function/type iterates over its argument and turns it into a list. Sets are iterable, so that's all that's really going on here. oh :~). Learning experience happening here... Thank you. The reason that lists don't have set-like methods is because lists aren't sets -- lists can contain duplicate elements Interesting point -- if that's all there is in it, then lists should have difference and intersection methods. Not because they are the same as sets -- because they are slightly different than sets. In this case it doesn't matter - my lists don't contain duplicate elements this time - but I have worked with lists in money market and in inventory, and finding the intersection and difference for matching off and netting out are standard operations. Still, any built in feature would probably be too simple to use in any but the simplest cases. Steve. Erik Max Francis [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam wrote: Excellent. By symmetry, I see that list casts the set back into a list. I wonder why list has not been extended with the same (difference, interesection) methods? Casting to set looks a little kludgy: c = list(set(a)-set(b)) I wonder if that is clearer than the explicit loop? This isn't a cast in the sense of some less-strongly-typed languages; it's just a conversion. The `list` function/type iterates over its argument and turns it into a list. Sets are iterable, so that's all that's really going on here. The reason that lists don't have set-like methods is because lists aren't sets -- lists can contain duplicate elements, whereas sets cannot. You should use the proper type for your needs; if you want to take two lists, remove duplicate elements, and then end up with a list, then the sets-difference-and-then-make-a-list mechanism is appropriate. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM, Y!M erikmaxfrancis It [freedom] must be demanded by the oppressed. -- Dr. Martin Luther King, Jr. -- http://mail.python.org/mailman/listinfo/python-list
beginner, idiomatic python
Would someone like to suggest a replacement for this? It works ok, but it doesn't look like any of the other code: tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] for port in tempList: pagefound = False for i in range(self.parent.GetPageCount()): page=self.parent.GetPage(i) if hasattr(page, port): if page.port == int(port): pagefound=True if not pagefound: sampleList.append(port) Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Wos! Several different thoughts: An object using yield to return only the relevant pages, one at a time. Pop to remove the items from the list. A dictionary to map between the strings and the integers. The dictionary was particularly unexpected. Eventually, I plan to change the string ports to device names. On the other hand, it looks like the only reason I have port numbers is to use as an index in things like this. After examining your suggestion, I realised that another thing I am interested in could be generalised: I want the complement of the set of ports in pages, given a universal set in tempList. Ignoring the break condition for the moment, and my problem with int(port)/str(port), would you have offered a different solution if I had asked for the relative complement of a small set? a= ['a','b','c'] b= ['b'] c= a-b #set theoretic difference, a\b, a.~b, ['a','c'] Steve. Zentrader [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Does page count change? i.e. is it necessary to retrieve it in every loop or tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] page_count = self.parent.GetPageCount() snipped for i in range(page_count): Also, once pagefound is set to True, all pages following will not be appended to sampleList because it is not initialized to False under the for i in range(self.parent.GetPageCount()) loop. Finally, if I understand the logic and question correctly, you want something like tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] page_count = self.parent.GetPageCount() for port in tempList: for i in range(page_count): page=self.parent.GetPage(i) if (hasattr(page, port)) and (page.port != int(port)) : sampleList.append(port) or perhaps (I'm not sure) tempList = [1, 2, 3, 4, 5, 6, 7, 8] sampleList=[] page_count = self.parent.GetPageCount() for i in range(page_count): page=self.parent.GetPage(i) if (hasattr(page, port)) and (page.port not in tempList) : sampleList.append(port) HTH -- http://mail.python.org/mailman/listinfo/python-list
beginner, idomatic python 2
Would someone like to suggest a replacement for this? This is a function that returns different kinds of similar objects, depending on what is asked for. PSP and PWR are classes. I don't really want to re-write the calling code very much: I'm just wondering if the function can be replaced with some kind of OOP pattern. def Device(DeviceType): if DeviceType=='PSP': return PSP() elif DeviceType==Power Supply return PWR() etc... Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Thank you, so generallizing: (1) Python re-evaluates the loop range on every loop, and (2) Python does short-circuit evaluation of conditions, in predictable order. Sorry about the bad question. Zentrader [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Does page count change? i.e. is it necessary to retrieve it in every loop or tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] page_count = self.parent.GetPageCount() snipped for i in range(page_count): Also, once pagefound is set to True, all pages following will not be appended to sampleList because it is not initialized to False under the for i in range(self.parent.GetPageCount()) loop. Finally, if I understand the logic and question correctly, you want something like tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] page_count = self.parent.GetPageCount() for port in tempList: for i in range(page_count): page=self.parent.GetPage(i) if (hasattr(page, port)) and (page.port != int(port)) : sampleList.append(port) or perhaps (I'm not sure) tempList = [1, 2, 3, 4, 5, 6, 7, 8] sampleList=[] page_count = self.parent.GetPageCount() for i in range(page_count): page=self.parent.GetPage(i) if (hasattr(page, port)) and (page.port not in tempList) : sampleList.append(port) HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Wos! Several different thoughts: An object using yield to return only the relevant pages, one at a time. Pop to remove the items from the list. A dictionary to map between the strings and the integers. The dictionary was particularly unexpected. Eventually, I plan to change the string ports to device names. On the other hand, it looks like the only reason I have port numbers is to use as an index in things like this. After examining your suggestion, I realised that another thing I am interested in could be generalised: I want the complement of the set of ports in pages, given a universal set in tempList. Ignoring the break condition for the moment, and my problem with int(port)/str(port), would you have offered a different solution if I had asked for the relative complement of a small set? a= ['a','b','c'] b= ['b'] c= a-b #set theoretic difference, a\b, a.~b, ['a','c'] Steve. Scott David Daniels [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bambam wrote: Would someone like to suggest a replacement for this? It works ok, but it doesn't look like any of the other code: tempList = ['1','2','3','4','5','6','7','8'] sampleList=[] for port in tempList: pagefound = False for i in range(self.parent.GetPageCount()): page=self.parent.GetPage(i) if hasattr(page, port): if page.port == int(port): pagefound=True if not pagefound: sampleList.append(port) Thanks! Look at good questions. This is a _very_ underspecified question. One stab at mindreading: def ported_pages(self): for i in range(self.parent.GetPageCount()): if hasattr(page, 'port'): yield page ... tempList = ['1','2','3','4','5','6','7','8'] missing = dict((int(v), v) for v in tempList) for page in self.ported_pages(): if page.port in missing: missing.pop(page.port) if not missing: break sampleList = missing.values() ... -Scott David Daniels -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner, idiomatic python
Excellent. By symmetry, I see that list casts the set back into a list. I wonder why list has not been extended with the same (difference, interesection) methods? Casting to set looks a little kludgy: c = list(set(a)-set(b)) I wonder if that is clearer than the explicit loop? Steve. Gabriel Genellina [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] En Thu, 23 Aug 2007 23:54:14 -0300, bambam [EMAIL PROTECTED] escribi?: After examining your suggestion, I realised that another thing I am interested in could be generalised: I want the complement of the set of ports in pages, given a universal set in tempList. Ignoring the break condition for the moment, and my problem with int(port)/str(port), would you have offered a different solution if I had asked for the relative complement of a small set? a= ['a','b','c'] b= ['b'] c= a-b #set theoretic difference, a\b, a.~b, ['a','c'] If you want a set - just use a set: py a = set(['a','b','c']) py b = set(['b']) py c = a-b py c set(['a', 'c']) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list