Re: HTML Conventions
Patrick Rutkowski wrote: I couldn't help but make an even better list in reference to this thread: snip I'll go you one better :)) I found the source of what I pulled that table from: http://jaynes.colorado.edu/PythonGuidelines.html Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: Speaking of list-comprehension?
Thank you all for taking the time to consider and respond. I had received the answer OL and responded with: Thank you, and your elaboration is well taken. I was just exploring here and the construct you noted is IMHO intuitively readable - at least for a simple expression and condition. Other than the choice order [False, True] which seems backward to me. So, where might I have found this construct. It is probably somewhere obvious, but I searched and searched without success. Of course, I've had only limited success in finding what I wanted in the official' docs, though the QR has been quite useful. Thanks again, Lee C == ta = [5, 15, 12, 10, 9] nta = [tai+[10,-10][tai=10]for tai in ta] nta [15, 5, 2, 0, 19] ota = [tai+[10,-10][tai=10]for tai in nta] ota [5, 15, 12, 10, 9] === The reply also included some advice which I include for someone else's benefit that might find this thread in the future. I leave the author's name out in case anonymity was desired (got in trouble that way once :~), not because I don't appreciate the reply. [tai + [10, -10][tai = 10] for tai in ta] [15, 5, 2, 0, 19] However, if you find yourself wanting to do simple expressions like this in list comprehensions a lot, you should probably define a helper function: def iif(expr, trueexpr, falseexpr): ... if expr: return trueexpr ... return falseexpr ... [tai + iif(tai = 10, -10, 10) for tai in ta] [15, 5, 2, 0, 19] If your expression gets much more complex, then you're much better off defining a separate function to do the whole thing, which will keep things readable, even if it doesn't make things more compact: def adjust(x): ... if x = 10: ... return x - 10 ... else: ... return x + 10 ... [adjust(tai) for tai in ta] [15, 5, 2, 0, 19] -- http://mail.python.org/mailman/listinfo/python-list
Re: Speaking of list-comprehension?
Chinook wrote whilst his head was elsewhere: So, where might I have found this construct. ta = [5, 15, 12, 10, 9] nta = [tai+[10,-10][tai=10]for tai in ta] nta [15, 5, 2, 0, 19] Immediately after posting and shutting down last night, I had one of those expansive moments that visit us elderly more and more infrequently. Duh :b whack %) x + c[b] and within a list comprehension too - how embarrassing I guess the OL reply was just trying to be kind to the intellectually defecient ;') Just goes to show that you can't help those that can't help themselves :)) Thank you all for allowing me to waste your time, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: Boss wants me to program
On Wed, 29 Jun 2005 08:11:43 -0400, phil wrote (in article [EMAIL PROTECTED]): Comes down to preference. Isn't it absolutely amazing how many choices we have. Remember the 70's - Cobol, ASM, C, Basic.CICS(shudder) And please, no eulogies (especially for CICS) - being reminded of them is bad for my heart :~) I once did a engineering modeling system in IBM 1130 assembler that ran with overlays in 32K memory, because FORTRAN was too hoggish. Input was the console keyboard and output was a CalComp plotter. Python reminds me more of Linux. Incredible no of packages, kinda disjointed, docs pretty bad, not integrated. But amazing stuff if you have the stomach for it. (seen pygame?) Maybe Python will get a daddy someday. Seriously, having been involved in several (so called) high-level productivity languages over the years on both IBM and HP (3000 series), I am really enamored with Python (not to mention being on the user end :~). However, as you say (needs a daddy) it is still for the most part in hackerdom evolution, and will not be a mainstream development platform until a Sun/IBM/whatever takes it under-wing with that intention in an open environment (the suits have to be convinced they can gain big time otherwise). Can that happen in the Open-Source arena - I'm not convinced it can because such is more akin to a staging ground at present. And what would be really cool is that if the same thing happened with Linux - it evolved to an elegant OS X like GUI without losing the intuitive underbelly. Just any daddy won't do though. The least beneficial would be the path of DOS (sorry, I'm not a MS fan :~)). A major problem is that business thinking (i.e. the suits) is overly monopolistic to the point of counter-productivity. Rather than an evolving open mainstream development platform (i.e. technical productivity competition) and commercial products emanating from such, the suits are focused on milking anything they can get their hands on with only short-term bonuses in mind. I guess it all gets down to human nature (or as Pogo said ...). Enough, before I really get carried away. Lee C -- http://mail.python.org/mailman/listinfo/python-list
OO refactoring trial ??
OO refactoring trial Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy if sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the doit methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach 2) The implications of using this in a recursive approach (referenced from but outside the recursive function) and if the decorators help with such. 3) Any other comments you might offer Thank you, Lee C === ootest.py class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): if tv == 'relates to A': return True else: return False def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): if tv == 'relates to B': return True else: return False def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() Test run == Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type help, copyright, credits or license for more information. import ootest # did B # # did A # -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
On Tue, 28 Jun 2005 02:22:13 -0400, Peter Otten wrote (in article [EMAIL PROTECTED]): Chinook wrote: 3) Any other comments you might offer if tv == 'relates to A': return True else: return False Make that return tv == 'relates to A' lest your zen master hit you. Peter Thank you Peter, So wrapped up in the OO I overlooked the simpler aspects. Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
[[ This message was both posted and mailed: see the 'To' and 'Newsgroups' headers for details. ]] Clarifications: 1) Truth test simplified after a %) by Peter Otten - thanks. In reality the testit methods will all be quite different as you might imagine (as will the doit methods). 2) A final subclass will always return True, so there will always be a valid factory (?) result. Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy if sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the doit methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach and/or how I might improve it 2) The implications of using this in a recursive approach (referenced from but outside the recursive function). 3) Any other comments you might offer Thank you, Lee C === ootest.py class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): return (tv == 'relates to A') def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): return (tv == 'relates to B') def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() Test run == Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type help, copyright, credits or license for more information. import ootest # did B # # did A # -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
Clarifications: 1) Truth test simplified after a %) by Peter Otten - thanks. In reality the testit methods will all be quite different as you might imagine (as will the doit methods). 2) A final subclass will always return True, so there will always be a valid result. Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy if sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the doit methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach and/or how it might be improved 2) The implications of using this in a recursive approach (referenced from but outside the recursive function) 3) Any other comments you might offer Thank you, Lee C === ootest.py class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): return (tv == 'relates to A') def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): return (tv == 'relates to B') def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() Test run == Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type help, copyright, credits or license for more information. import ootest # did B # # did A # -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
On Tue, 28 Jun 2005 07:31:43 -0400, Chinook wrote (in article [EMAIL PROTECTED]): [[ This message was both posted and mailed: see the 'To' and 'Newsgroups' headers for details. ]] Sorry for the duplication. I'm trying Hogwasher on OS X and it seems I better look around some more. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
On Tue, 28 Jun 2005 10:22:59 -0400, Paul McGuire wrote (in article [EMAIL PROTECTED]): Lee, Interesting idea, but I think the technique of inherit from MF to automatically add class to the test chain is a gimmick that wont scale. Here are some things to consider: - I'm not keen on the coupling of forcing your A,B,etc. classes to inherit from MF. Especially in a duck-typing language like Python, it adds no value, the subclasses receive no default behavior from their superclass, and I'm not keen on using the inheritance hierarchy to register test classes. What is the order of classes returned from __subclasses__()? Will you always want this order? Will you always want all subclasses? If this is part of a library that others will use, you may not be able to anticipate what subclasses someone else may stick on to your MF class. Even though this is an exercise, it is a learning exercise and your points are taken as pertinent considerations in real-world adaptation. So basically I'm coming from a if:elif:...else: test sequence where the order of the tests is critical (could be multiple hits and the first should be taken). My first trial was just to move the if sequence to a factory method. My second trial was to initially create an ordered list of classes to be tested as in: class A(object): ... def foo(self): ... print I'm A.foo ... class B(object): ... def foo(self): ... print I'm B.foo ... co = [A(), B()] co[1].foo() I'm B.foo My third trial is what you are responding to. So in the real-world I could only suggest how someone else might add a test, but just as in the top-down if sequence I could impose no discipline. Even adding a weighting/priority to test cases (and going through all) is a halfway measure (though possibly a more explicit one). I think that the consideration of how a test case might be added in the future is very important - having dug my way through many other programs. BTW: Is duck-typing a variation on duct-taping? - The list of items should be dynamic in the calling code, not built statically by your class structure. There's no way to anticipate what various sequences you will want to evaluate. I was also playing with another exercise involving dynamic test cases where I thought the ordered list (second trial) would be a potential approach? - Let's call the MF class MultiEvaluator. There are several ways to evaluate among several alternatives: . short-circuit, take first match what I was shooting for in this exercise . best-fit, evaluate all and take best score (assuming the testit routines return a double or int, as opposed to a bool) like my weighted/priority thought? For short-circuiting, say you have a case that will match A, you want to avoid any processing related to B,C,etc. as possible at test/do runtime. You *might* be able to do extra work at list construction time. Consider these two alternative designs: class MultiEvaluator(object): def __init__(self, *classes): self.testClasses = classes[:] def findit(self, *args): for C in self.testClasses: testobj = C() if testobj.testit(args[0]): testobj.doit() MultiEvaluator(A,B).findit(relates to A) my only drawback on such would be ME(A,B,...Z).findit(test_data) Explicit but cumbersome maybe, though no where near as cumbersome as a lengthy if sequence. vs. class MultiEvaluator(object): def __init__(self, *classes): self.testClasses = [ C() for C in classes ] def findit(self, *args): for testobj in self.testClasses: if testobj.testit(args[0]): testobj.doit() MultiEvaluator(A,B).findit(relates to B) In the first case, no B class is ever constructed, so if test object construction is expensive, you might go this route. In the second, A() and B() are built ahead of time, so the run-time processing is the fastest - you might choose this if the construction time can be done up front. The second option may cause problems for multi-threadedness or re-entrancy with a shared MultiEvaluator, though. This style of constructing the MultiEvaluator also makes more explicit (which I hear is better than implicit) what classes you are testing when creating your MultiEvaluator. - To make your testit() and doit() code more flexible and more powerful, I'd pass (*args) to each, as in: The testit() methods do in the full-fledged exercise. The doit() methods return code objects (but I'm rethinking that). class MultiEvaluator(object): def __init__(self, *classes): self.testClasses = classes[:] def findit(self, *args): for C in self.testClasses: testobj = C() if testobj.testit(args): testobj.doit(args) As in my ordered list approach (and what I thought my cleverly generated list would also do before
Re: I need help figuring out how to fix this code.
On Tue, 28 Jun 2005 14:39:47 -0400, Nathan Pinno wrote (in article [EMAIL PROTECTED]): Hi all, I need help figuring out how to fix my code. I'm using Python 2.2.3, and it keeps telling me invalid syntax in the if name == Nathan line. Here is the code if you need it. #This program asks for a password, then asks for the user's name after the correct password has been supplied. The computers response will vary, # depending on the name inputted. print Program Author: Nathan Pinno print ID# 2413448 print print Program 3 - Loops and IF Conditions print password = raw_input(Type in the password, please: ) while password != hello: print Incorrect password! print Welcome to the second half of the program! name = raw_input(What is your name, please? ) if name == Nathan: print What a great name! elif name == [Madonna, Cher]: print May I have your autograph please! else print name,, that's a nice name! What's wrong with the code? How do I fix it, so that it works? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ At least one problem is further within the if Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type help, copyright, credits or license for more information. name = 'yosa' test = ['yosa', 'sosa'] name == test False name in test True Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
Never mind. BTW: Is duck-typing a variation on duct-taping? http://www.rubygarden.org/ruby?DuckTyping http://en.wikipedia.org/wiki/Duck_typing Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
Paul, Going back over various material led to another question regarding your comments. - I'm not keen on the coupling of forcing your A,B,etc. classes to inherit from MF. Especially in a duck-typing language like Python, it adds no value, the subclasses receive no default behavior from their superclass, and I'm not keen on using the inheritance hierarchy to register test classes. The latter (__subclasses__() bit) I picked up on as a convenience (courtesy of a suggestion by STeVe) and I understand your point about more explicit ordering. However, the former seems to take issue with examples like: http://jamesthornton.com/eckel/TIPython/html/Sect08.htm or indirectly as a show stopper (using inheritance) as in: http://www.unc.edu/~mconway/mt_static/archives/odds_and_ends/ which is more in line with your comments. Anything more to this than individual preferences? Might it not be more explicit at least? Anyone? Thanks, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
On Tue, 28 Jun 2005 23:23:43 -0400, Kamilche wrote (in article [EMAIL PROTECTED]): ''' You might find this interesting. Note that the object creation in main() below could easily be read in from a text file instead, thus meeting your requirement of not knowing an item's class until runtime. Sample output: {'password': 'Your Password Here', 'type': 'A', 'logonid': 'Your Logonid Here'} # did A # {'ssn': 5, 'type': 'B'} # did B # {'type': 'BASE', 'address': '501 south street'} # did BASE # None ''' def Create(type = 'BASE', **kwargs): if type not in _CLASSES: return None # Or return a default object obj = _CLASSES[type](type = type, **kwargs) return obj class BASE(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __str__(self): return str(self.__dict__) def doit(self): print # did BASE # class A(BASE): def doit(self): print '# did A #' class B(BASE): def doit(self): print '# did B #' _CLASSES = {'BASE': BASE, 'A': A, 'B': B} def main(): obj1 = Create(type = 'A', logonid = 'Your Logonid Here', password = 'Your Password Here') print obj1 obj1.doit() obj2 = Create(type = 'B', ssn = 5) print obj2 obj2.doit() obj3 = Create(address = '501 south street') print obj3 obj3.doit() obj4 = Create(type = 'Missing') print obj4 main() Kamilche, Yes it is interesting and explicit, thank you. What I was not clear enough about though, is that at runtime the class object creation depends on the information being processed. That is, the context and type of node in the recursed tree. That's why in my trial the potential classes all included a testit method and the order of testing is important. Beyond that the doit methods all have some varying duplicated expressions, so I was constructing their functionality with code objects. However, in going back over researched material after Paul's comments I noticed another technique that might be better in creating functionality and have to study it further. Thanks for the sample, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: OO refactoring trial ??
On Wed, 29 Jun 2005 00:18:24 -0400, Paul McGuire wrote (in article [EMAIL PROTECTED]): Lee - Bruce Eckel's observation: the above scaffolding of Obstacle, Player and GameElementFactory (which was translated from the Java version of this example) is unnecessary - it's only required for languages that have static type checking. As long as the concrete Python classes follow the form of the required classes, we don't need any base classes... is consistent with my duck-typing comment that all that is needed of A,B,etc. is that they provide the necessary testit and doit methods in the proper form. He also goes on to say that, even if the base classes were empty, they still provide a useful handle for all of the derived classes, to indicate they are all common subtypes of Shape or whatever. I think you were referring to the Poking Python with a Stick entry in the second link. The inheritance of all taunts from Taunt allowed the author to put some overriding common-to-all-taunts behavior into the superclass, even if it was just a sorry, not implemented exception into the base Taunt class's tauntTheKnights() method. The idea was to provide a runtime exception if the needed method had not been overridden in the subclass. But it also provides a place to put any other common-to-all-taunts behavior, perhaps a common constructor, or other common helper methods. I think this is a good use of inheritance, when the base class actually adds some value to the architecture, even if it is just Bruce Eckel's empty placeholder base class. Note also that this author was doing patterns experimentation in both Python and Java. I envision him writing the factory's getInstance() method in Java, and having to declare its return value type. In this case Java really drives you to having all possible return values derive from a common base class, so that you can define the method as: Taunt getInstance(string tauntTypeTag) { ... which is a bit easier to deal with than just declaring that getInstance returns an object, and then having to cast it - in fact, if there were no common base type, it would be problematic to know just what to cast it to. But Python does not require this sort of type rigidity. In your code, the only requirement is that each class A,B,etc. have testit and doit methods - they have to walk and talk like ducks, they don't need to *be* ducks. My point in an earlier post was, I think many current design patterns were born out of the C++ and Java worlds, and may be overly restrictive for a comparable implementation in Python. One step you might take in the MultiEvaluator constructor is to validate the provided classes on input, so that you don't have to exhaustively test all A thru Z classes before finding out that you misspelled Z's doit method as dooit. This goes one better than the abstract subclass's you forgot to override me method implementation. In sum, both of the links you sent used examples that had inheritance hierarchies where the base class provided some contribution and commonality among the derived classes. TauntArthur is-a Taunt, TauntGalahad is-a Taunt. It really does look like the Factory pattern should return objects that share a common base class. But in Python, that common base class can also be just something that walks like a duck. -- Paul Thank you for the clarification Paul. I missed the influence of C++ and Java origins because my past experience was more in the assembler realm with a little C and Pascal, and now I'm trying to get up to speed with Python, ObjC and the OO world. You've helped me look at what I'm reading in a better light. Thanks again, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question
On Sun, 26 Jun 2005 01:06:08 -0400, Matt Hollingsworth wrote (in article [EMAIL PROTECTED]): Hello, Very new to python, so a noob question. When I've written stuff in JavaScript or MEL in the past, I've always adopted the variable naming convention of using a $ as the first character (no, I don't use perl, never have). Not possible in python. What are some good options that people commonly use so that they can easily and quickly identify variable with just a glance? When I was writing stuff in SoftImage XSI/JScript, many of the examples in the SDK used just a leading lower case o, but I'd like somethign that's more visible. I'm not a super advanced user and am just starting out in python (pretty much just working my way through Learning Python, at around page 160 or so). Seems like an _extremely_ elegent language that is very easy to read, so I suppose it's not really as much of an issue as it is with other languages. Still, I would like to see what other people do and what are some good ideas for this kind of thing. Thank you for any and all ideas. cheers, -Matt Here is something I copied from somewhere (someone else might know the source): Summary of Naming Conventions Type Convention Example - function action_with_underscores find_all variablenoun_with_underscores curr_index constantNOUN_ALL_CAPS ALLOWED_RNA_PAIRS class MixedCaseNoun RnaSequence public property MixedCaseNoun IsPaired private property_noun_with_leading_underscore _is_updated public method mixedCaseExceptFirstWordVerb stripDegenerate private method _verb_with_leading_underscore_check_if_paired really private data __two_leading_underscores __delegator_object_ref parameters that match properties SameAsProperty def __init__(data, Alphabet=None) factory functionMixedCase InverseDict module lowercase_with_underscores unit_test Hope it does not come out too jumbled, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: OO approach to decision sequence?
On Sun, 26 Jun 2005 17:58:11 -0400, George Sakkis wrote (in article [EMAIL PROTECTED]): Paul McGuire [EMAIL PROTECTED] wrote: Lee C - Here is a technique for avoiding the if-elseif-elseif...-else method for building objects. It is a modified form of ChainOfResponsibility pattern, in which you have a collection of factory methods that all have a common signature, or a collection of Factory classes that all implement a makeObject method. These common methods probably take a string, and return a generic object. Fortunately, such type flexibility is *very* easy in Python. :) Example: I want to convert individual strings to native data types. I want to detect integers, reals, complex numbers, and booleans (indicated by 'True' or 'False'). This is kind of similar to a parsing problem, but it could also be used for deserializing or unpickling data of an unknown original type. Note the special treatment I have to go through with boolean values - I needed to write a special makeBool routine, since Python will take any non-empty string to be True, when what I want is 'True' to yield true and 'False' to yield false. Hope this gives you some alternative ideas to your cascading if's. -- Paul def makeBool(s): if s in ('True','False'): return s == 'True' raise ValueError converters = [ int, float, complex, makeBool, str ] def makeObject(stringVar): for conv in converters: try: val = conv(stringVar) except Exception: continue else: break; return val def test(s): val = makeObject(s) print s, val, type(val) test('1') test('1.0') test('1+2j') test('1+0j') test('True') test('False') test('A') prints: 1 1 type 'int' 1.0 1.0 type 'float' 1+2j (1+2j) type 'complex' 1+0j (1+0j) type 'complex' True True type 'bool' False False type 'bool' A A type 'str' Nice technique. Something that needs to be pointed out is that the order of the converters *is* important; int takes precedence over float, which take precedence over complex and bool takes precedence over string. More succinctly: { int - float - complex } { bool - str } In general the converters will form a strict partially ordered set, so the list of converters should be a topological sort of the respective DAG. George Ah yes, there is more than one way to skin a cat :~) and your samples are helping me get a better grasp of both Python and OOP in such. I find both Bengt's and Paul's variation on a theme understandable (I must be making progress :~) and interesting. I must admit that I did have to look twice at Bengt's clever little slice on 'an' though. I had already worked my way through a href=http://fraca7.free.fr/blog/index.php?2005/02/28/2-design-patterns-part- i---chain-of-responsibilitythis/a though, so they were that much more understandable. Actually, I'm using a superclass as a factory, similar to Steve B's example (as modified by someone I can't find the name of). The difference is that my criteria does not map easily to class names so I have the verbose decision sequence in my superclass. Of course, if I want to get really fancy, I could use the COR pattern within such. I'm making more hay out of this one little pasture than I expected (i.e. increasing my understanding) thanks to all of you. I'm going to have to start writing down names (rather than rely on this ol head) so I can properly thank everyone - like those clarifying other examples. At some point I'll put up the original top-down and OO refactored versions of my little utility in the hope that I will learn even more from criticism of my efforts. The new deal top-down structured programming encountered in my continuing post grad work at BU in the 1960s was easier to get a solid handle on ;') Much appreciated, Lee C Wonder rather than doubt is the root of knowledge. --Abraham Joshua Heschel -- http://mail.python.org/mailman/listinfo/python-list
Re: Excellent Site for Developers
On Sat, 25 Jun 2005 15:36:06 -0400, Philippe C. Martin wrote (in article [EMAIL PROTECTED]): Hi, Not being from anglo-saxon heritage, I keep wondering why spammers always (or very often) get called 'trolls' ? I mean fantasy fiction has brought us many hugly beasts (goblin, warlock, orc, dark elf ) The trolls, as I recall, grow back their limns once those have been cut by the nice folks. Is that the reason ? Regards, Philippe Do Re Mi chel La Si Do wrote: rather... super troll Actually there are many understandings, but many stem from a something ugly sense as in the old Norse legend. In the context of the internet, the meaning is usually: To troll means to allure, to fish, to entice or to bait. An internet troll is someone who fishes for people's confidence and, once found, exploits it. Internet deception relies on exploiting trust and building confidence, and the rewards can be financial or psychological. As you can see, though, the context could be any communication, from anyone from the common criminal to the established political, religious, or business leader :~) Lee C God save us from those that would save us. -- my grandmother c1945 -- http://mail.python.org/mailman/listinfo/python-list
Re: Using code objects?
On Tue, 21 Jun 2005 09:56:27 -0400, Konstantin Veretennicov wrote (in message [EMAIL PROTECTED]): On 6/21/05, Chinook [EMAIL PROTECTED] wrote: When I create the code objects though, it seems a couple different ways work and I'm wondering which is better and why (or is there a more correct technique in this situation)? The two different ways are illustrated below: ... obj1 = compile(exp1, 'whatever', 'single') ... obj2 = compile(exp2, 'whatever', 'exec') Are you essentially asking about difference between compile(..., 'single') and compile(..., 'exec'), which is described in http://docs.python.org/lib/built-in-funcs.html ? - kv [I neglected to post this to the list] Sorry Konstantin, being way too late at the time I missed the obvious. Since I'll have multiple statements in a code object I will, of course, use 'exec' In the meantime I have done a lot of searching and I guess the second point of the query is pretty well settled also, unless you have another thought. There are some number of code objects independent of some number of potential classes. Each potential class action' method will return one or more of the code objects. So I 'compile' the code objects separately and pass back appropriate references from the factory derived class method. I'm intentionally over designing a simple utility so I will learn the techniques and alternatives for a more involved application that involves AI. Thanks, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Using code objects?
Using code objects? === As an OO exercise I have a factory pattern that returns class objects that each have an action method. ClassObj.action() in turn returns a code object in my recursive process loop. I create the code objects as a one time step outside my factory pattern and potential class definitions, then reference them in my potential classes which seems to work as expected. When I create the code objects though, it seems a couple different ways work and I'm wondering which is better and why (or is there a more correct technique in this situation)? The two different ways are illustrated below: Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type help, copyright, credits or license for more information. def foo(st): ... print st ... exp1 = 'foo(#expersion 1#)' exp2 = 'foo(#expersion 2#)' obj1 = compile(exp1, 'whatever', 'single') exec obj1 #expersion 1# obj2 = compile(exp2, 'whatever', 'exec') exec obj2 #expersion 2# Thank you, Lee C -- http://mail.python.org/mailman/listinfo/python-list
RE: functions with unlimited variable arguments...
Xah said unto the world: oops... it is in the tutorial... sorry. though, where would one find it in the python reference? i.e. the function def with variable/default parameters. This is not a rhetorical question, but where would one start to look for it in the python ref? a language is used by programers. Subroutine definition with variable/default parameters is a basic issue a programer wants to know, and different languages differs very much in how they handle this. This is what i mean that the language doc should be programing oriented, as opposed to computer-sciency or implementation oriented... I don't get to the reference docs much. Mostly I use the quick reference guide and it's noted there in an easy to find manner. If you have not checked it out then see: http://rgruet.free.fr/#QuickRef Lee C -- http://mail.python.org/mailman/listinfo/python-list
OO approach to decision sequence?
OO approach to decision sequence? - In a recent thread (Cause for using objects?), Chris Smith replied with (in part): If your table of photo data has several types of photos, and you find yourself saying if is_mugshot: #something elif is_freehand: #something else: #something then OOP will help organize your code. This struck a chord because I'm trying to refactor a top-down approach to an OO approach. The reason I am doing such is to try and get my mind wrapped around OO design, not because the particular module will benefit from an OO approach (it's a simple top-down recursive tree utility). In fact it's probably ill suited for OO and that is why I chose it. I've used an OO approach where I built up record (instance) content in a variable record file, but here I'm trying to come at it from the opposite direction as variable record mapping (deconstructing) would be to such. Anyway, a tree node can be any of seven types where: if node_type_1: # recurse elif node_type_2: # terminus - do something elif node_type_3: # terminus - do something else ... else: # terminus - catch all, do yet something else return #to parent So, where is the magic :~) Seriously, how might OO help me organize this type of problem (alleviate the conventional lengthy if structure)? I've looked at the cookbook, class interface techniques, factory functions and metaclasses till my head is swimming. Am I missing a bolt in the machinery somewhere, or simply trying to find magic that doesn't exist for a straightforward decision sequence? Thank you, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: OO approach to decision sequence?
On Sat, 18 Jun 2005 03:52:28 -0400, Brian van den Broek wrote (in article [EMAIL PROTECTED]): Chinook said unto the world upon 18/06/2005 02:17: OO approach to decision sequence? - In a recent thread (Cause for using objects?), Chris Smith replied with (in part): If your table of photo data has several types of photos, and you find yourself saying if is_mugshot: #something elif is_freehand: #something else: #something then OOP will help organize your code. This struck a chord because I'm trying to refactor a top-down approach to an OO approach. The reason I am doing such is to try and get my mind wrapped around OO design, not because the particular module will benefit from an OO approach (it's a simple top-down recursive tree utility). In fact it's probably ill suited for OO and that is why I chose it. I've used an OO approach where I built up record (instance) content in a variable record file, but here I'm trying to come at it from the opposite direction as variable record mapping (deconstructing) would be to such. Anyway, a tree node can be any of seven types where: if node_type_1: # recurse elif node_type_2: # terminus - do something elif node_type_3: # terminus - do something else ... else: # terminus - catch all, do yet something else return #to parent So, where is the magic :~) Seriously, how might OO help me organize this type of problem (alleviate the conventional lengthy if structure)? I've looked at the cookbook, class interface techniques, factory functions and metaclasses till my head is swimming. Am I missing a bolt in the machinery somewhere, or simply trying to find magic that doesn't exist for a straightforward decision sequence? Thank you, Lee C Hi Lee, I'm a hobbyist who came to grok the OO approach in the last 6 months or so ago. So, take the comments with that in mind. A simple toy example with the if type test approach: class A(object): ... pass ... class B(object): ... pass ... a = A() b = B() for item in (a, b): ... if type(item) == A: ... ident = an A ... if type(item) == B: ... ident = a B ... print Found %s %ident ... Found an A Found a B Now, the same sort of behaviour where the if type testing has been replaced with code more in keeping with the OOP approach: class C(object): ... def report(self): ... print Found a C ... class D(object): ... def report(self): ... print Found a D ... c = C() d = D() for item in (c, d): ... item.report() ... Found a C Found a D A metaphorical explanation that is a bit handwavy, but that I find useful: In both approaches, there is a common behaviour you want the various types of objects to exhibit. (In a less 'toy' example the behaviour would be more complicated.) In the if type style, you are asking each object what kind of object it is, and then setting an aspect of the behaviour as a function of the answer. In the more OOP approach, you rely on the fact that each object knows what kind of object it is. So, you don't need to ask it, and adjust the behaviour accordingly. You just tell it to behave, and, knowing what kind of thing it is, it knows how to behave as befits that kind of thing. Two big benefits in the context are that if you need to exhibit the same behaviour in multiple places, you don't have multiple if type chains, and, if you want to add a type, with its own specific behaviour, you just add a class, and there is no worry about hunting down the if type chains to update them. There was a thread on the tutor list around mid-Feb. which really helped me come to understand the idea. Actually, from Dec. to Feb. or so, there are several long tutor threads where people gave me much useful help coming to see how to employ OOP. Might be worth a trip through the archive. HTH, Brian vdB Thanks for the reply Brian. I understand what you are saying. The point I'm messing up my head with though, is when the entity (tree node in my case or variable record content deconstructing in the aspect example I noted) is not an instance of a class already - it is obtained from an external source and only decipherable by its content. In practical terms that leaves me with some decision sequence regardless and I was wondering (from what Chris Smith said) how that might be done in OOP. The whole problem may be that I'm reading too much into what Chris said :~) I will dig back through the Tutor archives as you suggested. Thanks again, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: OO approach to decision sequence?
On Sat, 18 Jun 2005 09:10:25 -0400, George Sakkis wrote (in article [EMAIL PROTECTED]): Chinook wrote: I understand what you are saying. The point I'm messing up my head with though, is when the entity (tree node in my case or variable record content deconstructing in the aspect example I noted) is not an instance of a class already - it is obtained from an external source and only decipherable by its content. In practical terms that leaves me with some decision sequence regardless and I was wondering (from what Chris Smith said) how that might be done in OOP. The whole problem may be that I'm reading too much into what Chris said :~) I will dig back through the Tutor archives as you suggested. What you are looking for is what is called the 'factory method pattern' (http://en.wikipedia.org/wiki/Factory_method_pattern) and it's one of the cases where OOP doesn't eliminate the if/elif/elif (or switch in C++/Java). That's ok though because, as you noticed, at some point you have to take a decision. What's important is the once and only once principle, that is all the decision logic is encapsulated in a single method (or in python in a single function) instead of being replicated every time you want to use an existing Node. Regards, George George, Yes, that answers my question of how the issue is approached in OOP - thank you. I'll do some more googling to find examples in Python and then try refactoring my little utility. The effect on my little utility will be a verbose abstraction of a specific efficient top-down approach, but the intended goal is to learn how to better facilitate extensibility. Thanks to all that took the time to wade through my post and especially to those that offered their thoughts, Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: extreme newbie
On Sat, 18 Jun 2005 14:00:35 -0400, Steven D'Aprano wrote (in article [EMAIL PROTECTED]): On Sat, 18 Jun 2005 12:05:59 -0400, Peter Hansen wrote: Furthermore, protecting you from someone else making money off a copy of your program is basically what licenses are for, and if you have noticed they don't protect even Microsoft (see, for example, entire governments like the Indonesian government, which has mass-pirated Microsoft software for a long time). Please call it what it is: copyright infringement, not piracy. Piracy takes place in international waters, and involves one or more of theft, murder, rape and kidnapping. Making an unauthorized copy of a piece of software is not piracy, it is an infringement of a government-granted monopoly. In any case, there is a powerful argument for wanna-be Microsofts to turn a blind eye to copyright infringements. It worked for Microsoft and almost every other successful software company. The biggest barrier to success for software developers is getting people to even know your software exists. The second biggest barrier is encouraging them to try your software. The third is getting them to keep using your software once they've tried it. Actually collecting money from them is at the bottom of the list -- you can't expect people to pay you for using your software if they don't even know you exist. Apart from the occasional public rant (such as Bill Gates' plea to users not to make illegal copies of MS BASIC), in the early days Microsoft didn't go out of their way to chase copyright infringers. If they had, the users would have simply stopped using the MS software and used something else. Instead, people grabbed copies of Word or Excel from their friends, taking market share from WordPerfect, WordStar, Lotus etc. Eventually, they would need an upgrade, or find it more convenient to buy than to copy. Every so-called pirated copy had (at least) four benefits to Microsoft: it denied a sale to Microsoft's competitors; it increased users' familiarity and confidence with Microsoft's products; it built Microsoft's brand recognition among software purchasers and IT departments; and it was (usually) a future sale to Microsoft. It was only as Microsoft approached monopoly status that copyright infringement began to hurt them more than it gained them. With few if any competitors, the loss of revenue from unauthorized copies of Word or Excel or Windows became greater than the benefits. Steven, Your weigh-in on semantics is misleading, but your elaboration of the aspect is very well put. As to semantics, piracy is to the originator what freedom fighter is to those that perceive themselves as oppressed. On the other hand, your elaboration is a very good example of the altered consciousness of human nature. That is, the acceptance of shades of complicity divorced from shades of guilt. Of course, one can see (if they so chose) many more obvious examples in business, let alone government and religion :~) Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic class inheritance something else
On Tue, 14 Jun 2005 12:39:09 -0400, Vero wrote (in article [EMAIL PROTECTED]): Hi. My name is Veronica, I am a master student at UNAM. I am working on something related to Artificial Inteligence and I have been looking for the most appropriated programming language to implement my algorithms. I found python to be very close to what I need, but there are still a couple of details that I haven't been able to solve. First, (and most important) I would like to be able to dynamically modify the classes from which a class inherits. I haven't found any way to do it with the language as it is. If there is a way, any suggestion will be truly appreciated. If I had to modify the source code to achieve this, I hope that you could give me some hints; I have an idea of how something like this could be achieved but since I don't know deeply the python sourcode I could get lost. Second, since my program will be modifying classes during run time, I would like to have a way to write on a file the python code that would have defined the class with the functions and attributes as they were left, just as if it had been writen like that at the very begining. I need it to be python code because I will be using that latter. Maybe I will have to solve this second problem by myself but I just wrote in case anybody had a good idea. Thank you very much for your help. Vero La sociedad es inherentemente democrática: la mayoría decide si pensar p or si misma o si dejar que alguien más les diga qué pensar. http://mx.geocities.com/aqua_azul_2000/ __ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ¡gratis! Regístrate ya - http://correo.yahoo.com.mx/ I'm not going to show my ignorance by noting the half-baked thoughts I had when reading your post, but I will point you at the article that initiated my thoughts so you might form your own (fully baked hopefully :~). http://www-106.ibm.com/developerworks/linux/library/l-pymeta.html Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: Going crazy...
On Mon, 13 Jun 2005 20:52:43 -0400, Gary Herron wrote (in article [EMAIL PROTECTED]): Jan Danielsson wrote: Hello all, I'm 100% sure that I saw an example which looked something like this recently: a=(1, 2, 3, 4, 5, 6) b=(2, 3, 6) a - b (1, 4, 5) The only new language I have been involved in lately is Python. Is my memory failing me, or have I seen such an Python-example somewhere? If so: Where; or more importantly: How does it work? I just tried typing the above in Python, and it - obviously - doesn't work, so it must be some other syntax. Not with tuples, lists or dictionaries. However a more recent addition to the language is Sets, and they support set differences: from sets import Set Set([1,2,3,4,5,6]) - Set([2,3,6]) Set([1, 4, 5]) Gary Herron Looks like something that might be part of an example of class operator overloading??? But I'm not far enough along to quickly show a sample if such is possible. Lee C -- http://mail.python.org/mailman/listinfo/python-list
Re: case/switch statement?
On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote (in article [EMAIL PROTECTED]): Steven D'Aprano wrote: On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote: If the case values are constants known to the compiler, it can generate O(1) code to take the correct branch. It is precisely this behavior that is desired in many situations. Agreed. I certainly don't object to sensible optimizations! But the number of if...elif statements which can be optimised are a vanishingly small subset of the number of possible if...elif statements. And you can bet your last dollar that many people will use case statements even when doing so gives no advantage, in a mistaken opinion that it will be somehow magically faster. Case statements are actually more suitable in many cases even when performance is not a goal for reasons of *readability*. When reading an if statement, you have to scan down through effective each statement attempting to find the case in which you are interested. Some cases can be compound. The nested ifs can get confused with the surrounding ones (in Python or a language with explicit block delimiters). The cases are often not written in any particular order, or they are ordered *for* performance reasons, but in ways that make it harder to scan. A case statement, on the other hand, can be a message from the programmer, saying in effect here's code that represents a series of _simple_ conditionals, ordered (usually) in a sensible way (e.g. ascending numerical order), so just jump to the case you want and carry on maintaining this nice code. In current Python the equivalent approach is, of course, a dictionary of some kind, though it's arguable whether this is as clean in many cases as a case statement would be. -Peter I'm new to Python, but I'm retired from a software engineering career that began in the early 60s. I'm not against case statements in the simplest syntactical context, but over the years I've seen so many abuses of such (i.e. difficult to follow code) that neither am I against their exclusion from Python. The thought being (in my mind) that such might force the programmer to rethink their approach to something more intuitively structured (whether module/function wise or OO wise or some combination), though I admit it is an idealistic view. The problem I do see is your apples and oranges argument. You are equating at the extreme, compound if conditions with _simple_ case statement conditionals. Yet you are leaving out of your argument the transition from the former to the latter. If mapping one to the other is simple then the readability is no harder with if statements. An example might be in dealing with variably formated records where each record contains a record type flag. On the other hand if you were to map compound conditions to _simple_ case statement conditionals, you need an intermediate translation that must be studied to understand the _simple_ conditionals anyway. Such translations also promote an overabundance of status/flag variables to understand and follow which does not increase the readability of code. In my experience I've also seen where case statements promote overly long and partially repetitive code blocks, which would be better constructed in a top-down fashion. Admittedly, if statements could be used in a similar way but I've not seen the same level of abuse with such. So arguably, if the translation is pretty much one to one then the argument is mute :~) If on the other hand the translation is many to one, then one's skill in developing well structured readable code is really the issue, and again case statements are a mute point. Lee C -- http://mail.python.org/mailman/listinfo/python-list