Re: Editor Ergonomics [was: Important features for editors]
On Sat, 06 Jul 2013 16:04:00 +0100, rusi wrote: On Saturday, July 6, 2013 7:40:39 PM UTC+5:30, Skip Montanaro wrote: * a lot of typing, * use of modifier keys (ctrl, alt, command, etc) * movement between the mouse and the keyboard My own experience: The second 2 are the worse culprits. And while emacs is bad on the second, its excellent on the third -- to the extend that you 'live inside emacs,' you dont need the mouse. You clearly never trained as a classical pianist :-) -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a Program to Decompose a Number and Run a Function on that Decomposition
On Fri, 19 Jul 2013 00:04:33 +0100, CTSB01 wrote: On Thursday, July 18, 2013 6:49:03 PM UTC-4, Ian wrote: On Jul 18, 2013 4:23 PM, "CTSB01" wrote: > > File "", line 2 > ... rtn = [] > ^ The "..." is the continuation prompt from the interactive interpreter, not part of the code. Don't paste it into Python. Thanks Ian. That worked regarding that issue. Now I have an 'invalid syntax' issue unfortunately. def phi_m(x,m): rtn = [] for n2 in range(0, len(x)*m - 2): n = n2 / m r = n2 - n * m rtn.append(m * x[n] + r * (x[n + 1] - x[n])) print 'n2 =', n2, ': n =', n, ' r =' , r, ' rtn =', rtn rtn on the line print 'n2 =', n2, ': n =', n, ' r =' , r, ' rtn =', rtn Is it something obvious? Are you using Python 2.x or 3.x? That print statement is valid 2.x, but "print" is a function in Python 3, so the parameter need parentheses around them. This would all involve a lot less guesswork if you cut and pasted both your code and the error traceback. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP8 79 char max
On Mon, 29 Jul 2013 22:09:10 +0100, Steven D'Aprano wrote: On Mon, 29 Jul 2013 15:43:49 -0400, Devyn Collier Johnson wrote: In Python programming, the PEP8 recommends limiting lines to a maximum of 79 characters because "There are still many devices around that are limited to 80 character lines" (http://www.python.org/dev/peps/pep-0008/#code-lay-out). What devices cannot handle 80 or more characters on a line? The only one I can think of is actual xterms (Ctrl-Alt-Function key terminals on Unix and Linux). But I think that's actually a red-herring. At least for me, I don't care about devices with 80 character lines. (Smart phones? Or is that more likely to be 40 character lines?) I care about being able to put multiple windows side-by-side, or a single window with code in one pane and a class map at the side. I care about being able to copy and paste code into an email, or Usenet post, without it being mangled. I care about *never* having to scroll left-to-right in order to read a line. And most of all, I care about lines being short enough to read without eye strain and mental fatigue from excessive horizontal width. +1 I'm working on some shonky C code at the moment that inconsistent indentation and very long lines. It is extremely annoying not to be able to put the original code, my "translation" and sundry utilities all side-by-side on the same screen (and it's not a particularly small screen), and having to keep flipping between them slows me down dramatically. Long lines have no effect on the speed of the program, but they can have serious effects on the speed of the programmer. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP8 79 char max
On Tue, 30 Jul 2013 01:11:18 +0100, Joshua Landau wrote: On 30 July 2013 00:08, Rhodri James wrote: I'm working on some shonky C code at the moment that inconsistent indentation and very long lines. It is extremely annoying not to be able to put the original code, my "translation" and sundry utilities all side-by-side on the same screen (and it's not a particularly small screen), and having to keep flipping between them slows me down dramatically. Long lines have no effect on the speed of the program, but they can have serious effects on the speed of the programmer. Then just wrap it. This is a very automatable thing for editors. There might even be a clever hard-wrap somewhere. I just tried pyformat -- that works wonders. I tried that at first, but it actually made matters worse. "Simple" word-wrapping just broke the structural cues from indentation (which I'd already had to instruct my editor to make at least somewhat consistent). I couldn't just take in the code layout at a glance, I had to work at it. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: 2 + 2 = 5
On Wed, 04 Jul 2012 20:37:25 +0100, Paul Rubin wrote: I just came across this (https://gist.github.com/1208215): import sys import ctypes pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) five = ctypes.cast(id(5), pyint_p) print(2 + 2 == 5) # False five.contents[five.contents[:].index(5)] = 4 print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) Heh. The author is apparently anonymous, I guess for good reason. Someone's been writing FORTRAN again :-) -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing ISO date/time strings - where did the parser go?
On Sun, 09 Sep 2012 13:14:30 +0100, Roy Smith wrote: In article , Thomas Jollans wrote: The ISO date/time format is dead simple and well-defined. Well defined, perhaps. But nobody who has read the standard could call it "dead simple". ISO-8601-2004(E) is 40 pages long. A short standard, then :-) -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Obnoxious postings from Google Groups
On Fri, 02 Nov 2012 01:25:37 -, Steven D'Aprano wrote: Huh. If you're messing about with ancient[1] languages like Java, C# and especially C, you're not a real programmer. Real programmers use modern, advanced languages like D, Erlang, Go or Haskell. Advanced? Huh. I have here a language that does exactly what I want without all that messy syntax nonsense. I call it "Research Assistant." -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: loops
On Sun, 02 Dec 2012 22:28:48 -, Verde Denim wrote: Nicely done! That fixed it! Is that a version feature or should I take what I find in these books with a grain of salt? It's a difference between Python 2 and Python 3 (which is almost certainly what your book told you to). The other feature which you will trip over is that "print" was a keyword in Python 2, but is a function in Python 3. This happens to have made no difference in the example you gave, but try this: Python 3.2 (r32:88445, Oct 20 2012, 14:09:29) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. print(1,2,3) 1 2 3 Python 2.7.1+ (r271:86832, Sep 27 2012, 21:12:17) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. print(1,2,3) (1, 2, 3) -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Working with classes
On Mon, 03 Dec 2012 22:47:53 -, wrote: Hello, I've been working on this program for a long time but can't seem to get it to work. I'm sorry, you are going to have to be a lot clearer. It isn't even a little bit obvious what you are talking about, which rather makes me suspect this is a homework question :-) The first array is the input file, What array? Do you mean the string of numbers haphazardly separated by spaces, commas and equals signs? then a class, another class and the actual program. Are those in separate files? Your "import" statements suggest they are, but you don't give us any other hints. Could anyone see what is wrong? It's a bit hard to do that when you don't tell us what "right" means in this case, and why you think your program might be wrong. I'm sorry if the program doesn't make any sense at all I'm just starting to learn this. The program makes perfectly good sense, it is your description that I don't understand. Please tell us what it is supposed to do, and what makes you think it doesn't do it. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
On Sun, 23 Dec 2012 21:42:14 -, wrote: Okay, I try to publish this sample, and yes it's not a working piece of code, but I try to "draw" my problem that way. So instead of telling us what your problem is, you're going to give us an artist's impression of your code and leave us to guess? Sorry but I'm not bored enough to try. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart (Terminolgy): "Class"
On Mon, 14 Jan 2013 19:43:34 -, Peter wrote: Real mature lot of responses here guys - shows how much you have grown up. Reading this thread looked more like observing a bunch of 3rd grader - somebody offers an opinion and all you can do is ridicule it? Now read the rest of the thread. While it is true that Rick offers sufficiently many daft opinions that ridicule is actually likely to be the correct response, there have been detailed (and therefore ignored) responses pointing out his failure to understand both the English language and the last couple of decades of computer science. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: fputs
On Tue, 05 Jun 2012 14:54:54 +0100, hassan wrote: what is the equivalent to the php fputs in python The write() method of the file object. Though if you're asking the question like that, you need to read this: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files ...and stop trying to think in terms of PHP. While you can write PHP in any language (I know people who still write FORTRAN, whatever language they might be using), you'll find that getting into the right mindset for whatever language you are using works a lot better. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: doing cross platform file work
On Thu, 23 Jun 2011 08:13:18 +0100, Gurpreet Singh wrote: ...Cygwin spam. Twice. Please don't mail to both comp.lang.python and python-list. They are gatewayed to each other, so we see your messages twice, which makes us roughly half as likely to respond to them. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Community Involvement
On Thu, 04 Aug 2011 18:04:48 +0100, Ethan Furman wrote: Of the two, I like the StackOverflow option better -- but keep in mind that at this moment, about 6,600 unanswered Python questions remain. (I've made it to page 23 of 132 over the last week.) Getting an answer upvoted can be pretty hit-and-miss. The other thing that may affect this is that anything posted to SE is subject to the Creative Commons license. This may be an issue for academic purposes, I don't know. (It's certainly an issue when you come across J*ff!) -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: List spam
On Thu, 18 Aug 2011 16:00:40 +0100, Jason Staudenmayer wrote: I'm a strong opponent of dropping any email with a stupid footer spam. By contrast, an excessively large sig (particularly an excessively large sig without a proper separator) is something that's guaranteed to get on my wick, and usually indicates someone I don't want to bother listening to. Thank you for trimming it. I'm reading this as the comp.lang.python newsgroup, straight off an NNTP server, and to be honest I'm not getting the level of spam you are talking about. There's some, sure -- usually for Bollywood actress pictures -- but not enough to make me worry about Opera's relatively poor newsgroup filtering facilities. If you're getting as much as you say, it's being injected on the mail side of the gateway somehow. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Word Perfect integration
On Thu, 18 Aug 2011 20:24:17 +0100, Ethan Furman wrote: Alec Taylor wrote: wow, people still use WordPerfect? Them's fightin' words right there! :) Yes, we still use Word Perfect, and will as long as it is available. The ability to see the codes in use (bold, margins, columns, etc) has so far been unequaled in anything else I have looked at. I take it you haven't looked at TeX, then? :-) -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Defining class attributes + inheritance
On Wed, 09 Mar 2011 00:29:18 -, Martin De Kauwe wrote: On Mar 9, 10:20 am, Ethan Furman wrote: [snip] Just make sure and call the parent's constructor, either with class NewClass(BaseClass): def __init__(self, ): BaseClass.__init__(self, other_params) or class NewClass(BaseClass): def __init__(self, ): super(NewClass, self).__init__() ~Ethan~ Hi thanks, but I think I am implementing it wrong then? BaseClass has 4 attributes and when I tried what you said class NewClass(BaseClass): def __init__(self): super(NewClass, self).__init__(new_thing) I get the error TypeError: __init__() takes exactly 1 argument (6 given) Please give us either the rest of the code or the rest of the traceback, or preferably both. Without one or the other we have little hope of guessing what you've typed. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Defining class attributes + inheritance
On Wed, 09 Mar 2011 01:00:29 -, Martin De Kauwe wrote: class BaseClass(object): def __init__(self, a, b, c, d): self.a = a self.b = b self.c = c self.d = d class NewClass(BaseClass): def __init__(self): super(NewClass, self).__init__(new) self.new = new print self.new Two things leap out immediately. First, BaseClass.__init__ takes four parameters besides `self`, but when you call it you only give it one parameter, `new`. It's not going to like that. Second, where did `new` come from? It's not a parameter to NewClass.__init__, and it doesn't seem to be a global. That's not going to work well either. However neither of these things are what the traceback is complaining about. if __name__ == "__main__": A = PreviousClass(1, 2, 3, 4, 5) B = NewClass(1, 2, 3, 4, 5) $ python test.py Traceback (most recent call last): File "model_data.py", line 29, in B = NewClass(1, 2, 3, 4, 5) TypeError: __init__() takes exactly 1 argument (6 given) When you create your NewClass, you give it five parameters (1, 2, 3, 4, 5) plus the implicit `self`, which is the "(6 given)" part of the message. However NewClass.__init__ takes no parameters aside from `self` (i.e. it "takes exactly 1 argument"). There's a mismatch between what you've told NewClass.__init__ to expect and what you actually deliver to it. The point that may be confusing you is that NewClass.__init__ knows nothing at all about BaseClass.__init__. It doesn't inherit parameters from it or anything magical like that; you have to tell it everything. If you want parameters to pass from NewClass.__init__ to BaseClass.__init__ you will have to provide them somehow. In this case, I think what you meant was something like this: class NewClass(BaseClass): def __init__(self, a, b, c, d, new): super(NewClass, self).__init__(a, b, c, d) self.new = new # etc -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: class error
On Sat, 19 Mar 2011 02:15:55 -, Terry Reedy wrote: On 3/18/2011 5:27 PM, monkeys paw wrote: TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) OK, i overlooked that and the error was not very enlightening. A detailed explanation: every module is an instance of a class we will call Module. Every class is an instance of some class, its metaclass. The default metaclass, in the absence of any indication otherwise, is class type. So your class statement was translated to type('FileInfo',(UserDict,), d) where d is a dict mappint '__init__' to the function object. type.__new__ checks the types (metaclasses) of each of the base classes. In particular, it sees that type(UxerDict) is Module, not type. Since it assumed that UserDict is a class (since you said it was), it assumed that Module is a proper metaclass and called Module('FileInfo',(UserDict,), d) But Module is not a metaclass and does not expect the tuple of base classes, and Module.__new__ passed too much to Module.__init__. Since others have made the same mistake, I opened an issue to improve the message. http://bugs.python.org/issue11604 It has to be said that the confusion is exacerbated by ignoring PEP-8 and using the same (CamelCase) name for the module and the class. That does provide a rich source of errors in cases like this. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex in if statement.
On Mon, 21 Mar 2011 00:46:22 -, Ken D'Ambrosio wrote: Hey, all -- I know how to match and return stuff from a regex, but I'd like to do an if, something like (from Perl, sorry): if (/MatchTextHere/){DoSomething();} How do I accomplish this in Python? The basic routine is to do the match and test the returned object: match_obj = re.match(pattern, string) if match_obj is not None: do_something(match_obj) If you don't need the match object (you aren't doing group capture, say), obviously you can fold the first two of those lines together. This can be a bit of a pain if you have a chain of tests to do because of having to stop to save the match object. To get around that, wrap the match in something that stashes the match object. Here's a primitive class-based version: import re class Match(object): def __init__(self): self.match_obj = None def match(self, *args, **kwds): self.match_obj = re.match(*args, **kwds) return self.match_obj is not None match = Match() if match.match(pattern1, string1): do_something(match.match_obj) elif match.match(pattern2, string2): do_something_else(match.match_obj) Knowing more about what it is you want to do, you should be able to do better than that. As other people have said though, regular expressions are often overkill, and it's worth thinking about whether they really are the right answer to your problem. Coming from Perl, it's easy to get into the mindset of applying regexes to everything regardless of how appropriate they are. I certainly did! -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Python problem
On Mon, 28 Mar 2011 22:38:29 +0100, John Parker wrote: infile = open("scores.txt", "r") lines = infile.readlines() infile.close() tokens = lines.split(",") names = [] scores = [] [snippety snip] error: Traceback (most recent call last): File "Score_8.py", line 38, in tokens = lines.split(",") AttributeError: 'list' object has no attribute 'split' So, what am I doing wrong? Exactly what the traceback says: you're taking `lines`, the list you created of all the lines in the file, and trying to split the list *as a whole* on commas. That doesn't work. You split strings, not lists. By the looks of it that line is something left over from a previous attempt. Just delete it, it's not doing anything useful for you. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: An unusual question...
On Sun, 17 Apr 2011 17:17:02 +0100, wrote: I`ll give you a clue... id(some_object) is close enough but NOT that close. You do realise that what id() returns is implementation-dependent, don't you? In particular, what IronPython returns isn't an address. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: An unusual question...
On Mon, 18 Apr 2011 08:01:00 +0100, wrote: Hi Rhodri... You do realise that what id() returns is implementation-dependent, don't you? In particular, what IronPython returns isn't an address. I'm pretty sure I wrote "standard Python" install in one of my replies. Yeah here it is in a reply to Miki... "Hmm, I was hoping to stay inside a standard Python install." IronPython *is* a standard Python install. So is CPython, the one I presume you mean. Even that doesn't offer you any guarantee that it isn't going to change what id() returns from one version to the next. Relying on implementation-defined behaviour like this is a good way of getting code to blow up in your face. You'll get much more reliable results by starting in a language that was actually intended for direct memory access, like C, and wrapping that in Python. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Popen to get stdout and stderr for ffmpeg - No such file or directory ?
On Tue, 19 Apr 2011 00:07:46 +0100, goldtech wrote: Trying to learn how to run a linux command and get the stdout and stderr. I'm trying the following: cmd3 = r'ffmpeg -i /home/giga/Desktop/Guitar1.flv' p = Popen(cmd3, stdout=PIPE, stderr=PIPE) Traceback (most recent call last): File "", line 1, in p = Popen(cmd3, stdout=PIPE, stderr=PIPE) File "/usr/lib/python2.6/subprocess.py", line 623, in __init__ errread, errwrite) File "/usr/lib/python2.6/subprocess.py", line 1141, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory This is something that catches everyone! From the Fine Manual (http://docs.python.org/library/subprocess.html#using-the-subprocess-module): On Unix, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. If a string is specified for args, it will be used as the name or path of the program to execute; this will only work if the program is being given no arguments. What you actually want is more like: p = Popen(('ffmpeg', '-i', '/home/giga/Desktop/Guitar1.flv'), stdout=PIPE, stderr=PIPE) The manual gives you an example of using shlex to split a string into tokens if you'd rather do it that way. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Namespaces in functions vs classes
On Tue, 19 Apr 2011 17:47:40 +0100, Gerald Britton wrote: Gerald Britton wrote: I now understand the Python does not consider a class definition as a separate namespace as it does for function definitions. That is a helpful understanding. That is not correct. Classes are separate namespaces -- they just aren't automatically searched. The only namespaces that are automatically searched are local, non-local, global, and built-in. I see you misunderstood my observation: Python does not consider a class definition as a separate namespace *as it does* for function definitions. This phrase normally parses as "Python does not consider a class definition as a separate namespace. In contrast, Python does consider a function definition as a separate namespace." If you meant "Python does not consider a class definition as a separate namespace *in the same way* that it does for function definitions," saying so would make life easier for the fairly large number of readers of this newsgroup whose first language isn't English. Language abuse: it's not just Python. A donation of just $5 will keep a programmer in prepositions for a month. $50 will supply enough articles to keep a small company understandable for over a year. With your generous help, we can beat this scourge! Ahem. Normal service will now be resumed. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: MIDI message sending and receiving, MID file manipulation
On Mon, 25 Apr 2011 14:17:50 +0100, Passiday wrote: Hello, I'd like to experiment with Python, connecting my Linux PC with MIDI device (standard synthesiser keyboard). I am pretty new to the Python world, so the questions that crop up, I assume, could be pretty basic to someone who had spent some time with it. So, here comes: 1) Is everything what could be done with Python in some IDE (Eclipse for me), can be accomplished in the interactive console? I mean, perhaps Python could be used just as programming language and compiled in binary code, thus allowing access to some binary libraries what might not be accessible from within the interpreter. This is two, or possibly three, distinct unrelated questions as best I can tell. 1a) Yes, anything you can do in an IDE you can do at the Python interactive command line prompt. Or by running your script directly in a terminal window. Personally I find it less hassle to do it that way, since IDEs usually don't work the way I want them to. 1b) Python can be compiled down to binary if you try hard, with utilities like Py2exe. You don't usually want to do that, though. 1c) ...because there are plenty of ways of wrapping up libraries so that Python scripts can use them. ctypes (in the standard library) is a good place to start. 2) Is there a way how to run Python script in event-driven mode, ie, run the script, it registers some function as keyboard event handler, and then calls that function whenever I press any key. Is such behaviour possible in the interactive mode? Since I want to test the MIDI message exchange, having a function sitting on the timer event is what I'll need for playback, and an event that is triggered by incoming MIDI message for recording. Probably. It sounds like what you really want is a framework of some sort that knows about things like "the timer event", and using it from the interactive prompt won't be for the faint of heart! Someone must have walked this path before, though. 3) Of course, I need some Python module to actually get this MIDI communication happen. Sending and receiving MIDI messages to and from my MIDI device. 4) As for manipulating the MIDI files in Python, I have searched up this: http://www.mxm.dk/products/public/pythonmidi However, this lib doesn't try to provide actual communication with MIDI device. The Python In Music wiki page (http://wiki.python.org/moin/PythonInMusic) has an entire section on MIDI packages. I've never used any of them, so I can't comment. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: use of index (beginner's question)
On Thu, 28 Apr 2011 01:49:33 +0100, Chris Angelico wrote: On Thu, Apr 28, 2011 at 10:42 AM, Rusty Scalf wrote: list1 = ['pig', 'horse', 'moose'] list2 = ['62327', '49123', '79115'] n = 2 s2 = "list" + `n` a = s2[list1.index('horse')] print a s2 is a string with the value "list2"; this is not the same as the variable list2. You could use eval to convert it, but you'd do better to have a list of lists: lists = [ ['pig', 'horse', 'moose'] ['62327', '49123', '79115'] ] Then you could use: n = 2 a = lists[n][list1.index('horse')] *cough* I think you mean n = 1 a = lists[n][list[0].index('horse')] The alternative would be to have a dictionary of lists: lists = { "list1": ['pig', 'horse', 'moose'], "list2": ['62327', '49123', '79115'] } n = 2 s2 = "list" + str(n) a = lists[s2][lists["list1"].index('horse')] Both of these can be made less ugly if the list you want to index into isn't one of the lists you might want to look up, but that's just a detail. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: obviscating python code for distribution
On Mon, 16 May 2011 03:21:00 +0100, Daniel Kluev wrote: On Mon, May 16, 2011 at 1:04 PM, Littlefield, Tyler wrote: Hello all: Finally, is there a good way to accomplish this? I know that I can make .pyc files, but those can be disassembled very very easily with the disassembler and shipping these still means that the person needs the modules that are used. Is there another way to go about this? No, there is no way to prevent users from getting access to raw python sources. By its nature and design, python is not meant to be used this way, and even obfuscation would not harm readability much. However, you can write all parts you want to hide in C/C++/Cython and distribute them as .so/.dll ...which is, of course, not exactly secure either. A sufficiently determined hacker won't have much trouble disassembling a shared library even if you do strip out all the debug information. By chance I'm having to do something closely related to this at work just at the moment; it's hard, but far from impossible. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner needs advice
On Tue, 31 May 2011 01:32:01 +0100, harrismh777 wrote: Steven D'Aprano wrote: Compatibility is inherently continuous, a matter of degree. Compatible by degrees is incompatible. Just 'how' incompatible determines whether the factor(s) are utterly useless, or just difficult to negotiate. (uh, oh,... me suspects another analogy fallacy coming up... ) This is especially true when it comes to languages, both natural and programming. ( Yup... analogy fallacy for Ænglisc speakers... ) I don't know about you, but I speak English not "Anglish". This is how an aesc is pronounced, after all. British English and American English are perhaps 99.5% compatible, but "table a motion" means completely opposite things in British and American English. (In Britain, it means to deal with it immediately; in the USA, it means to postpone it.) Should we conclude from this that British and American English are "different languages" and "completely incompatible"? We Americans have not spoken 'English' in well over two hundred years... :) roflol Quite the contrary, in fact. Much American usage of English actually better preserves the styles of eighteenth century English usage, having managed to avoid some of the "corrections" of Victorian grammarians. However, I guarantee that if I'm dumped unaided in Piccadilly I'll be able to hail a cab, pay my £12.00 and get myself to Liverpool Street Station, find the bathroom, and be on the correct train just in time for dinner, all without looking into the English dictionary. And I guarantee that you'd get odd looks for at least one of those. You may not notice; we Brits are used to translating the large amount of US TV we get back into British English. On the other hand (playing along with this analogy fallacy) if I dump a python newbie unaided in the middle of 2.5 and ask them to format a simple polytonic Greek unicode string and output it with print to stdout (redirected to a file) they will fail... maybe even if they have a dictionary ! Now this is an analogy fallacy, and an obvious one at that. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get values for skos/note, skos/notation and label in N-Triples
On 05/09/17 10:31, David Shi via Python-list wrote: <http://www.w3.org/2000/01/rdf-schema#label> "Baginton E04009817"@en .<http://opendatacommunities.org/id/geography/administration/par/E04009817> <http://www.w3.org/2004/02/skos/core#note> "Live" .<http://opendatacommunities.org/id/geography/administration/par/E04009817> <http://www.w3.org/2004/02/skos/core#notation> "E04009817" . Are there any hello world examples? Examples of what? You really must explain yourself clearly or we cannot help you. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Run python module from console
On 05/09/17 17:11, Stefan Ram wrote: Ned Batchelder writes: exec( compile( open( 'myscr.py', 'rb' ).read(), 'myscr.py', 'exec' )) . This looks quite complicated, but there are rumors that Python 4 might have a »execfile« function, and one then will be able to write: execfile( 'myscr.py' ) It's better to not start rumors about fictitious Python versions. That was an attempt to make a kind of joke. The background is: Python 2 has »execfile«, but not Python 3. Another background is: We recently had this discussion, where Steve wrote: |there should be a standard solution, instead of having to |re-invent the wheel over and over again. Even when the wheel |is only two or three lines. The difference is that inventing this particular wheel is almost always a mistake. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On 05/09/17 23:29, Grant Edwards wrote: On 2017-09-05, Marko Rauhamaa wrote: Pointer arithmetics is not an essential part of C. One could argue that it was a mistake to include it in the language. One may argue that it was a mistake, but I remember at least one implementation where pointer arithmetic was hugely more efficient than indexing into arrays. Incrementing a pointer through an array was way, way faster than indexing through the array by incrementing an array subscript. But, that was 25 years ago on an 8-bit CPU where where integer multiplies were expensive. The last time I compare the two methods with a recent GCC on a 32-bit CPU, it generated pretty much the same code either way... That's the optimiser at work, turning what you wrote into the best fit to the processor architecture. On an ARM, for example, that would likely still be incrementing a pointer through an array. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On 06/09/17 14:02, Stefan Ram wrote: Chris Angelico writes: The 'is' operator tests if two things are the same thing. »Roughly speaking, to say of two things that they are identical is nonsense, and to say of one thing that it is identical with itself is to say nothing at all.« Ludwig Wittgenstein, Tractatus Logico-Philosophicus (5.5303) Irrelevant. We are talking about identity, not identicallity (to coin a word). Or in plainer English, asking if two things are the same thing is not the same as asking if two things are identical. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: tictactoe script - commented - may have pedagogical value
On 06/09/17 18:16, Stefan Ram wrote: Dennis Lee Bieber writes: Not to mention there are four rotations of the board, along with reflections... One could, internally, keep track of the rotation needed to normalize the first moves (eg: if a corner was the first move, rotate the board as needed to make that corner the top-left; evaluate all moves from there, and "de-rotate" the response). Whenever someone yells at me, »HTML is not a programming language!«, I show them the interactive tic-tac-toe by Flo Kreidler, written in pure HTML: web.archive.org/web/20040428174214/http://www.geocities.com/flo_kreidler/tictactoe.html Presumably they stop taking you seriously at that point? -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: A question on modification of a list via a function invocation
On 08/09/17 13:45, Stefan Ram wrote: Gregory Ewing writes: [a random integer will on average have ] infinitely many digits -- despite every actual integer only having finitely many digits! This is not possible because every integer has a finite number of digits (in base 10). Surely an infinitely large integer has an infinite number of digits? -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: the core values of the Python "platform"
On 14/09/17 03:22, Stefan Ram wrote: Ben Finney writes (special characters edited): As I understand it, "flat is better than nested" is talking about *hierarchies* in a code base. It's not IIUC referring to anything about the difference between expressions like you wrote. I have read »import this« again, after reading the above, but there was no indication whatsoever in it that says that it was talking about "*hierarchies* in a code base" only. In any short, pithy commentary like the Zen, a great deal of what is said is implicit. Given your very literalist interpretations, I would suggest that trying to make deductions based on the Zen is a waste of time. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about modules documentation
On 15/09/17 18:05, Tobiah wrote: On 09/15/2017 09:25 AM, Stefan Ram wrote:> Tobiah writes: Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed .. When it refers to 'the imported module names' it sounds as though it is referring to the top level variables and functions in the imported module. A "module name" usually is the name of a module. When someone uses "module name(s)" it does /not/ sound as if he is using it to mean "the top level variables and functions in the named module(s)". Since the preceding sentence uses the plural "import statements", the next sentence has to use the plural "module names". 'next sentence' is the operative piece. I think that if the bit about placement was moved to the end of the paragraph the whole thing would be more readable and I wouldn't have stumbled on it. If it had meant "the imported module's names" or indeed "the imported modules' names", I would hope it would have said so. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells At Whippersnappers
On 19/09/17 16:00, Stefan Ram wrote: D'Arcy Cain writes: of course, I use calculators and computers but I still understand the theory behind what I am doing. I started out programming in BASIC. Today, I use Python, the BASIC of the 21st century. Python has no GOTO, but when it is executed, its for loop eventually is implemented using a GOTO-like jump instruction. Thanks to my learning of BASIC, /I/ can have this insight. Younger people, who never learned GOTO, may still be able to use Python, but they will not understand what is going on behind the curtains. Therefore, for a profound understanding of Python, everyone should learn BASIC first, just like I did! Tsk. You should have learned (a fake simplified) assembler first, then you'd have an appreciation of what your processor actually did. :-) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Old Man Yells At Cloud
On 18/09/17 16:29, Ben Bacarisse wrote: Steve D'Aprano writes: To answer your question, what do I mean by int/int being undefined, I'd have to dig into areas of maths that either weren't taught in the undergrad courses I did, or that I've long since forgotten about. Something about... fields? This is a pretty specialised area of maths. You won't learn anything about it in high school. And possibly not undergrad maths degrees. I seem to vaguely recall just barely touching on groups, but not rings or fields. When you said before that you thought that undefined division was rather obscure I was going to mention that it's the basic difference between a ring and a field; the intent being that you'd go "oh, yes, of course it's not obscure at all". I'm glad I didn't now, because you would not have seen it as the simple notion I expected! Teaching rings and fields is (or at least was 30 or so years ago) 1st year undergraduate maths here in the UK. Maybe it's changed. I think I achieved a nodding acquaintance with rings, fields and vector spaces in Further Maths (pre-university), and then got the real deal in my first term at university. I think they now happen later in the first year; looking at the on-line syllabus, the first two terms of IA Maths are now full of things that used to be taught at A-level. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells At Whippersnappers
On 19/09/17 16:59, Grant Edwards wrote: On 2017-09-19, Rhodri James wrote: On 19/09/17 16:00, Stefan Ram wrote: D'Arcy Cain writes: of course, I use calculators and computers but I still understand the theory behind what I am doing. I started out programming in BASIC. Today, I use Python, the BASIC of the 21st century. Python has no GOTO, but when it is executed, its for loop eventually is implemented using a GOTO-like jump instruction. Thanks to my learning of BASIC, /I/ can have this insight. Younger people, who never learned GOTO, may still be able to use Python, but they will not understand what is going on behind the curtains. Therefore, for a profound understanding of Python, everyone should learn BASIC first, just like I did! Tsk. You should have learned (a fake simplified) assembler first, then you'd have an appreciation of what your processor actually did. :-) Tsk, Tsk. Before learning assembly, you should design an instruction set and implement it in hardare. Or at least run in in a VHDL simulator. [Actually, back in my undergrad days we used AHPL and implemented something like a simplified PDP-11 ISA.] Eh, my school never 'ad an electronics class, nor a computer neither. Made programming a bit tricky; we 'ad to write programs on a form and send 'em off to next county. None of this new-fangled VHDL neither, we 'ad to do our simulations with paper and pencil. (All true, as it happens. My school acquired a computer (just the one: a NorthStar Horizon) in my O-Level year, but before that we really did have to send programs off to Worcester where someone would laboriously type them in for you. A week later you got a print out of the results and a roll of paper tape with your program on it.) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells At Whippersnappers
On 19/09/17 17:52, justin walters wrote: On Tue, Sep 19, 2017 at 9:12 AM, Rhodri James wrote: Eh, my school never 'ad an electronics class, nor a computer neither. Made programming a bit tricky; we 'ad to write programs on a form and send 'em off to next county. None of this new-fangled VHDL neither, we 'ad to do our simulations with paper and pencil. (All true, as it happens. My school acquired a computer (just the one: a NorthStar Horizon) in my O-Level year, but before that we really did have to send programs off to Worcester where someone would laboriously type them in for you. A week later you got a print out of the results and a roll of paper tape with your program on it.) What happened if there was a bug? Did you have to re-send it? Yes. We proofread our little programs very carefully after the first bug :-) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Even Older Man Yells at Whippersnappers
On 19/09/17 19:33, Larry Martell wrote: On Tue, Sep 19, 2017 at 1:38 PM, ROGER GRAYDON CHRISTMAN wrote: I recall giving a quiz to my college students sometime back around the late nineties which had a little bit of arithmetic involved in the answer. It's been too long ago to still have the exact details, but I remember a couple solutions that would be of the form: 5 + 10 + 1*2 And then the student would write he was unable to actually compute that without a calculator. And yes, I deliberately designed the questions to have such easy numbers to work with. It was my birthday the other day. People at worked asked how old I was. I replied: ((3**2)+math.sqrt(400))*2 Quite a few people somehow came up with 47. And these are technical people. You obviously look very spry for your age. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Old Man Yells At Cloud
On 19/09/17 19:31, bartc wrote: Can't you get around all those with things like sys.stdout.write? If so, what was the point of having a discrete print statement/function at all? Simplicity. It is much easier to explain to a beginner that print("Wombats are go!") will write something to the console rather than expecting them to remember the incantation import sys sys.stdout.write("Wombats are go!\n") (That's basically my gripe against print becoming a function in Python3. It makes a lot of sense as has already been pointed out, but it breaks every beginners tutorial.) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Old Man Yells At Cloud
On 21/09/17 16:12, Steve D'Aprano wrote: On Thu, 21 Sep 2017 08:19 pm, Rhodri James wrote: (That's basically my gripe against print becoming a function in Python3. It makes a lot of sense as has already been pointed out, but it breaks every beginners tutorial.) Nobody made that decision lightly. It wasn't a spur of the moment decision, Guido didn't wake up one morning and say "Hey, how about we break a whole lot of the Python ecosystem for giggles!" You can't fix mistakes without breaking things that depend on those mistakes. Oh, I don't doubt it, and Python3 is the better for it. It's just that my major use for Python at the time was teaching a summer course for 12-15 year olds, and switching to Python3 would have involved rewriting almost every worksheet we had. So we didn't. (Looking at the worksheet sources on Github, the course still hasn't made the switch!) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Old Man Yells At Cloud
On 21/09/17 17:31, Chris Angelico wrote: For a good while, I was in the same position. But instead of massively rewriting everything, all I did was to adjust the material to use Py2/Py3 compatible syntax. Adding parens around your print calls won't stop it from being Py2-compatible, and it means that the shift to Py3 becomes a lot easier. It's compatible syntax, but it doesn't half look weird in Py2. >>> x=2 >>> print("x is", x) ('x is', 2) >>> is very unfriendly to young beginners. We did consider it, but decided it was a non-starter; it was less effort to ignore Py3 entirely. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Call by binding [was Re: [Tutor] beginning to code]
On 25/09/17 15:26, Marko Rauhamaa wrote: Chris Angelico : On Mon, Sep 25, 2017 at 7:41 PM, Marko Rauhamaa wrote: In Python, all expressions evaluate pointers. And that's an assertion that isn't backed by anything in the Python specification. Where do you get that all Python expressions are pointers? That's not what I said. I said all expressions *evaluate to* pointers. This may well be true in particular implementations, but it is an implementation detail so Chris' point still stands. Another implementation could evaluate expressions to indices (as BCPL used to treat its globals), pieces of string or cheese, who knows? As for the specification, it doesn't make use of the word "pointer:" There's a reason for that... The (English) expression: The name is bound to the object. is just another way of saying: A pointer to the object is stored in the variable. It really isn't. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Call by binding [was Re: [Tutor] beginning to code]
On 25/09/17 20:40, Marko Rauhamaa wrote: Rhodri James : On 25/09/17 15:26, Marko Rauhamaa wrote: That's not what I said. I said all expressions *evaluate to* pointers. This may well be true in particular implementations, but it is an implementation detail so Chris' point still stands. Another implementation could evaluate expressions to indices (as BCPL used to treat its globals), pieces of string or cheese, who knows? Those are all pointers. A pointer is something that points to a data object. In that case you are using "pointer" in such an informal sense that making deductions from it is unlikely to be successful. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Call by binding [was Re: [Tutor] beginning to code]
On 25/09/17 21:00, Tim Golden wrote: (Slight sigh). Can I step in as a list owner and ask the people who are so very fond of debating this topic again and again: please let it drop. But, but... someone on the internet is wrong! https://www.facebook.com/playingrapunzel/videos/10153716804864491/ :-) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: style: single and multiple lines
On 02/10/17 17:00, Stefan Ram wrote: My copy of pep 8 (from 2016) says: Yes: def f(x): return 2*x . So this single-line style should not be that bad. However, I remember someone saying that the multiline style is more phytonic? So, is this better: def f(x): return 2*x Most of the time, yes. The whitespace on the left-hand side is a good visual cue that something content-like is happening, in this case the body of a function. The fact that it has shape makes it easier to comprehend at a glance. ? And is def f(x): y = x*2 return y better than def f(x): y = x*2; return y Hell yes. One thought per line, please. Something I keep repeating to clients is that whitespace is not the enemy. Not even in C. Judicious use of spacing can make code *much* easier to comprehend. Densely-written code makes you work hard to break it down into manageable chunks; something as simple as the odd blank line to "paragraph" your code can make that a lot easier. Experience also suggests a correlation between code that's hard to read and code that's rather crap. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: The "loop and a half"
On 03/10/17 18:29, Stefan Ram wrote: Is this the best way to write a "loop and a half" in Python? Define "best". x = 1 while x: x = int( input( "Number (enter 0 to terminate)? " )) if x: print( f'Square = { x**2 }' ) I'd usually write it as while True: x = tedious_function_call_with_sentinel() if x == 0: break do_something_with(x) ...or alternatively x = tedious_function_call_with_sentinel() while x != 0: do_something_with(x) x = tedious_function_call_with_sentinel() ...or some other refactoring. In a C-like language, one could write: while x = int( input( "Number (enter 0 to terminate)? " )) print( f'Square = { x**2 }' ) One could. One would richly deserve the compiler warnings one got as a result, but one could. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: The "loop and a half"
On 04/10/17 10:01, Robin Becker wrote: Given the prevalence of the loop and a half idea in python I wonder why we don't have a "do" or "loop" statement to start loops without a test. See PEP 315. Guido's rejection note is here: https://mail.python.org/pipermail/python-ideas/2013-June/021610.html -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: newb question about @property
On 04/10/17 12:07, bartc wrote: I've seen that example brought up before. It still doesn't cut any ice. You might as well be condescending of someone who finds Joyce or Proust unreadable, and prefers McBain, Simenon or Chandler. (Sorry, can't think of any modern pulp novelists). I don't think your comparison is appropriate. Joyce and Proust strike me as the literary equivalent of Perl or APL; very clever but nearly unreadable even for experts. No, think rather of Terry Pratchett. (Almost) anyone can read a Pratchett novel and enjoy it. Most people will not even notice maybe half the jokes. This is most obvious with The Colour of Magic and The Light Fantastic, where long-time Fantasy readers will spot Fafhrd and the Grey Mouser, recognise the tropes that are cheerfully being exploded, and so on. You can write decent Python without using decorators, properties, metaclasses or comprehensions in much the same way that you can enjoy Pratchett without ever having heard of Fritz Lieber. For a straightforward enough problem, writing your Python as if it was C won't even cause you any trouble. But if you think using these extra tools isn't programming, you are as flat out wrong as if you think Small Gods is just about a deity having to work on being believed in. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: newb question about @property
On 04/10/17 16:33, Paul Moore wrote: On 4 October 2017 at 16:03, bartc wrote: No error. Some would perceive all this as an advantage, but it means you can't just declare a lightweight struct or record 'Point' with exactly two fields x and y. You have to use other solutions ('namedtuples' or whatever, which probably are immutable so that don't work the same way). This is another example of neglecting the basics, but going for more advanced, perhaps more sexy features instead. It's another example of a consistent design philosophy (highly dynamic classes) that you might not like - possibly even enough that Python isn't the best language for you. It's not an advantage or a disadvantage, just an approach. Many people like it, you may not. Specifically, yes you can't "just declare a lightweight struct or record with exactly two fields". Actually you can: >>> class Point: ... __slots__ = ("x", "y") ... def __init__(self, x, y): ... self.x = x ... self.y = y ... def __str__(self): ... return "({0},{1})".format(self.x, self.y) ... >>> p = Point(3,4) >>> print(p) (3,4) >>> print(p.x) 3 >>> p.x = 7 >>> print(p) (7,4) >>> p.z = 2 Traceback (most recent call last): File "", line 1, in AttributeError: 'Point' object has no attribute 'z' I pretty much never bother to do this because (bart to the contrary) it isn't useful if you're thinking in Pythonic terms, but it can be done pretty easily. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: The "loop and a half"
On 05/10/17 19:45, bartc wrote: Yes, I tried typing 'sort' in Linux, where it apparently hangs (same on Windows actually). The reason: because it might have killed someone to have added a message saying what you are expected to type and how to end it. (Namely, press Ctrl-D start at the start of a line in Linux, and Ctrl-Z followed by Enter, I think also at the start, in Windows.) Actually it might. Linux tools are written not to assume that stdin and stdout are the console, because they frequently aren't. Extra puff written to stdout at best makes it harder to use in a pipeline, and at worst makes it useless; tools that do that tend not to get used. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: callable values
On 06/10/17 17:25, Stefan Ram wrote: Terry Reedy writes: On 10/6/2017 8:44 AM, ROGER GRAYDON CHRISTMAN wrote: Despite the documentation, I would still be tempted to say that range is a function. It is, *according* to the documentation. Built-in classes are included in Library Reference, Ch. 2, Built-in Functions. Changing that to "Built-in Functions and Classes" has been proposed (perhaps by me) and rejected. FWIW, in my course notes, I have coined a special word for this: A /prelate/ (German: "Prälat") is a callable value (object). I think I'll continue to call them callables. That way I won't burst into giggles when I accidentally think of them as church dignitaries. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 09/10/17 20:06, Stefan Ram wrote: r...@zedat.fu-berlin.de (Stefan Ram) writes: Steve D'Aprano writes: At various stages of education, we teach many lies-to-children, including: Many of those lies can be perfectly true in some sense. I pick some examples: Another noun phrase with "lie" is "white lie". In his book about programming, Bjarne Stroustrup writes: |We try hard to avoid "white lies"; that is, we refrain from |oversimplified explanations that are clear and easy to |understand, but not true in the context of real languages and |real problems. That would go a long way to explaining why I tried and failed to learn C++ three times from Stroustrup's books. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: on = style
On 09/10/17 08:46, Steve D'Aprano wrote: I truly believe that, with*very* few exceptions (*ALL* of which are some form of in-line data table, and even then only rarely) any programmer who worries about lining up assignments on different lines like this is just engaged in a time-wasting exercise to make themselves look busy while actually taking it easy. It is a pure avoidance activity. I'm inclined to disagree, at least in as much as I think the exceptions are more common than you do. For me at least there are two opposed principles: * Columnar data is easier to read. * Big gaps in the middle of a line make it hard to read. I fairly often line up initialisers height = 5 width = 10 length = 2 density = 0.75 ...or other related groups of assignments, but that takes a minute at most. When there is a huge mismatch in name length, aligning the columns is more tedious and gives you less visual advantage, so I don't bother. Somewhere in the middle is a tipping point. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 11/10/17 01:48, Bill wrote: Steve D'Aprano wrote: On Tue, 10 Oct 2017 06:06 am, Stefan Ram wrote: In his book about programming, Bjarne Stroustrup writes: |We try hard to avoid "white lies"; that is, we refrain from |oversimplified explanations that are clear and easy to |understand, but not true in the context of real languages and |real problems. Bjarne Stroustrup is famous for designing one of the most heavyweight, baraque, hard-to-understand, difficult-to-use programming languages in common use. While C++ has many excellent features, and is constrained by the need to be compatible with C, I don't think many people believe that it is a well-designed language. It is a well-designed language. It is and was carefully thought out. I was manfully trying not to head off on another OT trail, but this is simply not true. C++ is designed, true, but well designed? It has a fundamental flaw; it wants to be both a high-level language and compatible with C, under the mistaken impression that C is a high level language. Since C is actually an excellent macro-assembler, this dooms the exercise from the very start. C++ lives in the no-man's land between programming languages that care quite a lot what processor they are running on and programming languages that wouldn't recognise hardware if it came up and bit them. It can be used either way, but comes with all the baggage for both. I am yet to see a C++ program that wasn't more comprehensible when rendered as either C or Python (or the high-level language of your choice, I imagine). -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 11/10/17 15:36, Chris Angelico wrote: On Thu, Oct 12, 2017 at 1:14 AM, bartc wrote: Python, maybe. C syntax isn't as painful as C++ but I still have a lot of trouble with it. (Eg. the variable declaration 'char(*(*x[3])())[5]'. The name of the variable can be found lurking in that lot somewhere, but what's the type?) Not so convenient. People love showcasing stupid examples like that. But how often do you REALLY make declarations that complex? That's not technically strawmanning, since C syntax does indeed include that, but you're cherry-picking the most extreme example. That's only really one level more complex than declarations I use fairly regularly (I am an embedded system programmer most of the time). On the other hand, I never actually do declare things in that way: typedef is your friend, and makes your C code much easier to read. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Lies in education [was Re: The "loop and a half"]
On 12/10/17 16:06, Grant Edwards wrote: On 2017-10-12, Steve D'Aprano wrote: On Thu, 12 Oct 2017 04:41 pm, Grant Edwards wrote: Even two different C compilers could return different values. Nope. If sizeof char is not 1, then it's not C. Today I Learned. It sure was an education the first I wrote C code for a machine where 1 == sizeof char == sizeof int == sizeof long == sizeof float == sizeof double All were 32 bits. Ah yes. In my case it was 16 bits, so sizeof long == 2 just for a little variation. Writing protocol code that dealt with the outside world via a serial port was _painful_. Amen, brother. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: how to read in the newsreader
On 16/10/17 16:07, Grant Edwards wrote: Ah yes. I solved problem that by writing a wrapper around slrn so that my .newsrc and .score files reside "in the could". ^ Now there's a typo someone should run with :-) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: I used list, def. why li += [100, 200] , and li = li + [100, 200] is different
On 23/10/17 17:29, 임현준 wrote: I am a Korean student, and I am a beginner in English and Python.;( I can't understand about this def If I want to print [1,2,3,4,5] [1,2,3,4,5,100,200] I will make code like this, and I can understand code. def modify(li): li += [100,200] > list = [1,2,3,4,5] print(list) modify(list) print(list) Here is approximately what Python does when you run this: * Create a list [1,2,3,4,5] * Give the list the name "list". In talking about Python we often say that it *binds* the name "list" to the list [1,2,3,4,5]. (It is usually a bad idea to use names like "list" that also have a meaning in Python, but we will ignore that for now.) list \ +---+ | 1,2,3,4,5 | +---+ * Print the object bound to the name "list", which is the list [1,2,3,4,5]. * Call modify(). This also binds the name "li" to the object that "list" is bound to. list \ +---+ | 1,2,3,4,5 | +---+ li --/ * Create a new list [100,200] * "li += [100,200]" for a list means "change the list bound to the name 'li' by joining the new list onto the end of it. It is still the same object, it just has some more added to it. list \ +---+ | 1,2,3,4,5,100,200 | +---+ li --/ "list" is still bound to the same object, so you see the changes outside the function modify(). BUT, when I make code like this. I will make code like this, and I can understand code. def modify(li): li = li + [100,200] What happens here is a little different. It starts off the same with "li" and "list" bound to the same object: list \ +---+ | 1,2,3,4,5 | +---+ li --/ and a new object [100,200] that doesn't have a name. What happens next is: * Take the object bound to the name "li" and the unnamed object [100,200], and create a *new* object by joining them together. * Bind the name "li" to this new object list \ +---+ | 1,2,3,4,5 | +---+ li --\ +---+ | 1,2,3,4,5,100,200 | +---+ Notice that it is only the name "li" that is bound. The name "list" still refers to the original object. When we return from the function, we stop using the name "li" and nothing refers to our new object [1,2,3,4,5,100,200] any more. Python will quietly delete it ("garbage collect") in the background. The key is that "+" on its own creates a new object, while "+=" alters the existing object. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Invoking return through a function?
On 29/10/17 16:45, Alberto Riva wrote: On 10/29/2017 11:13 AM, bartc wrote: (What the OP wants was also proposed a few weeks back in comp.lang.c. But that was only within nested functions, so if H is inside G, and G is inside F, then a 'returnall' from H would return directly directly from F. Apparently Lisp allows this...) Well, not directly, but it can be simulated with the condition system (equivalent to try/except) or with throw/catch, which is similar but doesn't use exceptions. But my point was that in Lisp you don't need to do this, because you can write a macro that expands into a return *in place*, without calling a separate function, and this eliminates the problem entirely. Since Python doesn't have macros I was looking for the next-best solution, but there doesn't seem to be one. Oh, well... You can do the same in C. I've had the displeasure of trying to maintain such code. It was near-unreadable, because it constantly broke your expectations of what the code flow *could* be. The fact that something that could return from the middle of your function without the slightest indication was a rich source of bugs. (I didn't have to tell my boss to up our rates for dealing with this code. It took several days to do the work anyway, which was punishment enough at our rates.) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Coding style in CPython implementation
On 28/10/17 19:42, Στέφανος Σωφρονίου wrote: Greetings everyone. I have noticed that in many if conditions the following syntax is used: a) if (variable == NULL) { ... } b) if (variable == -1) { ... } c) if (variable != NULL) { ... } What I wanted to ask is, is there a particular reason for not choosing a) if (!variable) { ... } in place of if (variable == NULL) { ... }, "if (variable == NULL)" emphasises that "variable" is a pointer variable, aiding readability. b) if (-1 == variable) { ... } in place of if (variable == -1) { ... }, and It's just not natural English. It's safer to write it with the constant first, but modern compilers will warn you about assignments in conditions these days, and it's not worth the reduction in readability in my opinion. (Also, if you aren't using the -Werror -Wall flags to the compiler, you deserve everything that will be coming to you.) c) if (variable) { ... } in place of if (variable) { ... } ? I assume you mean "if (variable != NULL)" here. Again, it emphasises the type; variable will be a pointer. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Invoking return through a function?
On 31/10/17 02:06, Alberto Riva wrote: Steve D'Aprano gave you a pretty full answer, I just wanted to add: The kind of statement I was trying to add would at least have made that explicit: return-if-so-and-so-happens. That's only obvious in the function that's doing the returning. The function that's doing the calling that gets its expectation of flow control broken has no clue, and that's my problem. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Report on non-breaking spaces in posts
On 31/10/17 17:23, Stefan Ram wrote: Ned Batchelder writes:    def wrapped_join(values, sep): Ok, here's a report on me seing non-breaking spaces in posts in this NG. I have written this report so that you can see that it's not my newsreader that is converting something, because there is no newsreader involved. Here are some relevant lines from Ned's above post: |From: Ned Batchelder |Newsgroups: comp.lang.python |Subject: Re: How to join elements at the beginning and end of the list |Message-ID: Hm. That suggests the mail-to-news gateway has a hand in things. |Content-Type: text/plain; charset=utf-8; format=flowed |Content-Transfer-Encoding: 8bit |    def wrapped_join(values, sep): [snippety snip] |od -c tmp.txt |... |0012620 s u l a t e i t : \n \n   |0012640  d e f w r a p p e d _ |... | |od -x tmp.txt |... |0012620 7573 616c 6574 6920 3a74 0a0a c220 c2a0 |0012640 c2a0 20a0 6564 2066 7277 7061 6570 5f64 |... And you can see, there are two octet pairs »c220« and »c2a0« in the post (directly preceding »def wrapped«). (Compare with the Content-Type and Content-Transfer-Encoding given above.) (Read table with a monospaced font:) corresponding Codepoint UTF-8ISO-8859-1 interpretation U+0020?c2 2020? SPACE? U+00A0 c2 a0a0 NON-BREAKING SPACE This makes it clear that there really are codepoints U+00A0 in what I get from the server, i.e., non-breaking spaces directly in front of »def wrapped«. And? Why does that bother you? A non-breaking space is a perfectly valid thing to put into a UTF-8 encoded message. The 0xc2 0x20 byte pair that you misidentify as a space is another matter entirely. 0xc2 0x20 is not a space in UTF-8. It is an invalid code sequence. I don't know how or where it was generated, but it really shouldn't have been. It might have been Ned's MUA, or some obscure bug in the mail-to-news gateway. Does anyone in a position to know have any opinions? -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Code Snippets
On 01/11/17 18:57, Stefan Ram wrote: Ned Batchelder writes: You should not optimize for the shortest time to paste a line of code. You should take time and care writing your code, so that it reads best and runs best. If you needed another os function, would you have two __import__("os") in your code? Ugh. I make a distinction between two kinds of code: 1.) Quick-and-dirty code (rapid prototyping) One just wants to find out something using Python code. The code might be written into the Shell and not be saved, or only be saved temporarily. For example, what the sum of 5412 and 2141 is, or whether an idea for a program code works at all. The snippets are also intended for such code. 2.) Library-grade code This is code that might be around for a longer time and might be maintained in the future. It even is possible that it will become part of a library. It is possible that qnd-code might evolve into lg-code. In this case, it is still possible to remove all »__imports__«. Your comments might apply more to lg-code than to qnd-code. The bad thing here is that you are training yourself in a coding style (quick and dirty) that ought to be rejected in any code that isn't completely ephemeral. And in my experience, most "throw-away" code isn't thrown away. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Packages Error - Unresolved
On 02/11/17 11:17, Hinds, Megan wrote: Hi there, I was hoping you could help, as I have tried many different websites on this query and even asked the question on stackflow. I have tried many different types of commands in command prompt with the same error. I have recently installed Python 3.6. The 32 bit installation (automatically downloaded to this). I have set the correct environment path variables: C:\Users\MH\AppData\Local\Programs\Python\Python36-32;C:\Users\MH\AppData\Local\Programs\Python\Python36-32\Scripts; I am on a work laptop with admin rights. A few days ago I could install python packages using the following command in command prompt (in python36-32 directory): pip install -index-url=http://pypi.python.org/simple -trusted-host pypi.python.org pandas I managed to install pillow, cx_Oracle, and a few others previously. But not pandas and others (see attached file). I was thinking to move on to anaconda, however, I may see the same error in installing packages in there (Oracle related packaged that are not in conda). I would be very grateful for any help. I'm afraid the mailing list has stripped your attachments (as well it should, since this is also a newsgroup). Could you repeat them in the body of your message? If they include the exact error messages and any traceback, that would be a great help. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Thread safety issue (I think) with defaultdict
On 02/11/17 20:24, Chris Angelico wrote: Thank you. I've had this argument with many people, smart people (like Steven), people who haven't grokked that all concurrency has costs - that threads aren't magically more dangerous than other options. I'm with Steven. To be fair, the danger with threads is that most people don't understand thread-safety, and in particular don't understand either that they have a responsibility to ensure that shared data access is done properly or what the cost of that is. I've seen far too much thread-based code over the years that would have been markedly less buggy and not much slower if it had been written sequentially. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Thread safety issue (I think) with defaultdict
On 03/11/17 14:50, Chris Angelico wrote: On Fri, Nov 3, 2017 at 10:26 PM, Rhodri James wrote: On 02/11/17 20:24, Chris Angelico wrote: Thank you. I've had this argument with many people, smart people (like Steven), people who haven't grokked that all concurrency has costs - that threads aren't magically more dangerous than other options. I'm with Steven. To be fair, the danger with threads is that most people don't understand thread-safety, and in particular don't understand either that they have a responsibility to ensure that shared data access is done properly or what the cost of that is. I've seen far too much thread-based code over the years that would have been markedly less buggy and not much slower if it had been written sequentially. Yes, but what you're seeing is that *concurrent* code is more complicated than *sequential* code. Would the code in question have been less buggy if it had used multiprocessing instead of multithreading? What if it used explicit yield points? My experience with situations where I can do a reasonable comparison is limited, but the answer appears to be "Yes". Multiprocessing brings with it a whole lot of extra complications around moving data around. People generally understand how to move data around, and the mistakes are usually pretty obvious when they happen. People may not understand how to move data around efficiently, but that's a separate argument. Multithreading brings with it a whole lot of extra complications around NOT moving data around. I think this involves more subtle bugs that are harder to spot. People seem to find it harder to reason about atomicity and realising that widely separated pieces of code may interact unexpectedly. Yield points bring with them the risk of locking another thread out unexpectedly (particularly since certain system calls aren't async-friendly on certain OSes). I've got to admit I find coroutines straightforward, but I did cut my teeth on a cooperative OS. It certainly makes the atomicity issues easier to deal with. All three models have their pitfalls. Assuredly. I just think threads are soggier and hard to light^W^W^W^W^W prone to subtler and more mysterious-looking bugs. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Thread safety issue (I think) with defaultdict
On 03/11/17 18:12, Israel Brewster wrote: On Nov 3, 2017, at 7:11 AM, Rhodri James wrote: People generally understand how to move data around, and the mistakes are usually pretty obvious when they happen. I think the existence of this thread indicates otherwise :-) This mistake was far from obvious, and clearly I didn't understand properly how to move data around *between processes*. Unless you are just saying I am ignorant or something? :-) Ah, but from the point of view of this argument, you didn't make a mistake, you made a meta-mistake. It wasn't that you didn't understand how to move data around between processes, it was that you didn't think you were moving between processes! Whether or not you do understand remains to be seen :-) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Ideas about how software should behave
On 09/11/17 17:41, Michael Torrie wrote: On 11/09/2017 09:33 AM, Chris Angelico wrote: On Fri, Nov 10, 2017 at 2:14 AM, Rurpy via Python-list wrote: On 11/08/2017 11:29 AM, Chris Angelico wrote: [...] Please, Jon, accept that we were not deliberately trying to put you down. Steve, if you can clearly state your position on this (possibly worded in the form of an apology?), it would go a long way to clearing this up. ChrisA Are you the same ChrisA who wrote in this very list just a month ago towards a poster you disagreed with: "Yep. Good reasons like that you're a moron." [*] If I said that, there's more to it than just that I disagreed with the person. But how does that justify the comment? Sounds like a rationalization to me. A little humility on all our parts goes a long ways. One can apologize for offense taken, even if none was intended, and even if my own opinion is still strongly held. But some people really do behave moronically on this list. I generally killfile them before the urge to insult gets too strong, but I do see Chris's point; leaving people with the idea that unacceptable behaviour is acceptable is a service to no one. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Python homework
On 07/12/17 13:19, Mario R. Osorio wrote: On Tuesday, December 5, 2017 at 8:33:52 PM UTC-5, nick martinez wrote: I have a question on my homework. [snip] Just my 2 cents: Sigh. Please don't do people's homework for them. It doesn't teach them anything. Now Nick had got 90% of the way there and shown his working, which is truly excellent, but what he needed was for someone to hint at how to search through the array, not to be handed a working example with no explanation. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Please tell me how to execute python file in Ubuntu by double
On 14/12/17 07:25, Chris Angelico wrote: So it's an imperfect solution even as far as it goes, and a highly limiting way to do things. I'm sure it made good sense back when MS-DOS file systems ruled the Windows world, and 8.3 was just the way of things. Even then there was RiscOS, which divorced file names from file types entirely. A file's type was part of its directory data, and that was what determined what happened when you double-clicked on it. You were still limited to only one default application (and icon, and so on) per file type, so OS/2 still wins on that front, but I always felt that having names determine types was somehow mucky. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Answers to homework questions [WAS]: Re: Python homework
On 14/12/17 10:22, Lorenzo Sutton wrote: Hi Roger, On 13/12/17 23:31, ROGER GRAYDON CHRISTMAN wrote: On Wed, Dec 13, 2017, Lorenzo Sutton wrote: On 05/12/17 06:33, nick martinez2 via Python-list wrote: I have a question on my homework. [...] For this kind of problem I think the collections module [1] can be very useful. In this case in particular have a look at the Counter package ;) [...] A nice answer at face value, and for general questions, but perhaps not the best given the subject line and the first sentence in the OP's note. > [...] When I teach my course, I have no desire to have all my students turn into cargo cultists. At least this particular student did post his intended solution, instead of outright begging for code. And most of the responses I see did attempt to work within the perceived constraints regarding what language tools the student was expected to use. I see your point as a teacher, but after all this *is* a Python mailing list and not a python-homework-support mailing list. That implies you shouldn't have answered a homework assignment at all :-p -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Learning
On 18/12/17 13:28, Marko Rauhamaa wrote: However, I have been doing quite a bit of hiring, quite successfully, I might add. I am not prejudiced one way or another. Your résumé doesn't count. Your education doesn't count. What you can do for the team counts, and that is measured during the interview process. While I agree with most of what you say, I disagree with you here. Your CV (résumé) does count, just not necessarily in the way most people expect. I haven't often been involved in hiring, but the few times I have we had more applicants than it was feasible to interview. We used CVs as the only thing we had to filter with, looking for *interesting* people. Exactly what "interesting" meant was somewhat arbitrary; we put one person through to interview because she was a cellist, and that would have given us a complete string quartet (she didn't get the job, sadly). -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Learning
On 18/12/17 16:33, Marko Rauhamaa wrote: Rhodri James : I haven't often been involved in hiring, but the few times I have we had more applicants than it was feasible to interview. You don't have to interview them all. Once you encounter an excellent candidate, you can close the deal. If you don't, you might lose them. You don't have to find the one pearl in a thousand. We used CVs as the only thing we had to filter with, looking for *interesting* people. For a developer position, we use a home assignment as a filter. There's no knowing who completes the assignment, but (1) it gives an idea what is expected of them and (2) it demonstrates interest from their part. I believe we have a standard set of C programming questions we throw at interviewees, on the same principle. One place I worked at used to request a hand-written cover letter with applications. This too was a filter, though not by graphological analysis as many people assumed (and took umbrage at). No, we were testing if you could follow instructions and take some degree of care. A hastily scribbled piece of paper with lots of crossings out didn't auger well for how careful you would be with the code base! Exactly what "interesting" meant was somewhat arbitrary; we put one person through to interview because she was a cellist, and that would have given us a complete string quartet (she didn't get the job, sadly). We want to hire for the job and not bring in extracurricular activities. However, one great way to stand out is a portfolio of GitHub projects. Er, isn't that an extracurricular activity? I certainly don't have time for it outside work. Several people have gotten an offer largely based on those (after they aced the technical interviews). For example, we just hired someone who had written a game in sed. That doesn't make him an "interesting person," nor do we look for game or sed developers. But that silly exercise deeply resonated with our team. We expect to have great synergy with him. In other words, you find him interesting because of that. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter,show pictures from the list of files in catalog-problem
On 19/12/17 18:33, Ziggy wrote: I have a problem with this code, it seems to work but first it shows the picture then supposed to iterate through file list and shows them each changed after 3seconds however show just the last one from list. https://paste.pound-python.org/show/txvB4IBtlUrn3TuB0rtu/ Nope. Not following a link from someone I don't know (with all due respect) with a URL I don't immediately recognise. If you want help, post your code here, preferably trimmed down to the minimum you need to demonstrate the problem. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Where has the practice of sending screen shots as source code come from?
On 29/01/18 04:29, Dan Stromberg wrote: On Sun, Jan 28, 2018 at 8:24 PM, Dan Stromberg wrote: If an NN can ... play go on a level that can beat the best human in the world Correcting myself: I think Google's AlphaGo used more than one NN, plus perhaps a little traditional reading algorithm. So I probably should have said "If NN's can ...". No, you should have said "If NNs can..." without the grocer's apostrophe :-) (Well, it seems to be that sort of thread.) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Where has the practice of sending screen shots as source code come from?
On 30/01/18 16:47, alister via Python-list wrote: The British TV show QI seemed to think this is actually part of the Dutch driving test although they have been known to make mistakes It has to be noted that the QI Elves did not do particularly well in Only Connect... -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: "None" and "pass"
On 06/02/18 10:23, alister via Python-list wrote: On Tue, 06 Feb 2018 08:55:35 +1100, Chris Angelico wrote: On Tue, Feb 6, 2018 at 8:39 AM, Ben Finney wrote: Chris Angelico writes: As one special case, I would accept this sort of code: def f(): ... (three dots representing the special value Ellipsis) It's a great short-hand for "stub". I would not accept that. An even better way to write a stub function is to write a docstring: def frobnicate(): """ Frobnicate the spangule. """ A docstring, like any bare expression, is also a valid statement. Writing a docstring can be done immediately, because if you're writing a stub function you at least know the external interface of that function. This is true, but I'd rather have something _under_ the docstring if possible, and "..." works well for that. A docstring with nothing underneath doesn't look like a stub - it looks like a failed edit or something. Having a placeholder shows that it's intentional. ChrisA indeed and pass was implemented for precisely this usage why even think about possible alternatives None shall pass. (Seriously. I'm disappointed in all of you :-) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Regex on a Dictionary
On 13/02/18 13:11, Stanley Denman wrote: I am trying to performance a regex on a "string" of text that python isinstance is telling me is a dictionary. When I run the code I get the following error: {'/Title': '1F: Progress Notes Src.: MILANI, JOHN C Tmt. Dt.: 05/12/2014 - 05/28/2014 (9 pages)', '/Page': IndirectObject(465, 0), '/Type': '/FitB'} Traceback (most recent call last): File "C:\Users\stand\Desktop\PythonSublimeText.py", line 9, in x=MyRegex.findall(MyDict) TypeError: expected string or bytes-like object Here is the "string" of code I am working with: {'/Title': '1F: Progress Notes Src.: MILANI, JOHN C Tmt. Dt.: 05/12/2014 - 05/28/2014 (9 pages)', '/Page': IndirectObject(465, 0), '/Type': '/FitB'} I want to grab the name "MILANI, JOHN C" and the last date "-mm/dd/" as a pair such that if I have X numbers of string like the above I will end out with N pairs of values (name and date)/ Here is my code: import PyPDF2,re pdfFileObj=open('x.pdf','rb') pdfReader=PyPDF2.PdfFileReader(pdfFileObj) Result=pdfReader.getOutlines() MyDict=(Result[-1][0]) print(MyDict) print(isinstance(MyDict,dict)) MyRegex=re.compile(r"MILANI,") x=MyRegex.findall(MyDict) print(x) As the error message says, re.findall() expects a string. A dictionary is in no sense a string, so passing it in whole like that won't work. If you know that the name will always show up in the title field, you can pass just the title: x = MyRegex.findall(MyDict['/Title']) Otherwise you will have to loop through all the entries in the dictionary: for entry in MyDict.values(): x = MyRegex.findall(entry) # ...and do something with x I rather suspect you are going to find that the titles aren't in a very systematic format, though. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2 to 3 Conversion
On 18/02/18 16:18, Wildman via Python-list wrote: But that's only going to show one (uplink) address. If I needed to get ALL addresses for ALL network adapters, I'd either look for a library, and if one wasn't easily found, I'd shell out to the "ip" command and parse its output.:) I considered using the "ip" command but I prefer not to depend on external programs if I can get around it. I know that might be considered silly but that's just me. It's not silly at all, but for Linux networking it might be the best idea. I believe in theory you are supposed to use libnl (in some suitable wrapping), but my experience with that is that it is badly documented and horrendously unreliable. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Are the critiques in "All the things I hate about Python" valid?
On 20/02/18 17:11, Wild, Marcel, Prof wrote: I scarcely know Python, and I have no intention delving into it further. I was forced to use Python because it features binary decision diagrams, which MATHEMATICA doesn't. Coming from Mathematica the account of Nathan Murphy reads like a nightmare. I have to admit, I have no idea what you're talking about. I suspect, though, that you would find a similar discussion of any other programming language at least as nightmarish. The one point that stroke me the most was the schism between Python 2 and 3. No such thing with Mathematica: All its 11 or more versions are fully compatible, I never experienced any problems in this regard. The schism is not as wide as you are implying. Aside from "print" becoming a function, which is blindingly obvious whenever you trip over it, there is relatively little reason why an ordinary Pythonista would care whether he or she was running Python 2 or Python 3. Python 3.5 vs Python 3.7 is much more likely to be a relevant question, because of course Python has evolved new features over time. The statement "all its [...] versions are fully compatible" implies Mathematica hasn't evolved over those versions. I sincerely doubt that is true. Another point is the bad online help provided to "teach yourself" Python. For instance, it took me more than an hour to find out how to negate a Boolean variable, whereas in Mathematica you would just type "Negation" in the Wolfram Documentation search window, and get the information you need. This is likely to be a personal thing. Mathematica ties you firmly to its IDE; you get all the bells and whistles of that IDE, but only the bells and whistles of that IDE. Python doesn't tie you to anything in particular, so you have to provide your own bells and whistles (but can provide any you can find or create). That said, you are not making a good case for your research skills. Googling "python boolean negation" got me the information in under a minute, including the Firefox startup time. Reading through the Boolean Expressions part of the online documentation at docs.python.com took little longer, though admittedly that isn't meant for beginners. Even firing up a Python interpreter and typing >>> help("not") didn't take that long (and honestly, "negation" is not the first word I think of when inverting booleans). I know one pays for Mathematica whereas Python is open source, but I've come to realize now that this money is very well spent! Question: Apart from a few commands not available in Mathematica, such as expr2bdd, is there really any domain of computation where Mathematica is inferior to Python? Not knowing much about Mathematica, all I can say is "almost certainly." -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make Python run as fast (or faster) than Julia
On 22/02/18 10:59, Steven D'Aprano wrote: https://www.ibm.com/developerworks/community/blogs/jfp/entry/Python_Meets_Julia_Micro_Performance?lang=en Interesting article. I can't help but feel that using Cython is cheating a bit, and I was really expecting a bit more Pythonic rewriting of the benchmarks Pythonic, but still food for thought. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: How to make Python run as fast (or faster) than Julia
On 26/02/18 13:42, Ned Batchelder wrote: Also, I note that you said, "Most integers are unsigned", but the C code has them all declared as signed? It doesn't seem to have mattered to your result, but I'm not an expert on C portability guarantees. C explicitly leaves the behaviour of signed arithmetic overflow undefined, so you have no portability guarantees there. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Is there are good DRY fix for this painful design pattern?
On 26/02/18 14:41, Steven D'Aprano wrote: I have a class with a large number of parameters (about ten) assigned in `__init__`. The class then has a number of methods which accept *optional* arguments with the same names as the constructor/initialiser parameters. If those arguments are None, the defaults are taken from the instance attributes. An example might be something like this: class Foo: def __init__(self, bashful, doc, dopey, grumpy, happy, sleepy, sneezy): self.bashful = bashful # etc def spam(self, bashful=None, doc=None, dopey=None, grumpy=None, happy=None, sleepy=None, sneezy=None): if bashful is None: bashful = self.bashful if doc is None: doc = self.doc if dopey is None: dopey = self.dopey if grumpy is None: grumpy = self.grumpy if happy is None: happy = self.happy if sleepy is None: sleepy = self.sleepy if sneezy is None: sneezy = self.sneezy # now do the real work... def eggs(self, bashful=None, # etc... ): if bashful is None: bashful = self.bashful # and so on There's a lot of tedious boilerplate repetition in this, and to add insult to injury the class is still under active development with an unstable API, so every time I change one of the parameters, or add a new one, I have to change it in over a dozen places. Is there a good fix for this to reduce the amount of boilerplate? You could use dicts? Untested code: class Foo: def __init__(self, **kwds): self.defaults = kwds def spam(self, **kwds): vars = self.defaults.copy() vars.update(kwds) # Do the work with vars['bashful'] etc -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Python3, column names from array - numpy or pandas
On 15/12/16 01:56, renjith madhavan wrote: I have a dataset in the below format. id A B C D E 100 1 0 0 0 0 101 0 1 1 0 0 102 1 0 0 0 0 103 0 0 0 1 1 I would like to convert this into below: 100, A 101, B C 102, A 103, D E How do I do this ? I tried numpy argsort but I am new to Python and finding this challenging. Appreciate any help in this. Numpy or pandas? Neither, this is a straightforward bit of text manipulation you can do without needing to import anything. I wouldn't bother considering either unless your dataset is massive and speed is anything of an issue. with open("data.txt") as datafile: # First line needs handling separately line = next(datafile) columns = line.split()[1:] # Now iterate through the rest for line in datafile: results = [] for col, val in zip(columns, line.split()[1:]: if val == "1": results.append(col) print("{0}, {1}".format(data[0], " ".join(results))) Obviously there's no defensive coding for blank lines or unexpected data in there, and if want to use the results later on you probably want to stash them in a dictionary, but that will do the job. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Screwing Up looping in Generator
On 04/01/17 02:10, Deborah Swanson wrote: Sayth Renshaw wrote, on January 03, 2017 5:36 PM So can I call the generator twice and receive the same file twice in 2 for loops? Once to get the files name and the second to process? for file in rootobs: base = os.path.basename(file.name) write_to = os.path.join("output", os.path.splitext(base)[0] + ".csv") with open(write_to, 'w', newline='') as csvf: for file in rootobs: # create and write csv Cheers Sayth I don't see why not, if you let the first one run to completion and then do it again a second time. Assuming your generator doesn't somehow delete or modify the file specifications as it yields them. It would be helpful to see the code for rootobs, if you have it. Ahem. If Sayth is using the correct terminology and rootobs actually is a generator (not, say, a list or tuple), then no it won't work. Once a generator is exhausted, it's exhausted. Besides, the nested for-loops over the same iterable is a dead giveaway that something is wrong. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Clickable hyperlinks
On 05/01/17 04:52, Deborah Swanson wrote: My original question was in fact whether there was a way to make clickable hyperlinks in a console. I was persuaded after about 10 replies that the answer was no, Then you were persuaded wrong; the actual answer was "this isn't a meaningful question since it's based on incorrect assumptions." Translating that to "No" is just as much a mistake as translating it to "Yes." -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Screwing Up looping in Generator
On 04/01/17 02:10, Deborah Swanson wrote: > Sayth Renshaw wrote, on January 03, 2017 5:36 PM >> >> So can I call the generator twice and receive the same file >> twice in 2 for loops? >> >> Once to get the files name and the second to process? >> >> for file in rootobs: >> base = os.path.basename(file.name) >> write_to = os.path.join("output", >> os.path.splitext(base)[0] + ".csv") >> with open(write_to, 'w', newline='') as csvf: >> for file in rootobs: >> # create and write csv >> >> Cheers >> >> Sayth > > I don't see why not, if you let the first one run to completion and then > do it again a second time. Assuming your generator doesn't somehow > delete or modify the file specifications as it yields them. It would be > helpful to see the code for rootobs, if you have it. Ahem. If Sayth is using the correct terminology and rootobs actually is a generator (not, say, a list or tuple), then no it won't work. Once a generator is exhausted, it's exhausted. Besides, the nested for-loops over the same iterable is a dead giveaway that something is wrong. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Clickable hyperlinks
On 05/01/17 02:53, Deborah Swanson (Deborah Swanson) wrote: Rhodri James wrote, on January 05, 2017 3:53 AM On 05/01/17 04:52, Deborah Swanson wrote: My original question was in fact whether there was a way to make clickable hyperlinks in a console. I was persuaded after about 10 replies that the answer was no, Then you were persuaded wrong; the actual answer was "this isn't a meaningful question since it's based on incorrect assumptions." Translating that to "No" is just as much a mistake as translating it to "Yes." Actually, your statement "this isn't a meaningful question since it's based on incorrect assumptions" is false. PyCharm outputs clickable links to the console, but they aren't web links, they simply link to lines of code. Nope. PyCharm outputs text to the console that the console chooses to interpret as a link and makes clickable. As Stephen pointed out right back at the beginning of this thread, printing the textual string that is a URL could do exactly the same thing *if* the console you print to chooses to interpret it as such. The choice is with the console, not your program; that there is the incorrect assumption. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Clickable hyperlinks
On 09/01/17 13:53, Tim Chase wrote: On 2017-01-09 05:00, Deborah Swanson wrote: The console is a dead thing, it has no mind or soul to choose anything. Surely an educated person would know that. Pretty much every quality system administrator I know uses the terminal. Just about all of the best devs I know use the terminal. Microsoft added Powershell because of demand. They added Ubuntu/bash support because of demand. It allows for powerful automation that would otherwise require writing full-fledged scripts. There is nothing dead about it. I think you're falling foul of Deborah's inability to communicate again. I think she meant to say that the console is dumb, not dead. In a very strict sense that's almost true, but since we've been using "console" interchangeably with "terminal emulator" throughout this discussion, it's hilariously wrong. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Using namedtuples field names for column indices in a list of lists
On 09/01/17 21:40, Deborah Swanson wrote: Peter Otten wrote, on January 09, 2017 6:51 AM records = sorted( set(records), key=operator.attrgetter("Description") ) Good, this is confirmation that 'sorted()' is the way to go. I want a 2 key sort, Description and Date, but I think I can figure out how to do that. There's a handy trick that you can use because the sorting algorithm is stable. First, sort on your secondary key. This will leave the data in the wrong order, but objects with the same primary key will be in the right order by secondary key relative to each other. Then sort on your primary key. Because the sorting algorithm is stable, it won't disturb the relative order of objects with the same primary key, giving you the sort that you want! So assuming you want your data sorted by date, and then by description within the same date, it's just: records = sorted( sorted( set(records), key=operator.attrgetter("Description") ), key=operator.attrgetter("Date") ) -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Find and append file path
On 12/01/17 13:58, Iranna Mathapati wrote: Hi Team, How to append file path and find the latest folder according to the latest date: CLI input :"/root/user/branches/xyz" i want to find latest file within CLI input path and append to given CLI path Example: CLI Input: /root/user/branches/xyz find latest file and append to CLI path: "/root/user/branches/xyz/Apple" Use os.scandir() to list whatever is in the directory, DirEntry.is_dir() will tell you if an entry is itself a directory, and DirEntry.stat() will let you get at the directory's various time stats. Which attribute you want depends on exactly what you mean by "the latest folder according to the latest date". Then just use your favourite means to join the directory name you selected to the original path. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: update a list element using an element in another list
On 31/01/17 11:28, Daiyue Weng wrote: Hi, I am trying to update a list of dictionaries using another list of dictionaries correspondingly. In that, for example, # the list of dicts that need to be updated dicts_1 = [{'dict_1': '1'}, {'dict_2': '2'}, {'dict_3': '3'}] # dict used to update dicts_1 update_dicts = [{'dict_1': '1_1'}, {'dict_2': '1_2'}, {'dict_3': '1_3'}] so that after updating, dicts_1 = [{'dict_1': '1_1'}, {'dict_2': '1_2'}, {'dict_3': '1_3'}] what's the best way to the updates? This is actually coming from when I tried to create a list of entities (dictionaries), then updating the entities using another list dictionaries using google.cloud.datastore. entities = [Entity(self.client.key(kind, entity_id)) for entity_id in entity_ids] # update entities using update_dicts for j in range(len(entities)): for i in range(len(update_dicts)): if j == i: entities[j].update(update_dicts[i]) I am wondering is there a brief way to do this. This all relies on the lists being in the same order and the same length, which is probably an unwise assumption, but it's what your code does: for entity, update_dict in zip(entities, update_dicts): entity.update(update_dict) range(len(something)) is usually a warning sign (code smell, if you prefer) that you aren't thinking in Python. If you really need the list index for some nefarious purpose, enumerate(something) is probably still a better bet. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.6
On 07/03/18 14:07, Jeremy Jamar St. Julien wrote: How do i open python 3.6 in a console and how do i see the binary its running with Can you give us a little more information? What operating system are you using? When you say "console", do you mean whatever passes for a terminal window on your OS or the IDLE program? What exactly do you mean by "the binary its [sic] running with"? -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Console
On 07/03/18 14:41, Jeremy Jamar St. Julien wrote: I had an problem when trying to start the python GUI. It said there was a subprocess startup error. I was told to start IDLE in a console with idlelib and see what python binary i was runnning IDLE with. Im using windows 10 and i guess console refers to the terminal window and i have no idea what they meant by "the binary its running with" I'm afraid I can't help you with with the Console program. Windows does like to bury Console deep in its menus, and I don't have a copy of Windows 10 to find it in. Once you have a console running, all you should need to do then is type "idle" at the prompt. That should open a window, which amongst other things will tell you the version of Python it is using. If that fails, try "idle -n" instead; it may not make any difference, but it's worth a go. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Reg python regexp
On 21/03/18 10:44, sankarram...@gmail.com wrote: Hi, I have a requirement. cmd="cat |grep -c 'if [ -t 1 ]; then mesg n 2>/dev/null; fi'" I need to escape only the square brackets in above variable since its not grepping without escaping the brackets. You need to escape the square brackets as you normally would for your shell, with backslashes I presume. Then you need to escape the backslashes so they aren't interpreted specially by Python, with more backslashes. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Pep8 for long pattern
On 27/03/18 22:02, Dan Stromberg wrote: On Tue, Mar 27, 2018 at 8:18 AM, Michael Torrie wrote: But when it's exactly what you need, why do you need to shoehorn the expression into 79 characters? Seems pointless in a case like this. PEP8 is a guideline, not an absolute rule. It's okay to bend it a bit in cases like this. I think PEP8 specifying a max of 80 columns is very silly. Even an old VT220 terminal could do 132 columns. At the risk of starting the Yorkshiremen sketch again, the *old* terminals couldn't :-) The BBC Micros we used as terminals to the mainframe could be made to give you more columns, but no one was that masochistic. My understanding is that PEP8 requires 80 columns because a tiny, tiny, tiny minority of Python developers wanted to be able to put 3 editors next to each other horizontally, without wrapping. Hi :-) I like to check my code with pycodestyle, but I always override that dang 80 column requirement. Very rarely I will let a line leak past 80 characters when it really doesn't make any sense to break it up into smaller chunks. I'm fine with other people going longer if they're fine with me reformatting their code if I have to work on it. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list