Re: Encapsulation, inheritance and polymorphism
On 07/17/2012 04:24 AM, Lipska the Kat wrote: ... Thanks for your time and I'll try to do a bit better with the reading thing before asking more questions... not sure about this obsession with code indentation though :-| I think it's inaccurate to call this indentation an obsession, it's part of Python's defined syntax. It's used INSTEAD OF punctuation or keywords (like {} or BEGIN END). If you're already used to indenting your code consistently, you'll be surprised at how quickly it becomes a non-issue when you start using Python. It's a bit dated, but you might find http://www.linuxjournal.com/article/3882 to be an interesting read. -=- Larry -=- -- http://mail.python.org/mailman/listinfo/python-list
Re: jython lacks working xml processing modules?
On 18/07/12 05:12, gaodexiaozh...@gmail.com wrote: However,there is one project implemented by Python used PyXML and now my Jython project has to depend on it ,so I am afraid that if Jython doesn't support PyXML,then my jython project can not depend on the original Python project ,then my jython project maybe can not move on unless I find another project to take place of the original Python project. I think, if possible, such project should switch out of PyXML anyway. If you make them nice patch to port them to standard ElementTree (and as a side-effect make the project working with Jython), they will like you. I guess. Matěj -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 18/07/12 01:46, Andrew Cooper wrote: On 17/07/2012 19:36, Lipska the Kat wrote: On 17/07/12 19:18, Mark Lawrence wrote: On 17/07/2012 18:29, Ethan Furman wrote: Terry Reedy wrote: On 7/17/2012 10:23 AM, Lipska the Kat wrote: snip Take for example a Linux system call handler. The general form looks a little like (substituting C for python style pseudocode) if not (you are permitted to do this): return -EPERM if not (you've given me some valid data): return -EFAULT if not (you've given me some sensible data): return -EINVAL return actually_try_to_do_something_with(data) How would you program this sort of logic with a single return statement? This is very common logic for all routines for which there is even the remotest possibility that some data has come from an untrusted source. Eeek! well if you insist (type bound) someType -EPERM someType -EFAULT sometype -EINVAL someType -EDOSOMETHING //method someType checkSomething(data){ someType result = -EINVAL //or your most likely or 'safest' result if not (you are permitted to do this): result = -EPERM if not (you've given me some valid data): result = -EFAULT if not (you've given me some sensible data): result = -EINVAL else result = -EDSOMETHING return result } //cohesive, encapsulated, reusable and easy to read //later if(checkSomething(data) == EDOSOMETHING){ actually_try_to_do_something_with(data) } else{ //who knows } What do you think ? ~Andrew P.S. like the sig. thanks -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 17 July 2012 13:01, Lipska the Kat wrote: > Well I've set myself a task. > I have a text file containing a list of stock items > each line contains the number in stock followed by a tab followed by the > name of the item. I need to implement something that reads in the text file > and outputs the stock list in ascending or descending order of quantity. > > Please note I am NOT asking for solutions. > > In bash this is laughably trivial > sort -nr $1 | head -${2:-10} Here's a Python translation that won't help :) from sys import argv print ''.join(sorted(open(argv[1]), key=lambda l: -int(l.split('\t')[0]))[:10 if len(argv) < 3 else int(argv[2])]) Who said Python was readabl'y yours, -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Pylint 0.25.2 / ASTNG 0.24 / logilab-common 0.58.1 released
Hi there, I've released this morning new versions of Pylint, ASTNG and logilab-common projects. For more information, read http://www.logilab.org/blogentry/100365 Enjoy! -- Sylvain Thénault, LOGILAB, Paris (01.45.32.03.12) - Toulouse (09.54.03.55.76) Formations Python, Debian, Méth. Agiles: http://www.logilab.fr/formations Développement logiciel sur mesure: http://www.logilab.fr/services CubicWeb, the semantic web framework:http://www.cubicweb.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
Am 18.07.2012 11:06, schrieb Lipska the Kat: On 18/07/12 01:46, Andrew Cooper wrote: Take for example a Linux system call handler. The general form looks a little like (substituting C for python style pseudocode) if not (you are permitted to do this): return -EPERM if not (you've given me some valid data): return -EFAULT if not (you've given me some sensible data): return -EINVAL return actually_try_to_do_something_with(data) How would you program this sort of logic with a single return statement? This is very common logic for all routines for which there is even the remotest possibility that some data has come from an untrusted source. Eeek! well if you insist (type bound) someType -EPERM someType -EFAULT sometype -EINVAL someType -EDOSOMETHING //method someType checkSomething(data){ someType result = -EINVAL //or your most likely or 'safest' result if not (you are permitted to do this): result = -EPERM if not (you've given me some valid data): result = -EFAULT if not (you've given me some sensible data): result = -EINVAL else result = -EDSOMETHING return result } //cohesive, encapsulated, reusable and easy to read This is a classic discussion topic, whether single exit (SE) functions should be used or not. There are two things I consider as problematic with them: 1. In the presence of exceptions, every function has at least two possible paths that can be taken out, one returns a value (or None, in Python), the other throws an exception. For that reason, trying to achieve SE is a dangerous illusion. The syscall handler above is C, which doesn't have exceptions like Java, C++ or Python, so it doesn't suffer those two paths. 2. The biggest problem with SE functions is that you often need to skip over lots of code before you finally find out that the fault at the very beginning causes nothing else to happen inside the function before it is finally returned to the caller. A typical symptom is deeply nested if-else structures. Another symptom is result variables that are checked multiple times to skip over effectively the rest of the function, which "unrolls" the nested if-else structures. Yet another symptom is a very fine granularity of microscopic functions, which is effectively a distributed nest of if-else structures. Coming back to Python, this would look like this: if not /you are permitted to do this/: raise NotPermitted("go awai!") if not /you've given me valid data/: raise TypeError("unexpected input") if not /you're given me sensible data/: raise ValueError("invalid input") # do stuff here... If you shoehorn this into an SE function (which you can't do if something in between might throw), then it probably looks like this: error = None if not /you are permitted to do this/: error = NotPermitted("go awai!") elif not /you've given me valid data/: raise TypeError("unexpected input") elif not /you're given me sensible data/: raise ValueError("invalid input") else: # do stuff here... if error: raise error else: return result //later if(checkSomething(data) == EDOSOMETHING){ actually_try_to_do_something_with(data) } else{ //who knows } Interestingly, you suggest to divide the original function into one that verifies some conditions and one that does the actual work. Using an early return is to me like drawing a big red line inside a function by which it can be split into two sections. This makes it IMHO equally clear, even clearer since I don't have to locate and read that other function. My bioware parses this so that if the first part succeeds, the second part can be read independently thereof, which reduces the amount of info to keep in mind at a time. Also, when changing code, I don't have to locate other places where the utility function (checkSomething) is called (Python allows local functions, which can be very(!!) useful). Since the code is inline, I know that only this one function is affected. Yes, this is in direct contrast to the reusability you mentioned. Neither ease of change nor reusability are goals in and of themselves though, so this is not a black-or-white question and a compromise can be good enough. It's a question of taste, experience, phase of the moon, coffeination levels etc. :) Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Tue, 17 Jul 2012 12:01:21 +0100, Lipska the Kat wrote: > For the past 9 years I have been developing in Java [...] > Anyway, I'm looking at Python as a rapid prototyping language. I have an > idea and just want to get it down in basic outline code as quickly as > possible before it departs my aging brain... A couple of good resources for you to read, written by a top Python developer who also knows Java backwards: http://dirtsimple.org/2004/12/python-is-not-java.html http://dirtsimple.org/2004/12/java-is-not-python-either.html You will occasionally (i.e. about sixteen times a day) read some Python programmer tossing out comments like "Flat is better than nested", often in quotes. P.J. Eby does this at least twice in the first link above. What the hell are they talking about? They're talking about the Zen of Python, a list of a dozen or so slightly tongue in cheek mottoes meant to encapsulate the (often deliberately contradictory) coding philosophy that Python developers should aspire too. At the interactive Python prompt, enter "import this" (without the quotes) and be enlightened. Keeping the Zen in mind as an ideal is incredibly useful. Arguing over whose opinion is more true to the Zen is a waste of time. > I'm not used to using > variables without declaring their type ... (well I used to do Visual > Basic many years ago) It just seems so weird, Compared to Java, or Haskell, or Ada, Python may seem like an incredibly sloppy language. A lot of that sloppiness comes from the lack of compile- time type-checking. And that's probably true: Haskell's type checker can detect infinite loops, by Jove! Python won't even warn you that you're about to blow away a built-in function. (Don't worry though, you can easily get it back again.) (But at least Python isn't Perl, or PHP.) While Python doesn't (can't!) check the type of data at compile-time, but it does check the type of data at run-time. This ain't assembly language, where there's only one type, bytes! I came from a Pascal background, and at first I found the lack of type declarations rather concerning. But soon I found it liberating. Especially once I started using Python interactively, at the REPL. Most arguments about which is better, compile-time type checking or run- time type checking, miss the point: both have advantages, and disadvantages. Which is "better" depends on what you want to do. Python is deliberately designed to be *fast to write*. It gives up a little bit of safety for that. But not as much as you might think. Type errors are less frequent than other errors (errors of logic, bad data, etc.). And so in the time it might take a Java programmer to satisfy the compiler's insistence on type correctness, a Python programmer has probably written the program *and* the unittests and given the customer the first iteration of the application. At least, that's the theory. But you probably already know that. After all, that's why Python is the rapid-application-development language, not Java. > and what's this obsession > with 'correct' indentation of code ??? Nearly everyone rights correctly indented code anyway. At least, those who don't, you don't want on your project. Python just takes it one step further, and makes correctly indented code mandatory rather than optional. The plus side is, no more style wars over where the braces go, no more hunting for lost braces. The downside is, if you paste code into a dumb application (like many email clients!) that strips whitespace, your code will break. So don't do that. http://stromberg.dnsalias.org/~strombrg/significant-whitespace.html -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Tue, 17 Jul 2012 09:52:59 -0400, Roy Smith wrote: > you could write in Python: > > # Type matching will get checked at run-time > def my_function(mpf, ot): >assert isinstance(mpf, MassivelyParallelFrobinator) >assert isinstance(ot, OtherThing) Keep in mind that assertions are not guaranteed to run. Code like the above is buggy, because if Python is run under the -O (optimize) flag, assertions will be stripped out. Assertions are mostly useful for two things: 1) "This cannot possibly happen, but just in case it does..." If you've ever written something like this: if x%2 == 0: do_spam() elif x%2 == 1: do_ham() else: # This can't happen! print("something unexpected happened") sys.exit() that is better written as: if x%2 == 0: do_spam() else: assert x%2 == 1, "something unexpected happened" do_ham() 2) To check your internal reasoning in a function or method. For example: def foo(something): n = len(something) x = math.sqrt(x) # We expect that x must be less than half of n. # E.g. n=100 gives 10 < 50, which is correct. assert x < n//2 process(n, x) Run with the -O flag, the (hopefully!) redundant test will be stripped out; without the flag, the test will check your logic for you and fail if the stated condition is not met. For bonus points, can you see the mistake? The stated condition is wrong. Without the assert, the process() code could go off and potentially silently do the wrong thing, but the assert guards against that possibility. And once I've had a bug report that my app raises an AssertionError, I will go back and think more carefully about the assertion that sqrt(n) is always less than half of n. > but that's just not the way people write code in Python. Better is to use explicit type checks and raise an exception yourself: if not isinstance(x, int): raise TypeError('expected an int, got %r' % x) Better still is to duck-type whenever you can. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Wed, 18 Jul 2012 01:46:31 +0100, Andrew Cooper wrote: > Take for example a Linux system call handler. The general form looks a > little like (substituting C for python style pseudocode) > > if not (you are permitted to do this): > return -EPERM > if not (you've given me some valid data): > return -EFAULT > if not (you've given me some sensible data): > return -EINVAL > return actually_try_to_do_something_with(data) > > How would you program this sort of logic with a single return statement? That's not terribly hard. if not (you are permitted to do this): result = -EPERM elif not (you've given me some valid data): result = -EFAULT elif not (you've given me some sensible data): result = -EINVAL else: result = actually_try_to_do_something_with(data) return result A better example would involve loops. I used to hate programming in some versions of Pascal without a break statement: I needed a guard variable to decide whether or not to do anything in the loop! # pseudo-code for i in 1 to 100: if not condition: do_something_useful() Even with a break, why bother continuing through the body of the function when you already have the result? When your calculation is done, it's done, just return for goodness sake. You wouldn't write a search that keeps going after you've found the value that you want, out of some misplaced sense that you have to look at every value. Why write code with unnecessary guard values and temporary variables out of a misplaced sense that functions must only have one exit? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
In article <5006b2e2$0$29978$c3e8da3$54964...@news.astraweb.com>, Steven D'Aprano wrote: > On Tue, 17 Jul 2012 09:52:59 -0400, Roy Smith wrote: > > > you could write in Python: > > > > # Type matching will get checked at run-time > > def my_function(mpf, ot): > >assert isinstance(mpf, MassivelyParallelFrobinator) > >assert isinstance(ot, OtherThing) > > Keep in mind that assertions are not guaranteed to run. Code like the > above is buggy, because if Python is run under the -O (optimize) flag, > assertions will be stripped out. One could equally say that "code like the above is efficient, because if Python is run under the -O (optimize) flag, assertions will be stripped out" :-) > Better is to use explicit type checks and raise an exception yourself: > > if not isinstance(x, int): > raise TypeError('expected an int, got %r' % x) Maybe, but that's two lines where one does just fine. If you're going to go for type-bondage, you might as well be efficient and succinct about it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Wed, 18 Jul 2012 09:07:22 -0400, Roy Smith wrote: >> Keep in mind that assertions are not guaranteed to run. Code like the >> above is buggy, because if Python is run under the -O (optimize) flag, >> assertions will be stripped out. > > One could equally say that "code like the above is efficient, because if > Python is run under the -O (optimize) flag, assertions will be stripped > out" :-) You seem to have missed my point. Asserts *should* be used for checks which are optional. In this case, the fact that assert is optimized away is a feature: you have the added safety of a guard against some programming errors, while still being able to optimize that code on request. This is what assert is for. You get no argument from me about that -- my code is bulging with assertions. But where you *need* an explicit check to run, assert is not suitable, because you cannot control whether or not it will run. The caller, not you, controls that, by passing -O to the python interpreter. If you have a public function or method that can be called by any other piece of code, and it has required pre-conditions that need to be checked (not necessarily a type-check), then DO NOT USE ASSERT. If you use assert, then sometimes that pre-condition will not happen, and the caller can pass garbage into your function. The pre-condition will be violated, and your function will silently go off and do the wrong thing without warning. If you're lucky, your program will fail somewhere else, probably far away from where the error actually occurs, and you will merely have to spend hours or days trying to debug it. If you're unlucky, your program won't fail, it will just calculate garbage, or otherwise do the wrong thing. Besides, there is another reason not to use assert: it gives the wrong exception. If the error is a type error, you should raise TypeError, not ValueError, or ZeroDivisionError, or IndexError, or AssertionError. Using assert because it saves a line of code is lazy, sloppy programming. >> Better is to use explicit type checks and raise an exception yourself: >> >> if not isinstance(x, int): >> raise TypeError('expected an int, got %r' % x) > > Maybe, but that's two lines where one does just fine. But one line (assert) does *not* do just fine under the conditions I am talking about. If you need the check to run, then assert is not suitable, because it is not guaranteed to run. It's as simple as that. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 2012-07-17, Lipska the Kat wrote: > and what's this obsession with 'correct' indentation of code ??? If you can explain to us Java's obsession with 'correct' placemnt of curly-braces, then you've explained indentation in python. Unless you're asking about the tabs vs. spaces argument. In that case, people who use 4 spaces per level are 'correct'; people who use a different number of spaces are a bit less correct; people who use tabs are wrong; and people who mix spaces and tabs -- well, we don't talk about them in polite company. -- Grant Edwards grant.b.edwardsYow! NEWARK has been at REZONED!! DES MOINES has gmail.combeen REZONED!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Foxpro goto command and deleted records
On 2012-07-17, Ethan Furman wrote: > In Foxpro if you do a Foxpro? -- Grant Edwards grant.b.edwardsYow! I am NOT a nut at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 18/07/12 14:05, Steven D'Aprano wrote: On Wed, 18 Jul 2012 01:46:31 +0100, Andrew Cooper wrote: Take for example a Linux system call handler. The general form looks a little like (substituting C for python style pseudocode) if not (you are permitted to do this): return -EPERM if not (you've given me some valid data): return -EFAULT if not (you've given me some sensible data): return -EINVAL return actually_try_to_do_something_with(data) I’m feeling a bit fed uI’m feeling a bit fed uI’m feeling a bit fed u How would you program this sort of logic with a single return statement? That's not terribly hard. if not (you are permitted to do this): result = -EPERM elif not (you've given me some valid data): result = -EFAULT elif not (you've given me some sensible data): result = -EINVAL else: result = actually_try_to_do_something_with(data) return result A better example would involve loops. I used to hate programming in some versions of Pascal without a break statement: I needed a guard variable to decide whether or not to do anything in the loop! # pseudo-code for i in 1 to 100: if not condition: do_something_useful() Even with a break, why bother continuing through the body of the function when you already have the result? When your calculation is done, it's done, just return for goodness sake. You wouldn't write a search that keeps going after you've found the value that you want, out of some misplaced sense that you have to look at every value. Why write code with unnecessary guard values and temporary variables out of a misplaced sense that functions must only have one exit? Object Oriented programming is all about encapsulating human concepts in a way that makes sense to human beings. Make no mistake, it is NEVER the case that a software system is written for any other reason than to serve human beings. OO is more than just the mechanics of writing code, it's a state of mind. OO was 'invented' to address the many problems that beset increasingly complex software systems. The main problem was maintainability. Encapsulating a concept in a clear and concise way makes the code easier to understand. Sometimes this means writing code that is not 'optimal' for the machine. Good code should be readable as well as efficient but I contend that it is better to write something that is clear, concise and well encapsulated than always go for the 'meanest dog in the scrapyard' approach where a developer is determined to write unreadable code that shows how jolly clever he is. More often than not he is forced to admit six months down the line that he has no idea what his code does as he 'forgot' to comment it. I speak from bitter experience. This approach works for me. I have thousands of lines of code operating every day 'in the wild', everything from flight booking systems to real time odds arbitrage. Any developer who 'gets' OO can read and modify my code and I am very proud of this fact ... and I have never been forced to admit that I don't know what I wrote six months ago. If you are writing embedded systems that must have a very limited memory footprint then there is a case for conciseness over readability but even then it has to be maintainable Python looks like an interesting language and I will certainly spend time getting to know it but at the moment it seems to me that calling it an Object Oriented language is just plain misleading. There, I've said it, trolls and flamers beware, I take no prisoners. Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 18/07/12 15:34, Grant Edwards wrote: On 2012-07-17, Lipska the Kat wrote: and what's this obsession with 'correct' indentation of code ??? If you can explain to us Java's obsession with 'correct' placemnt of curly-braces, then you've explained indentation in python. I'm not getting into the curly braces wars. Life is just too short. Unless you're asking about the tabs vs. spaces argument. In that case, people who use 4 spaces per level are 'correct'; people who use a different number of spaces are a bit less correct; people who use tabs are wrong; hmm, I've been using tabs ... still, why use one key press when you can use 4 ;-). Actually I quite like this aspect of Python, it's rapidly growing on me. Wonder if I could introduce this in a future release of Java ... nah, I'd be dead within a week %-( and people who mix spaces and tabs -- well, we don't talk about them in polite company. -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 7/18/2012 9:34 AM, Grant Edwards wrote: > people who us tabs are wrong Don't make me get my flamethrower! > and people who mix spaces and tabs -- well, we don't > talk about them in polite company. Mixing can make sense, but not in Python. *hides* -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Thu, Jul 19, 2012 at 12:40 AM, Lipska the Kat wrote: > Python looks like an interesting language and I will certainly spend time > getting to know it but at the moment it seems to me that calling it an > Object Oriented language is just plain misleading. Python isn't object oriented in the way Java is ("EVERYTHING has to be in a class! Look, it's all OO now!"). It simply says that, well, what's the difference? That integer you're holding. That's an object. Your function is an object. The module you're in, your "global scope", is an object too, and can be passed around. Python doesn't care about buzzwords, it cares about making code. Of course, the simplicity of Python's object model has its costs too. Every little integer has to be memory-managed and garbage-collected (eg in CPython, they're all refcounted). That has a performance hit. But not all that big a hit, and it is so handy when you want your function to be able to accept, and distinguish between, different types of object - you don't have to write one version that takes an integer and a different one that takes a heap object. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Thu, Jul 19, 2012 at 12:48 AM, Lipska the Kat wrote: > hmm, I've been using tabs ... still, why use one key press when you can use > 4 ;-). Actually I quite like this aspect of Python, it's rapidly growing on > me. Wonder if I could introduce this in a future release of Java ... nah, > I'd be dead within a week %-( First let's get Python working properly. The "from __future__ import braces" statement still doesn't work on any of the released versions. After that, we can consider fixing Java to do the converse. We must meet half way, you know. As to tab vs spaces: I'm a fan of tabs, myself. There was an argument over the matter last year at work, and we settled on tabs because the one guy who reckons 1-2 space indent is plenty was then able to just set his editor to two-space tabs, and the rest of us could use a more reasonable width. Using tab characters in the file gives this flexibility. It separates the lexical structure ("this is three blocks in") from the visual display ("draw these glyphs 35mm from the left margin"). ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
Lipska the Kat wrote: On 18/07/12 14:05, Steven D'Aprano wrote: Even with a break, why bother continuing through the body of the function when you already have the result? When your calculation is done, it's done, just return for goodness sake. You wouldn't write a search that keeps going after you've found the value that you want, out of some misplaced sense that you have to look at every value. Why write code with unnecessary guard values and temporary variables out of a misplaced sense that functions must only have one exit? Object Oriented programming is all about encapsulating human concepts in a way that makes sense to human beings. Make no mistake, it is NEVER the case that a software system is written for any other reason than to serve human beings. OO is more than just the mechanics of writing code, it's a state of mind. I must admit I have no idea how we went from discussing Single Exit functions to the One True Purpose of Object Oriented Programming; are you saying that SE is one of the basic tenets of OO? OO was 'invented' to address the many problems that beset increasingly complex software systems. The main problem was maintainability. Encapsulating a concept in a clear and concise way makes the code easier to understand. Sometimes this means writing code that is not 'optimal' for the machine. Good code should be readable as well as efficient but I contend that it is better to write something that is clear, concise and well encapsulated than always go for the 'meanest dog in the scrapyard' approach where a developer is determined to write unreadable code that shows how jolly clever he is. More often than not he is forced to admit six months down the line that he has no idea what his code does as he 'forgot' to comment it. And one of the many reasons I love Python is that it is so easy to write clear, readable, and sometimes concise code (nested list comps are still a challenge for me). . . . Python looks like an interesting language and I will certainly spend time getting to know it but at the moment it seems to me that calling it an Object Oriented language is just plain misleading. Since *everything* in Python is an object, how can you /not/ call it an OO language? Sure, you don't have to use everything as an object -- plain functions exist -- kinda ;) Even functions live in some namespace: len() lives in __builtin__, any top level function lives in its module, etc. Oh, and namespaces are objects. It seems to me that Python is more about providing tools, and then staying out of your way. That works for me. Maybe it will work for you, too. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 18/07/12 16:09, Chris Angelico wrote: On Thu, Jul 19, 2012 at 12:48 AM, Lipska the Kat wrote: hmm, I've been using tabs ... snip We must meet half way, you know. Seems reasonable to me, I'll let you suggest it ;-) As to tab vs spaces: I'm a fan of tabs, myself. There was an argument over the matter last year at work, and we settled on tabs because the one guy who reckons 1-2 space indent is plenty was then able to just set his editor to two-space tabs, and the rest of us could use a more reasonable width. Using tab characters in the file gives this flexibility. It separates the lexical structure ("this is three blocks in") from the visual display ("draw these glyphs 35mm from the left margin"). OK, I'll set my tab to 4 spaces ... Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 18/07/12 16:32, Ethan Furman wrote: Lipska the Kat wrote: On 18/07/12 14:05, Steven D'Aprano wrote: Even with a break, why bother continuing through the body of the function when you already have the result? When your calculation is done, it's done, just return for goodness sake. You wouldn't write a search that keeps going after you've found the value that you want, out of some misplaced sense that you have to look at every value. Why write code with unnecessary guard values and temporary variables out of a misplaced sense that functions must only have one exit? Object Oriented programming is all about encapsulating human concepts in a way that makes sense to human beings. Make no mistake, it is NEVER the case that a software system is written for any other reason than to serve human beings. OO is more than just the mechanics of writing code, it's a state of mind. I must admit I have no idea how we went from discussing Single Exit functions to the One True Purpose of Object Oriented Programming; are you saying that SE is one of the basic tenets of OO? It's my fault, I get carried away sometimes. Maintainable code is one of the basic tenets of OO, it all seems so clear to me and I get frustrated when I think that others don't see the 'beauty' ... but then I come to my senses and realise that there is always another way to do things. Python looks like an interesting language and I will certainly spend time getting to know it but at the moment it seems to me that calling it an Object Oriented language is just plain misleading. Since *everything* in Python is an object, how can you /not/ call it an OO language? Obviously I can't. I can't make a call as I haven't studied the language yet. I just can't get my head around duck typing at the moment as it is just so ... different. Sure, you don't have to use everything as an object -- plain functions exist -- kinda ;) Even functions live in some namespace: len() lives in __builtin__, any top level function lives in its module, etc. Oh, and namespaces are objects. It seems to me that Python is more about providing tools, and then staying out of your way. That works for me. Maybe it will work for you, too. I hope so and thank you for being so calm and reasonable in your response. ~Ethan~ Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 07/18/2012 08:58 AM, Steven D'Aprano wrote: > > > > 2) To check your internal reasoning in a function or method. > > For example: > > def foo(something): > n = len(something) > x = math.sqrt(x) > # We expect that x must be less than half of n. > # E.g. n=100 gives 10 < 50, which is correct. > assert x < n//2 > process(n, x) > > > > For bonus points, can you see the mistake? The stated condition is wrong. > Without the assert, the process() code could go off and potentially > silently do the wrong thing, but the assert guards against that > possibility. And once I've had a bug report that my app raises an > AssertionError, I will go back and think more carefully about the > assertion that sqrt(n) is always less than half of n. > > There are actually two bugs in that function. One is in the assertion, but more importantly, there's a typo earlier. One that would give a traceback, so it would be caught quickly. UnboundLocalError: local variable 'x' referenced before assignment Once you change the argument of sqrt() to n, then you come to the problem you were expecting; if n has a value of 1, 2, or 3, 4, or 5 the assertion will fire. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Foxpro goto command and deleted records
On Jul 17, 2012, at 5:57 PM, Ethan Furman wrote: > In Foxpro if you do a > > GOTO 7 > > with deleted off and record 7 is deleted, the record pointer doesn't > move (at least in version 6). > > I don't like that. > > I see four other options: > > 0) don't move the pointer (listed for completeness) > 1) go to that record anyway > 2) go to the next undeleted record > 3) go to the seventh undeleted record (possibly the least practical) > 4) raise an exception > > Any opinions? It's been many years since I fired up VFP, but the above doesn't sound correct. If you have SET DELETED OFF and the GOTO 7, the pointer should move to the 7th record, whether it is marked deleted or not. With SET DELETED ON, the pointer should not move, since 7 is not a valid record. -- Ed Leafe -- http://mail.python.org/mailman/listinfo/python-list
Re: Foxpro goto command and deleted records
Ed Leafe wrote: On Jul 17, 2012, at 5:57 PM, Ethan Furman wrote: In Foxpro if you do a GOTO 7 with deleted off and record 7 is deleted, the record pointer doesn't move (at least in version 6). I don't like that. I see four other options: 0) don't move the pointer (listed for completeness) 1) go to that record anyway 2) go to the next undeleted record 3) go to the seventh undeleted record (possibly the least practical) 4) raise an exception Any opinions? It's been many years since I fired up VFP, but the above doesn't sound correct. If you have SET DELETED OFF and the GOTO 7, the pointer should move to the 7th record, whether it is marked deleted or not. With SET DELETED ON, the pointer should not move, since 7 is not a valid record. Your memory is good! I typed it in wrong. I still don't like it. Any opinion on the other four choices? I'm leaning towards 1, possibly with 4 as an option: def goto(self, recno, raise_if_deleted=True): if is_deleted(self[recno)) and raise_if_deleted: raise DbfError( "Record %d is deleted and use_deleted is False" % recno) self._index = recno Part of the reason I feel this is reasonable is that with my dbf module it is possible to create an index that does /not/ include certain records: def ignore_deleted(record): if dbf.deleted(record): return dbf.DoNotIndex return dbf.recno(record) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Foxpro goto command and deleted records
On Jul 18, 2012, at 12:16 PM, Ethan Furman wrote: > Your memory is good! I typed it in wrong. Well, I was an MVP for Visual Foxpro for 10 years, so... ;-) > I see four other options: > > 0) don't move the pointer (listed for completeness) > 1) go to that record anyway > 2) go to the next undeleted record > 3) go to the seventh undeleted record (possibly the least practical) > 4) raise an exception > > I still don't like it. Any opinion on the other four choices? I'm leaning > towards 1, possibly with 4 as an option: #4 is probably the most Pythonic approach. The calling code can then decide how to react to attempting to access a deleted record. Even if you're accessing data stored in VFP tables, your module should be as Pythonic as possible. > Part of the reason I feel this is reasonable is that with my dbf module it is > possible to create an index that does /not/ include certain records: Deleting a record in VFP doesn't remove it from the index; I believe it marks that index entry as deleted, too. I think that as long as you treat the deleted status as the same as any other boolean column you'll be good. -- Ed Leafe -- http://mail.python.org/mailman/listinfo/python-list
Re: Foxpro goto command and deleted records
On 18/07/2012 18:28, Ed Leafe wrote: On Jul 18, 2012, at 12:16 PM, Ethan Furman wrote: Your memory is good! I typed it in wrong. Well, I was an MVP for Visual Foxpro for 10 years, so... ;-) I see four other options: 0) don't move the pointer (listed for completeness) 1) go to that record anyway 2) go to the next undeleted record 3) go to the seventh undeleted record (possibly the least practical) 4) raise an exception I still don't like it. Any opinion on the other four choices? I'm leaning towards 1, possibly with 4 as an option: #4 is probably the most Pythonic approach. The calling code can then decide how to react to attempting to access a deleted record. Even if you're accessing data stored in VFP tables, your module should be as Pythonic as possible. I disagree. I think that if you can see it should be able to go to it. I think that the closest analogue is a list, although maybe you should be able to hide any records which are marked for deletion. # Print all of the names. records.include_deleted = True print("There are {} names".format(len(records))) for r in records: if r.deleted: print("\t{} (deleted)".format(r["name"])) else: print("\t{}".format(r["name"])) # Print all but the deleted names. records.include_deleted = False print("There are {} names".format(len(records))) for r in records: print(r["name"]) Part of the reason I feel this is reasonable is that with my dbf module it is possible to create an index that does /not/ include certain records: Deleting a record in VFP doesn't remove it from the index; I believe it marks that index entry as deleted, too. I think that as long as you treat the deleted status as the same as any other boolean column you'll be good. -- http://mail.python.org/mailman/listinfo/python-list
Re: Foxpro goto command and deleted records
On Jul 18, 2012, at 12:57 PM, MRAB wrote: >> #4 is probably the most Pythonic approach. The calling code can then >> decide how to react to attempting to access a deleted record. Even if you're >> accessing data stored in VFP tables, your module should be as Pythonic as >> possible. >> > I disagree. I think that if you can see it should be able to go to it. The use case was a deleted record with SET DELETED ON, which means you shouldn't "see" it. -- Ed Leafe -- http://mail.python.org/mailman/listinfo/python-list
Re: FORTH in Python (py4th.py)
7 Aralık 1994 Çarşamba 05:04:22 UTC+2 tarihinde Nick Seidenman yazdı: > Just for fun I sat down and started writing a forth interpreter in > python. I got as far as putting in control structs and decided I';d > better get back to my real job. It does make a nice little example of > many of the cooler features of the language. I hearby bequeath its > current incodation to the net. > > No arguments, now! ;) > > ---- > #!/usr/Util/bin/python > # > # @(#)py4th.py1.1 94/12/06 > # > # Forth in Python (py4th). > # > ##This module implements a postfix interpreter class that > ##can be instantiated as the inner interpreter or as a forth-ish > ##interactive interpreter. The inner interpreter has two methods > ##called p_compile and p_interp that are the core methods. Compile > ##takes a string argument and returns a list that is executable by > ##the p_interp method. > ## > ##As of this version (12/6/94) there are a few important features > ##that need to be added, namely if-else-then and do-loop structures. > ##Doing so may require that the "for" construct used in p_interp > ##be replaced by a while loop that iterates over the program with > ##a program counter instead of the nice, clean, pc-less way it's done > ##now. I had thought about implementing these as follows: > ## > ##for IF-ELSE-THEN: > ## > ##given -- IF wordlist1 ELSE wordlist2 THEN > ##wordlist1 and wordlist2 would be compiled as embedded > ##lists within the current list. For example: > ## > ##a @ if dup * else dup dup * * then > ## > ##would compile into > ## > ##['a', '@', 'if', ['dup', > '*'], 'else', [ 'dup', 'dup', > ## '*', '*']] > ## > ##so that p_interp could then treat the wordlists as single > ##words and pass then to recursive invocations of itself. > ## > ##I have a similar scheme in mind for DO-LOOPs. > ## > ##10 0 do i . cr loop > ## > ##would become > ## > ##['10', '0', 'do', ['i', > '.', 'cr', 'loop']] > ## > ##One way to do it might be to have a prepass before > ##p_interp and after p_compile. Since these control structures > ##are only allowed inside definitions, perhaps p_semicolon > ##could be where this happens. It could then build the > ##sublists and add the code required for loop increments > ##and proper skipping (else over if) and handling of omitted > ##parts (if without else or then). > ## > ##Loops use the variable name 'I' for the reference count. > ##The prepass mentioned above would generate code to store > ##the current value of 'I' (if any) as some internally known > ##variable (e.g., '__I__2371') and restore it once the loop > ##was finished. > ## > ##I have already put the skeleton code in for doing this. It's a > ##bit of a hack at this point but you can get the gist of what I have > ##in mind from in. > ## > ##Author: Nick Seidenman > ##SAIC > ##n...@osg.saic.com > > import string > import math > import sys > import stack > > StackUnderflow = 'StackUnderflow' > ExitNonError = 'ExitNonError' > InnerInterpreterError = 'InnerInterpreterError' > > > # InnerInterpreter takes a postfix expression in the form of > # a python list object and 'executes it'. It has it's own > # dictionary, which is initialized with the py4thon primatives and a few > > # Operational modes. > Execution = 'Execution' > Definition = 'Definition' > Forgetting = 'Forgetting' > Comment = 'Comment' > Variable = 'Variable' > > class InnerInterpreter: > > def __init__(self): > # Create a new stack and dictionary for this interpreter instance. > self.__stack = stack.Stack() > self.__rstack = stack.Stack() > self.__vocabulary = {} > self.__ulist = [] > self.__vars = {} > self.__vlist = [] > self.__mode = Execution > self.__lastmode = Execution > self.__runlevel = 0 > > # Initialize the new dictionary with words for the primitive > # functions. > self.__vocabulary['.'] = self.p_dot > self.__vocabulary['cr'] = self.p_cr > self.__vocabulary['+'] = self.p_plus > self.__vocabulary['-'] = self.p_minus > self.__vocabulary['*'] = self.p_multiply > self.__vocabulary['/'] = self.p_divide > self.__vocabulary['uminus'] = self.p_uminus > self.__vocabulary['^'] = self.p_exponent > self.__vocabulary['variable'] = self.p_variable > self.__vocabulary['!'] = self.p_assign > self.__vocabulary['@'] = self.p_dereference > self.__vocabulary['dup'] = self.p_dup > self.__vocabulary['swap'] = self.p_swap > self.__vocabulary['bye'] = self.p_bye > self.__vocabulary['forget'] = self.p_forget > self.__vocabulary[':'] = s
Finding duplicate file names and modifying them based on elements of the path
I have an interesting problem I'm trying to solve. I have a solution almost working, but it's super ugly, and know there has to be a better, cleaner way to do it. I have a list of path names that have this form: /dir0/dir1/dir2/dir3/dir4/dir5/dir6/file I need to find all the file names (basenames) in the list that are duplicates, and for each one that is a dup, prepend dir4 to the filename as long as the dir4/file pair is unique. If there are multiple dir4/files in the list, then I also need to add a sequence number based on the sorted value of dir5 (which is a date in ddMONyy format). For example, if my list contains: /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/file3 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file1 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/file1 /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/file3 Then I want to end up with: /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/qwer_01_file3 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/abcd_file1 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/xyz_file1 /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/qwer_00_file3 My solution involves multiple maps and multiple iterations through the data. How would you folks do this? -- http://mail.python.org/mailman/listinfo/python-list
Re: FORTH in Python (py4th.py)
On Wed, Jul 18, 2012 at 4:05 PM, wrote: > 7 Aralık 1994 Çarşamba 05:04:22 UTC+2 tarihinde Nick Seidenman yazdı: You realize that you're replying to a post from 1994? This code was written for Python 1.0. I'll be pretty impressed if it still works in 2.7. > Thank you for the code. How can i import stack? Where is the code for it? Google turns up this post, also from 1994: https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/5qBmi7K-mo4 Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding duplicate file names and modifying them based on elements of the path
"larry.mart...@gmail.com" writes: > I have an interesting problem I'm trying to solve. I have a solution > almost working, but it's super ugly, and know there has to be a > better, cleaner way to do it. ... > > My solution involves multiple maps and multiple iterations through the > data. How would you folks do this? You could post your code and ask for suggestions how to improve it. There are a lot of not-so-natural constraints in that problem, so it stands to reason that the code will be a bit messy. The whole specification seems like an antipattern though. You should just give a sensible encoding for the filename regardless of whether other fields are duplicated or not. You also don't seem to address the case where basename, dir4, and dir5 are all duplicated. The approach I'd take for the spec as you wrote it is: 1. Sort the list on the (basename, dir4, dir5) triple, saving original location (numeric index) of each item 2. Use itertools.groupby to group together duplicate basenames. 3. Within the groups, use groupby again to gather duplicate dir4's, 4. Within -those- groups, group by dir5 and assign sequence numbers in groups where there's more than one file 5. Unsort to get the rewritten items back into the original order. Actual code is left as an exercise. -- http://mail.python.org/mailman/listinfo/python-list
A thread import problem
I'm trying to do something rather tricky, in which a program imports a module that starts a thread that exec's a (possibly altered) copy of the source in the original program, and the module doesn't return. This has to do with an attempt to run VPython in the Mac Cocoa context, in which Cocoa is required to be the primary thread, making it necessary to turn the environment inside out, as currently VPython invokes the Carbon context as a secondary thread. I've created a simple test case, displayed below, that illustrates something I don't understand. The module reads the source of the program that imported it, comments out the import statement in that source, and performs an exec of the modified source. The module then enters an infinite loop, so that there is no return to the original program; only the exec-ed program runs, and it runs in a secondary thread. The puzzle is that if there is any later import statement in the exec source, the exec program halts on that import statement, with no error message. I saw a discussion that suggested a need for the statement "global math" to make the math import work, but that doesn't fix the problem. I've tried with no success various versions of the exec statement, with respect to its global and local environment. Can anyone explain why the math import statement causes a problem? Thanks for any advice you can give. Bruce Sherwood --- The main program: from import_test import * print('exec this file') global math from math import sin print(sin(3.14159/6)) - Contents of import_test: from threading import Thread from time import sleep import sys prog = open(sys.argv[0]).read() prog = '#'+prog # comment out the import statement print(prog) class worker(Thread): def run(self): print('start thread') exec(prog) w = worker() w.start() while True: sleep(1) -- http://mail.python.org/mailman/listinfo/python-list
Re: FORTH in Python (py4th.py)
On 18/07/2012 23:43, Ian Kelly wrote: On Wed, Jul 18, 2012 at 4:05 PM, wrote: 7 Aralık 1994 Çarşamba 05:04:22 UTC+2 tarihinde Nick Seidenman yazdı: You realize that you're replying to a post from 1994? This code was written for Python 1.0. I'll be pretty impressed if it still works in 2.7. You'll need to create a Stack class and replace the string exceptions, but once those are fixed, it appears to work OK in Python 2.7. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to configure Tkinter Listbox to disable state keeping selected item highlighted
On Tuesday, July 17, 2012 8:55:21 AM UTC-5, Sarbjit singh wrote: > I am having a problem configuring a listbox widget such that the selection > remains highlighted even while it is set (programmatically) to the DISABLED > state. Below code shows the problem: > > from Tkinter import * > master = Tk() > listbox = Listbox(master) > listbox.pack() > listbox.insert(END, "Text1") > listbox.insert(END, "Text2") > listbox.insert(END, "Text3") > listbox.selection_set(first=0, last=None) > listbox.configure(exportselection=False) > listbox.configure(state=DISABLED) > > Now when I change state to NORMAL, selected item is being highlighted. Is > there a way I could disable widget (i.e. No response on mouse clicks) but > keep the selected object remain highlighted? > > Intent: I want to utilise this widget on wizard App that I am creating. I > would like this widget to indicate the current page / wizard number which the > user selected. Is there any other widget I could use instead of it? (Labels > possibly?) On Tuesday, July 17, 2012 8:55:21 AM UTC-5, Sarbjit singh wrote: > I am having a problem configuring a listbox widget such that the selection > remains highlighted even while it is set (programmatically) to the DISABLED > state. Below code shows the problem: > > from Tkinter import * > master = Tk() > listbox = Listbox(master) > listbox.pack() > listbox.insert(END, "Text1") > listbox.insert(END, "Text2") > listbox.insert(END, "Text3") > listbox.selection_set(first=0, last=None) > listbox.configure(exportselection=False) > listbox.configure(state=DISABLED) > > Now when I change state to NORMAL, selected item is being highlighted. Is > there a way I could disable widget (i.e. No response on mouse clicks) but > keep the selected object remain highlighted? > > Intent: I want to utilise this widget on wizard App that I am creating. I > would like this widget to indicate the current page / wizard number which the > user selected. Is there any other widget I could use instead of it? (Labels > possibly?) What's wrong with a page number displayed on a label? Why must you insist on displaying every page number in a Listbox? That seems like a waste of resources to me. You could even say: "Showing page I of N". -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding duplicate file names and modifying them based on elements of the path
On 19/07/12 08:20, larry.mart...@gmail.com wrote: I have an interesting problem I'm trying to solve. I have a solution almost working, but it's super ugly, and know there has to be a better, cleaner way to do it. I have a list of path names that have this form: /dir0/dir1/dir2/dir3/dir4/dir5/dir6/file I need to find all the file names (basenames) in the list that are duplicates, and for each one that is a dup, prepend dir4 to the filename as long as the dir4/file pair is unique. If there are multiple dir4/files in the list, then I also need to add a sequence number based on the sorted value of dir5 (which is a date in ddMONyy format). For example, if my list contains: /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/file3 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file1 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/file1 /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/file3 Then I want to end up with: /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/qwer_01_file3 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/abcd_file1 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/xyz_file1 /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/qwer_00_file3 My solution involves multiple maps and multiple iterations through the data. How would you folks do this? Hi Larry, I am making the assumption that you intend to collapse the directory tree and store each file in the same directory, otherwise I can't think of why you need to do this. If this is the case, then I would... 1. import all the files into an array 2. parse path to extract forth level directory name and base name. 3. reiterate through the array 3.1 check if base filename exists in recipient directory 3.2 if not, copy to recipient directory 3.3 if present, append the directory path then save 3.4 create log of success or failure Personally, I would not have some files with abcd_file1 and others as file2 because if it is important enough to store a file in a separate directory you should also note where file2 came from as well. When looking at your results at a later date you are going to have to open file2 (which I presume must record where it relates to) to figure out where it came from. If it is in the name it is easier to review. In short, consistency is the name of the game; if you are going to do it for some then do it for all; and finally it will be easier for others later to work out what you have done. -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Pythonhttp://www.fossworkflowguides.com/scripting -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
"Lipska the Kat" wrote in message news:c76dnv778_sw4zvnnz2dnuvz8ukdn...@bt.com... On 18/07/12 01:46, Andrew Cooper wrote: if not (you are permitted to do this): return -EPERM if not (you've given me some valid data): return -EFAULT if not (you've given me some sensible data): return -EINVAL return actually_try_to_do_something_with(data) How would you program this sort of logic with a single return statement? This is very common logic for all routines for which there is even the remotest possibility that some data has come from an untrusted source. someType result = -EINVAL //or your most likely or 'safest' result if not (you are permitted to do this): result = -EPERM if not (you've given me some valid data): result = -EFAULT if not (you've given me some sensible data): result = -EINVAL else result = -EDSOMETHING return result } //cohesive, encapsulated, reusable and easy to read But, it works differently from the above. Perhaps replace some of those "if" statements with "elif". The "return" version is handy because it provides a quick escape mechanism without cluttering up the rest of code with extra variables. -- Bartc -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Wed, 18 Jul 2012 15:48:28 +0100, Lipska the Kat wrote: > On 18/07/12 15:34, Grant Edwards wrote: >> Unless you're asking about the tabs vs. spaces argument. In that case, >> people who use 4 spaces per level are 'correct'; people who use a >> different number of spaces are a bit less correct; people who use tabs >> are wrong; > > hmm, I've been using tabs ... still, why use one key press when you can > use 4 ;-). My editor lets me add four spaces with a single key press, and delete them again with another single key press. Personally, I think tabs make more sense for indents than spaces, but for compatibility with others who are not as enlightened and insist on using broken tools that cannot deal with tabs, I have reluctantly standardised on spaces for indentation. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Wed, 18 Jul 2012 12:33:01 -0400, Dave Angel wrote: > On 07/18/2012 08:58 AM, Steven D'Aprano wrote: >> >> For bonus points, can you see the mistake? [...] >> > There are actually two bugs in that function. One is in the assertion, > but more importantly, there's a typo earlier. One that would give a > traceback, so it would be caught quickly. > > UnboundLocalError: local variable 'x' referenced before assignment Good catch :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Thu, 19 Jul 2012 01:04:50 +1000, Chris Angelico wrote: > Python isn't object oriented in the way Java is ("EVERYTHING has to be > in a class! Look, it's all OO now!"). Actually, Python is more object-oriented than Java. In Python, everything is an object. We have no distinction between boxed and unboxed integers, for example -- all integers are boxed, always. (Of course, data structures written in C, for example the array type, can encapsulate unboxed native ints. But the array itself is still an object.) On the other hand, Python doesn't force you to program using an object- oriented style. If you want to write functional code like Haskell, you can. If you want to write Pascal-style procedural code, you can. If you prefer an imperative style closer to shell scripting, go right ahead. The only one of the major paradigms that Python doesn't naturally support is logic programming. So Python is simultaneously more *and* less object-oriented than Java. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 19/07/2012 02:14, Steven D'Aprano wrote: On Wed, 18 Jul 2012 15:48:28 +0100, Lipska the Kat wrote: On 18/07/12 15:34, Grant Edwards wrote: Unless you're asking about the tabs vs. spaces argument. In that case, people who use 4 spaces per level are 'correct'; people who use a different number of spaces are a bit less correct; people who use tabs are wrong; hmm, I've been using tabs ... still, why use one key press when you can use 4 ;-). My editor lets me add four spaces with a single key press, and delete them again with another single key press. Personally, I think tabs make more sense for indents than spaces, but for compatibility with others who are not as enlightened and insist on using broken tools that cannot deal with tabs, I have reluctantly standardised on spaces for indentation. """Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out.""" -- Georg Brandl -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Wed, 18 Jul 2012 15:40:00 +0100, Lipska the Kat wrote: [...] >> Even with a break, why bother continuing through the body of the >> function when you already have the result? When your calculation is >> done, it's done, just return for goodness sake. You wouldn't write a >> search that keeps going after you've found the value that you want, out >> of some misplaced sense that you have to look at every value. Why write >> code with unnecessary guard values and temporary variables out of a >> misplaced sense that functions must only have one exit? > > Object Oriented programming is all about encapsulating human concepts in > a way that makes sense to human beings. Make no mistake, it is NEVER the > case that a software system is written for any other reason than to > serve human beings. OO is more than just the mechanics of writing code, > it's a state of mind. Um, yes? I'm no sure what this has to do with single-exit functions/methods. You can just as easily write multi-exit methods in an OO language as in a non- OO language. So long as your language has a return statement which exits the function, you can have more than one. I am aware that some languages enforce a single exit point, but that seems to be an unnecessary restriction to me. Of course it does require discipline and/or sense to not write crap code: if you have a 300 line function or method, whether it has dozens of exits or just one, that is crap code in any language. But if the choice is to write a 20 line function with three exits, or a 30 line function with a single exit, there would have to be a good reason to prefer the single- exit version. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Need help connecting via a remote VPN
I need to connect to a site/server that's only accessible after logging into a remote VPN, then scan a directory for a file pattern and then copy those files. I know how to do the latter using glob, and I think I figured out how to connect to the VPN using win32ras and got a response that said "302 Found" but I'm not sure what to do after that. Some people recommended using SSH or fabric.api modules, but I couldn't find any examples that applied to what I'm trying to do. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help connecting via a remote VPN
On 07/18/2012 09:36 PM, The Coca Cola Kid wrote: > I need to connect to a site/server that's only accessible after > logging into a remote VPN, then scan a directory for a file pattern > and then copy those files. I know how to do the latter using glob, > and I think I figured out how to connect to the VPN using win32ras and > got a response that said "302 Found" but I'm not sure what to do after > that. Some people recommended using SSH or fabric.api modules, but I > couldn't find any examples that applied to what I'm trying to do. Starting a VPN simply makes it possible for IP packets to get to the specified machine. You still need to match some protocol that the particular remote machine can handle. SSH is probably the most common, but there are lots of other possibilities, some standard and some custom. So the question is what does the remote machine (server) support for file access? glob will work if the server supports mounting the remote partition as a file system. But there are no guarantees that that's possible. You haven't even said what the two operating systems involved are, though I can guess that the local machine is some version of Windows. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Thu, Jul 19, 2012 at 11:22 AM, Steven D'Aprano wrote: > On Thu, 19 Jul 2012 01:04:50 +1000, Chris Angelico wrote: > >> Python isn't object oriented in the way Java is ("EVERYTHING has to be >> in a class! Look, it's all OO now!"). > > Actually, Python is more object-oriented than Java. In Python, everything > is an object. We have no distinction between boxed and unboxed integers, > for example -- all integers are boxed, always. That was my point. Less hype about OO but everything really is an object. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Google the video "9/11 Missing Links". 9/11 was a Jew Job!
On Jul 18, 2012, at 11:47 PM, Nicky dsdsdsds wrote: > COPY THIS MESSAGE FAST BECAUSE JEWS AND TRAITORS DELETE IT FAST! > > Sometimes I wish this list was moderated... -Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: Google the video "9/11 Missing Links". 9/11 was a Jew Job!
On 19/07/2012 05:10, William Ray Wing wrote: On Jul 18, 2012, at 11:47 PM, Nicky dsdsdsds wrote: COPY THIS MESSAGE FAST BECAUSE JEWS AND TRAITORS DELETE IT FAST! Sometimes I wish this list was moderated... -Bill I do that, unofficially of course :) I routinely flag crap like this on gmane.org and google groups, and for any other Python list that I happen to read. -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On Jul 19, 6:34 am, Steven D'Aprano wrote: > On Wed, 18 Jul 2012 15:40:00 +0100, Lipska the Kat wrote: > > Object Oriented programming is all about encapsulating human concepts in > > a way that makes sense to human beings. Make no mistake, it is NEVER the > > case that a software system is written for any other reason than to > > serve human beings. OO is more than just the mechanics of writing code, > > it's a state of mind. > > Um, yes? Its not so much a question of language as in programming as language as in layman-speak. One characteristic with our field is that we take ordinary words and then distort them so much the original meaning is completely lost. Take 'computer' for example. For Turing a computer was a mathematician doing a computation with a pen and paper. He then showed how to de-skill the mathematician so much that a machine could do what he was doing. In trying that he also hit upon the limits of such 'de-skilling' -- human-computers routinely detect infinite loops, whereas machine-computers can never do so (in full generality). Ironically the important lesson is lost and today 'computer' is synonymous with machine. Here is Dijkstra on similar distortions with 'user' and 'intelligent': http://www.cs.utexas.edu/~EWD/transcriptions/EWD06xx/EWD618.html 'Object' (and OO) are similar messes. In layman-speak and object is well, a thing. - subject to space-laws like can only exist at one place at a time, there cannot be two objects at the same place and time etc. - subject to time-laws like coming into existence at some time and going out at some other - connotes inanimateness unlike other 'creatures' or 'beings'. When this metaphor works (for example as in guis and simulation) then we have success-stories like smalltalk and simula. When it doesn't the success is poorer. eg a programmer writing math software in/on a OO system may for example 'clone' a matrix. This may be good science-fiction; its bad math. And one of the most pervasive (and stupidist) metaphors is the parent- child relation of classes. Just for the record, in the normal world 'creatures/beings' reproduce and therefore inherit. Objects dont. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 7/18/2012 10:40 AM, Lipska the Kat wrote: fact ... and I have never been forced to admit that I don't know what I wrote six months ago. That is an explicit objective of Python's design. Python looks like an interesting language and I will certainly spend time getting to know it but at the moment it seems to me that calling it an Object Oriented language is just plain misleading. I just call it object-based and let be done with it, as I have no interest in arguing 'Object Oriented'. What perhaps *you* need to know, given your background, is that nearly all syntax and most builtin callables wrap special method calls that can be defined on user classes. 'a + b' is executed as something like try: return a.__add__(b) # or the C type slot equivalent except: # not sure what is actually caught try: return b.__radd__(a) # r(everse)add except: # ditto raise TypeError("unsupported operand type(s) for +: {} and {}".format(a, b)) [Syntax exceptions: =, and, or] 'len(x)' calls x.__len__ and checks that the return value can be interpreted as an integer (I believe that means that it is an int or has an __index__ method, so that it can be used as a sequence index) and that its value is >= 0. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list