pre-PEP: Print Without Intervening Space
Here is a pre-PEP about print that I wrote recently. Please let me know what is the community's opinion on it. Cheers, Marcin PEP: XXX Title: Print Without Intervening Space Version: $Revision: 0.0 $ Author: Marcin Ciura Status: Draft Type: Standards Track Created: 11-Mar-2005 Post-History: 11-Mar-2005 Abstract This PEP proposes to extend the syntax of the print statement so that its space-insertion mechanism can be selectively disabled by using double instead of single commas. Rationale The print statement can write several expressions in one line, but presently always separates them with spaces. While this behaviour is often desirable, not uncommon are situations, where programmers have to use workarounds to achieve a non-spaced display. This has been recognized as one of "Python Gotchas" [1]. Even the simplest workaround results in an unnecessarily complicated code (for the sake of simplicity let us assume that fn() returns strings): result = '' for x in seq: result += fn(x) print result Not to mention it also has a terrible algorithmic complexity. None of the more efficient solutions is particularly straightforward, either: result = [] for x in seq: result.append(fn(x)) print ''.join(result) print ''.join([fn(x) for x in seq]) print ''.join(fn(x) for x in seq) Moreover, all of them require creating one or two temporary objects to hold the entire result. If the programmers use one of them without qualms, it is only because their mind is warped by the limitation of print. Using write() is not especially appealing either, especially if the print statements are used elsewhere in the code: import sys for x in seq: sys.stdout.write(fn(x)) print # or sys.stdout.write('\n') The proposed extension to the print statement is to use two commas to signal that no space should be written after an expression: for x in seq: print fn(x),, print To quote "The Zen of Python" [2]: "Beautiful is better than ugly. Simple is better than complex. Readability counts." The proposal applies also to the expressions in the middle of the print statement. Thus it provides an alternative to string concatenation and string interpolation, either with the '%'-based specifiers, or with the '$'-based ones introduced by PEP 292 [3], not requiring creating a temporary string object: print 'The phone number is (',,extension,,')', number,,'.' Note that I do not claim that the above version is any more readable than print 'The phone number is (%s) %s.' % (extension, number) Specification It is proposed to allow separating the expressions to be printed by single or double commas, and to allow single or double commas at the end of the print statement. The two commas shall be consecutive, i.e. there shall be no whitespace between them. Non-consecutive commas or any sequence of more than two commas constitute a syntax error. In the "print chevron" form of the statement, the name of the file object shall be separated from the next expression only by a single comma, as it is now. Formally, the proposed syntax of the extended print statement is print_stmt: "print" ( [expression (("," | ",,") expression)* ["," | ",,"]] | ">>" expression [("," expression (("," | ",,") expression)* ["," | ",,"]] Implementing the proposed syntax may require introducing a new type of token: double comma, or a hack in the parser to recognize two consecutive commas in the context of the print statement. Two new byte codes, parallel to PRINT_ITEM and PRINT_ITEM_TO, are needed to implement the semantics of the proposal. Discussion Pros: - The proposed semantics allows avoiding temporary string objects during the execution of the print statement and often makes for more readable and explicit source code. - The proposed syntax is easy to learn for the beginners. - It breaks no existing Python code. - Mistakes are unlikely to happen with the proposed syntax, unless someone has problems with his typing or his keyboard, in which case any programming is difficult, anyway. Cons: - Wrapper functions around print will be unable to mimic its syntax. It is, however, impossible even now, due to trailing commas. - In PEP 259 [4], the BDFL has pronounced that he wants to avoid any more tinkering with "print". - PEP 3000 [5] and &qu
Re: pre-PEP: Print Without Intervening Space
Duncan Booth wrote: import sys def nospace(value, stream=None): '''Suppress output of space before printing value''' stream = stream or sys.stdout stream.softspace = 0 return str(value) I'm teaching Python as the first programming language to non-computer scientists. Many of the toy programs would be simpler with the double comma syntax. Presently, having a choice whether to teach my students the result += fn(x) way or your way, I would still opt for the former. Best regards, Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
Larry Bates wrote: I fail to see why your proposed solution of: for x in seq: print fn(x),, print is clearer than: print ''.join([fn(x) for x in seq]) Thank you for your input. The latter form is fine with me personally, but you just can't explain it to complete novices. My proposal aims at making programming easier for them. Also your statement: print 'The phone number is (',,extension,,')', number,,'.' requires three double commas and can already be written more clearly as: print 'The phone number is ('+extension+') '+number'.' I agree with you in this point (if extension and number are strings). Best regards, Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
In view of Duncan's response, which invalidates the premises of my proposal, I announce the end of its short life. I will add Duncan's solution to my bag of tricks - thank you! Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
Steve Holden wrote: You could think about teaching them the linelist.append(fn(x)) way, which then gives you the choice of "".join(linelist) - no gaps "\n".join(lienlist) - one item per line " ".join(linelist) - spaces between items. Sure I will. Next week, when we come to list operations. .join() they already know. I just couldn't use this approach at the very beginning. Thanks to all who responded. Regards, Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: pre-PEP: Print Without Intervening Space
Bengt Richter wrote: BTW, what makes you think any self-respecting "scientist" wouldn't be insulted by the idea of your spoon-feeding them a dumbed-down programming equivalent of "See Spot run"? Am I right thinking that your dream 3 R's curriculum starts with "Stately, plump Buck Mulligan" and Pólya Enumeration Theorem? Most of them have no previous programming experience, mind you. Of course, you may be a suffering victim of circumstances, I don't know. They're not so bad: I deliver the lectures (1.5 h/week), and there are also laboratory classes (1.5 h/week). During one semester, most of Python topics are covered. Fortunately, Python is not that hard, and rapidly becomes fun unless the initial experience is structured against discovering the expressive power that is so enjoyable. I wholeheartedly agree with you in this point. I'm sure my students would appreciate being taught Python instead of Pascal if they had a chance to compare them. If you want the effect of print x, y, fn(z), etc without spaces, why don't you just write a function that will let you spell it simply, like Excellent advice, provided that you already know the concept of user-defined functions. IMO teachers should lead their students into contact with reality, not insulate them from it with delusionary simplifications that they will have to unlearn in order to progress. I'm not sure what you mean by "delusionary simplifications", but I hope you meant nothing insulting. They already know how to use string interpolation, and as soon as they learn how to mutate the contents of a list, I'll tell them to use looped .append() followed by .join() instead of looped string concatenation, and explain why. Best regards, Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: Large Dictionaries
Tim Peters wrote: > shellsort is much more a refinement of insertion-sort than of > bubblesort, but is not an O(N log N) algorithm regardlesss. With a judiciously chosen increment sequence, the number of comparisons made by shellsort *is* of the order N log N for practical values of N. See Figure 8 in http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: Large Dictionaries
Duncan Booth wrote: > Marcin Ciura wrote: >>See Figure 8 in >>http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf > That isn't what the reference says. It only covers N up to a few thousand. > Practical values of N need to at least go up into the millions. Please look at the performance graph of Tokuda's increment sequence. You can see that it scales pretty well at least up to 100 million. Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing variable from a function within a function
Nathan Harmston wrote: > Unfortunately this doesnt work since a,a1,b,b1 arent declared in the > function. Is there a way to make these variables accessible to the > euclid function. Or is there a better way to design this function? The canonical recommendations are: use attributes of the inner function or one-element lists as writable variables visible in the outer function. Another possibility is to modify the bytecode of the functions by an appropriate decorator. See http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/expose.py (you'll need the byteplay module by Noam Raphael to make it work). Marcin -- http://mail.python.org/mailman/listinfo/python-list
Python 3000 idea: reversing the order of chained assignments
Given class Node(object): pass node = Node() nextnode = Node() I tried to refactor the following piece of code node.next = nextnode node = nextnode as node = node.next = nextnode only to discover that Python performs chained assignments backwards compared to other languages, i.e. left-to-right instead of right-to-left. From the user's perspective, I can't think of any reasonable argument for keeping it this way in Python 3000. What is your opinion? Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3000 idea: reversing the order of chained assignments
Steven D'Aprano wrote: x, y, z = 1, 2, 3 x = y = z x, y, z > > (3, 3, 3) > > I certainly wouldn't expect to get (2, 3, 3). Neither would I. I must have expressed myself not clearly enough. Currently x = y = z is roughly equivalent to x = z y = z I propose to change it to y = z x = z Cheers, Marcin -- http://mail.python.org/mailman/listinfo/python-list
Gosper arithmetic in Python
Hello, I hacked together a module implementing exact real arithmetic via lazily evaluated continued fractions. You can download it from http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py an use as an almost drop-in replacement for the math module if you don't care too much about performance. I'd be happy to hear any feedback and suggestions. Cheers, Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: finding out the precision of floats
Arnaud Delobelle wrote: > I'm not doing 'real world' calcultations, I'm making an app to help > teach children maths. I need numerical values that behave well as > decimals. I also need them to have an arbitrary number of significant > figures. Floats are great but they won't help me with either. Amongst > other things, I need 3.0*0.1==0.3 to be True. I guess that speed is not at premium in your application, so you might try my continued fractions module, advertised here a few weeks ago: http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/cf.py It represents rational numbers exactly, and irrational numbers with an arbitrary accuracy, i.e. unlike Decimal it implements exact rather than multiple-precision arithmetic. Once you create an expression, you can pull from it as many decimal digits as you wish. The subexpressions dynamically adjust their accuracy, so that you always get exact digits. Regards, Marcin -- http://mail.python.org/mailman/listinfo/python-list
Re: any() and all() on empty list?
Georg Brandl wrote: > Steven D'Aprano wrote: >>all(flying elephants which are pink) => true >>all(flying elephants which are not pink) => true >> >>So, these flying elephants -- are they pink or not? > > No, you ask two different sets whether they are true. No, there is only one empty set. Relevant to this discussion is stuff about syllogisms concerning non-existent objects and what C.S. Peirce did to them in the 19th century. See e.g. http://www.math.fau.edu/schonbek/mfla/mfla1f01syl.html#tth_sEc5 Marcin -- http://mail.python.org/mailman/listinfo/python-list