Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Tue, Dec 3, 2013 at 11:31 PM, rusi wrote: > Its a more fundamental problem than that: > It emerges from the OP's second post) that he wants '-' in the attributes. > Is that all? > > Where does this syntax-enlargement stop? Spaces? Newlines? At non-strings. >>> setattr(foo, 21+21, 42) Traceback (most recent call last): File "", line 1, in TypeError: attribute name must be string, not 'int' -- https://mail.python.org/mailman/listinfo/python-list
Re: any use case of logging.config.listen()?
Thank you a lot for your case description. On Wed, 4 Dec 2013, Dan Sommers wrote: It begets the question, that if it is easier to write a socket-listening loging handler and forget all about logging.config.listen() stuff. I never did it before, hence the question. But why develop all of that code when logging.config.listen() already exists? Adding a new SocketHandler seems more heavyweight (and more risky) than adjusting the logging level on an existing SocketHandler. There are 2 reasons that i cannot just use existing API for the project I am working on. 1. My monitoring GUI client is often behind various NAT. In fact it is a hand-held client, I could be using it in a café's WIFI. It is impossible to tell the python-daemon to just send the log to given address and port. 2. I forgot to explain that in my project adjusting log level is only half of what needs to be done. The monitoring GUI client also needs to be able to send a few operational parameters' change. e.g. I need to see the log, and decide to change 'Threshold' from 0.5 to 0.53 and see the difference. For the first problem, a new logging.ListeningSocketHandler would work - don't know if it is easy to write one - which can be written in a way that simply drops logs if no one is listening, thus forgoing logging.config.listen(). For the second problem, a way to dynamically accept new operational paramters from socket is needed, solo logging.config.listen() wouldn't suffice. Either case I don't find use of logging.config.listen(), even though I am looking hard for every way to reuse existing code. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/03/2013 09:45 PM, Tim Roberts wrote: Piotr Dobrogost wrote: Attribute access syntax being very concise is very often preferred to dict's interface. It is not "very concise". It is slightly more concise. x = obj.value1 x = dct['value1'] You have saved 3 keystrokes. That is not a significant enough savings to create new syntax. Remember the Python philosophy that there ought to be one way to do it. That should be "one obvious way". On my keyboard, at least, those are an important three keystrokes! ;) To be clear, I am -1 on the new syntax. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
A cautionary tale
Hi all There is no question at the end of this, it is just an account of a couple of days in the life of a programmer (me). I just felt like sharing it. Feel free to ignore. The business/accounting system I am writing involves a lot of reading data from a database, and if changed, writing it back again. There are a number of data types involved - string, integer, decimal, boolean, date, datetime. I currently support PostgreSQL, MS SQL Server, and sqlite3. In all cases, they have a DB-API 2.0-compliant adaptor which handles the conversion to and from python objects transparently. Over the last year or so I have added two new types. I added a JSON type, to handle 'lists' and 'dicts', and an XML type to handle more complex structures. In both cases they are stored in the database as strings, so I have to handle the conversions myself. I don't allow direct access to the objects, as they can be affected by various business rules, so I use getters and setters. For the new types, I used the getter to convert from the string to the underlying object, and the setter to convert it back to a string. Then a couple of days ago I decided that this was not the correct place to do it - it should be done when reading from and writing to the database. That way the data is always represented by the underlying object, which can be passed around without worrying about conversions. It was a bit of effort, as I had to add extra getters and setters to handle the transfer between the database and the program, and then over-ride them in the case of the new data types to provide the required functionality. But after a few hours of hunting down all the places that required changes, testing, fixing errors, etc, it seemed to be working fine, so I thought I could carry on with the meat of my program. Then I noticed that certain changes were not being written back to the database. After some investigation, I found the error in a part of my program that I have not had to look at for ages. When reading data in from the database, I preserve a copy of the original value. When saving, I compare that to the current value when deciding which columns need updating. I do this in the obvious way - on reading - orig_value = value on saving - if value != orig_value: this one needs updating Have you spotted the deliberate mistake yet? In the case of a JSON list, orig_value and value point to the same, mutable, list. So when I compare value with orig_value, they are always the same, whether changes have been made or not! The obvious answer is to store a copy of the list. It was not so obvious where to make the change, as there were other implications. Eventually I decided to over-ride the 'getter' for the JSON type, and return copy(value) instead of value. That way if it is changed and then put back using the 'setter', the two objects are no longer equal. I have made that change, done some more testing, and for now it seems ok. So have the last couple of days been a waste of time? I don't think so. Is the program a bit cleaner and conceptually sounder? I hope so. Why am I telling you all this? No particular reason, just thought some of you might find it interesting. Frank Millman -- https://mail.python.org/mailman/listinfo/python-list
Re: extracting a heapq in a for loop - there must be more elegant solution
On Tue, 03 Dec 2013 04:40:26 -0800, rusi wrote: > On Tuesday, December 3, 2013 5:48:59 PM UTC+5:30, Helmut Jarausch wrote: >> Hi, >> >> I'd like to extracted elements from a heapq in a for loop. >> I feel my solution below is much too complicated. >> How to do it more elegantly? >> I know I could use a while loop but I don't like it. > > How about > > def in_sequence(h): > for i in range(len(h)): > yield heapq.heappop(h) > > Yeah its a bit fiddly: > 1. i needed for for but not used > 2. The range in the for loop -- normally a python 'smell' > > If python3 > > def ins3(h): >yield from (heapq.heappop(h) for i in range(len(h))) Many thanks, I'm using Python3 anyway! Helmut -- https://mail.python.org/mailman/listinfo/python-list
Re: extracting a heapq in a for loop - there must be more elegant solution
On Tue, 03 Dec 2013 13:38:58 +0100, Peter Otten wrote: > Helmut Jarausch wrote: > >> Hi, >> >> I'd like to extracted elements from a heapq in a for loop. >> I feel my solution below is much too complicated. >> How to do it more elegantly? >> I know I could use a while loop but I don't like it. >> >> Many thanks for some lessons in Python. >> >> Here is my clumsy solution >> >> from heapq import heappush, heappop >> # heappop raises IndexError if heap is empty >> >> H=[] >> for N in 'H','C','W','I' : >> heappush(H,N) > > H = ["H", "C", "W", "I"] > heapq.heapify(H) > > But see below. > >> # how to avoid / simplify the following function >> >> def in_sequence(H) : >> try : >> while True : >> N= heappop(H) >> yield N >> except IndexError : >> raise StopIteration >> >> # and here the application: >> >> for N in in_sequence(H) : >> print(N) > > If you are iterating over the complete heap I see no advantage over a sorted > list. So > > for N in sorted(H): > print(N) > > If H is huge use H.sort() instead of sorted() to save memory. > If you need only a few items use heapq.nsmallest(). Many thanks! In my real application the data which is pushed onto the heap will be extracted from a small file which is executed several thousands times. So, I thought, I could keep the CPU a bit busy while the OS is doing file I/O. Of course, I could have appended all these strings to a list which is sorted at the end. -- https://mail.python.org/mailman/listinfo/python-list
Re: extracting a heapq in a for loop - there must be more elegant solution
On Tue, 03 Dec 2013 13:06:05 +, Duncan Booth wrote: > Helmut Jarausch wrote: > >> Hi, >> >> I'd like to extracted elements from a heapq in a for loop. >> I feel my solution below is much too complicated. >> How to do it more elegantly? >> I know I could use a while loop but I don't like it. >> >> Many thanks for some lessons in Python. >> >> Here is my clumsy solution >> >> from heapq import heappush, heappop >> # heappop raises IndexError if heap is empty >> >> H=[] >> for N in 'H','C','W','I' : >> heappush(H,N) >> >> # how to avoid / simplify the following function >> >> def in_sequence(H) : >> try : >> while True : >> N= heappop(H) >> yield N >> except IndexError : >> raise StopIteration >> >> # and here the application: >> >> for N in in_sequence(H) : >> print(N) >> > > If all you want to do is pull all of the elements out of the heap in > order, you would probably be better off just doing: > > for N in sorted(H): > print(N) > > Heaps are mostly useful if you want only some of the elements, or if you > are continually producing more elements while also processing the > smallest ones. > > However, if you really wnt to do this: > > for N in iter(lambda: heappop(H) if H else None, None): > print(N) > > will work so long as H cannot contain None. If it can just replace both > occurences of None with some other sentinel: > > sentinel = object() > for N in iter(lambda: heappop(H) if H else sentinel, sentinel): > print(N) > > > Alternatively your 'in_sequence' function would look better without the > exception handling: > > def in_sequence(H) : > while H: > yield heappop(H) Many thanks! And as noted in another reply, I try to overlap CPU time with file I/O since I have to open / read / close a file for each line that gets pushed onto the heap. Helmut -- https://mail.python.org/mailman/listinfo/python-list
Re: extracting a heapq in a for loop - there must be more elegant solution
On Tue, 03 Dec 2013 15:56:11 +0200, Jussi Piitulainen wrote: > Helmut Jarausch writes: > ... >> I know I could use a while loop but I don't like it. > ... >> from heapq import heappush, heappop >> # heappop raises IndexError if heap is empty > ... >> # how to avoid / simplify the following function >> >> def in_sequence(H) : >> try : >> while True : >> N= heappop(H) >> yield N >> except IndexError : >> raise StopIteration > > That seems equivalent to this: > > def in_sequence(H): > while H: yield heappop(H) Many thanks, that's something I'd hoped for. > But I don't like the side-effect. I'd change the name to something > that indicates the draining of the heap - heapaerobic? - or consider > sorted(H) instead as others suggested. Since I fill the heap once and empty it afterwards I regard the side-effect clearly visible. Helmut -- https://mail.python.org/mailman/listinfo/python-list
Re: extracting a heapq in a for loop - there must be more elegant solution
On Wed, 04 Dec 2013 08:13:03 +1100, Cameron Simpson wrote: > On 03Dec2013 12:18, Helmut Jarausch wrote: >> I'd like to extracted elements from a heapq in a for loop. >> I feel my solution below is much too complicated. >> How to do it more elegantly? > > I can't believe nobody has mentioned PriorityQueue. > > A PriorityQueue (from the queue module in python 3 and the Queue > module in python 2) is essentially just a regular Queue using a > heapq for the storage. > > Example (untested): > > from Queue import PriorityQueue > > PQ = PriorityQueue() > for item in [1,2,3,7,6,5,9,4]: > PQ.put(item) > > while not PQ.empty(): > item = PQ.get() > ... do stuff with item ... > > I iterate over Queues so often that I have a personal class called > a QueueIterator which is a wrapper for a Queue or PriorityQueue > which is iterable, and an IterablePriorityQueue factory function. > Example: > > from cs.queues import IterablePriorityQueue > > IPQ = IterablePriorityQueue() > for item in [1,2,3,7,6,5,9,4]: > IPQ.put(item) > > for item in IPQ: > ... do stuff with item ... > > Cheers, Many thanks! I think you QueueIterator would be a nice addition to Python's library. Helmut -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
iMath wrote:
>I use the following code to do the test ,but error occurred ,it
>prompts system cannot find specified files ,but the files are indeed
>exists there ,any help ?
>
>with tempfile.TemporaryFile() as fp:
>fp.write(("file '"+'a1.mp3'+"'\n").encode('utf-8'))
>fp.write(("file '"+'a2.mp3'+"'\n").encode('utf-8'))
>
>subprocess.call(['ffmpeg/ffmpeg', '-f', 'concat','-i',fp, '-c',
> 'copy', 'a3.mp3'])
Basic rule: Always copy'n'paste the exact traceback you get.
I don't think you are running the code you have posted because your
subprocess call doesn't work:
>>> import tempfile, subprocess
>>> with tempfile.TemporaryFile() as fp:
... subprocess.call(["foo", "bar", fp, "baz"])
...
Traceback (most recent call last):
File "", line 2, in
File "/usr/lib/python3.3/subprocess.py", line 520, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.3/subprocess.py", line 820, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.3/subprocess.py", line 1380, in _execute_child
restore_signals, start_new_session, preexec_fn)
TypeError: Can't convert '_io.BufferedRandom' object to str implicitly
"fp" is a file object, but subprocess expects a list of strings as
its first argument.
Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list
Re: extracting a heapq in a for loop - there must be more elegant solution
Helmut Jarausch wrote: > On Tue, 03 Dec 2013 13:38:58 +0100, Peter Otten wrote: > >> Helmut Jarausch wrote: >> >>> Hi, >>> >>> I'd like to extracted elements from a heapq in a for loop. >>> I feel my solution below is much too complicated. >>> How to do it more elegantly? >>> I know I could use a while loop but I don't like it. >>> >>> Many thanks for some lessons in Python. >>> >>> Here is my clumsy solution >>> >>> from heapq import heappush, heappop >>> # heappop raises IndexError if heap is empty >>> >>> H=[] >>> for N in 'H','C','W','I' : >>> heappush(H,N) >> >> H = ["H", "C", "W", "I"] >> heapq.heapify(H) >> >> But see below. >> >>> # how to avoid / simplify the following function >>> >>> def in_sequence(H) : >>> try : >>> while True : >>> N= heappop(H) >>> yield N >>> except IndexError : >>> raise StopIteration >>> >>> # and here the application: >>> >>> for N in in_sequence(H) : >>> print(N) >> >> If you are iterating over the complete heap I see no advantage over a >> sorted list. So >> >> for N in sorted(H): >> print(N) >> >> If H is huge use H.sort() instead of sorted() to save memory. >> If you need only a few items use heapq.nsmallest(). > > > Many thanks! > In my real application the data which is pushed onto the heap will be > extracted from a small file which is executed several thousands times. So, > I thought, I could keep the CPU a bit busy while the OS is doing file I/O. > Of course, I could have appended all these strings to a list which is > sorted at the end. In that case have a look at bisect.insort() which adds an item to a list while keeping it sorted. -- https://mail.python.org/mailman/listinfo/python-list
Re: A cautionary tale
Frank Millman wrote: > Hi all > > There is no question at the end of this, it is just an account of a couple > of days in the life of a programmer (me). I just felt like sharing it. > Feel free to ignore. > > The business/accounting system I am writing involves a lot of reading data > from a database, and if changed, writing it back again. > > There are a number of data types involved - string, integer, decimal, > boolean, date, datetime. I currently support PostgreSQL, MS SQL Server, > and sqlite3. In all cases, they have a DB-API 2.0-compliant adaptor which > handles the conversion to and from python objects transparently. > > Over the last year or so I have added two new types. I added a JSON type, > to handle 'lists' and 'dicts', and an XML type to handle more complex > structures. In both cases they are stored in the database as strings, so I > have to handle the conversions myself. > > I don't allow direct access to the objects, as they can be affected by > various business rules, so I use getters and setters. For the new types, I > used the getter to convert from the string to the underlying object, and > the setter to convert it back to a string. > > Then a couple of days ago I decided that this was not the correct place to > do it - it should be done when reading from and writing to the database. > That way the data is always represented by the underlying object, which > can be passed around without worrying about conversions. > > It was a bit of effort, as I had to add extra getters and setters to > handle the transfer between the database and the program, and then > over-ride them in the case of the new data types to provide the required > functionality. But after a few hours of hunting down all the places that > required changes, testing, fixing errors, etc, it seemed to be working > fine, so I thought I could carry on with the meat of my program. > > Then I noticed that certain changes were not being written back to the > database. After some investigation, I found the error in a part of my > program that I have not had to look at for ages. When reading data in from > the database, I preserve a copy of the original value. When saving, I > compare that to the current value when deciding which columns need > updating. I do this in the obvious way - > > on reading - > orig_value = value > > on saving - >if value != orig_value: > this one needs updating > > Have you spotted the deliberate mistake yet? In the case of a JSON list, > orig_value and value point to the same, mutable, list. So when I compare > value with orig_value, they are always the same, whether changes have been > made or not! > > The obvious answer is to store a copy of the list. It was not so obvious > where to make the change, as there were other implications. Eventually I > decided to over-ride the 'getter' for the JSON type, and return > copy(value) instead of value. That way if it is changed and then put back > using the 'setter', the two objects are no longer equal. I have made that > change, done some more testing, and for now it seems ok. > > So have the last couple of days been a waste of time? I don't think so. Is > the program a bit cleaner and conceptually sounder? I hope so. > > Why am I telling you all this? No particular reason, just thought some of > you might find it interesting. You might like to know how others cope with basically the same problem: http://docs.python.org/dev/library/shelve.html#example http://www.zodb.org/en/latest/documentation/tutorial.html#persistent-objects -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 2:27:28 PM UTC+5:30, Ian wrote: > On Tue, Dec 3, 2013 at 11:31 PM, rusi wrote: > > Its a more fundamental problem than that: > > It emerges from the OP's second post) that he wants '-' in the attributes. > > Is that all? > > > > Where does this syntax-enlargement stop? Spaces? Newlines? > > At non-strings. > > >>> setattr(foo, 21+21, 42) > Traceback (most recent call last): > File "", line 1, in > TypeError: attribute name must be string, not 'int' Not sure what's your point. OP wants attribute identifiers like outer_fieldset-inner_fieldset-third_field. Say I have a python expression: obj.outer_fieldset-inner_fieldset-third_field It can (in the proposed extension) be parsed as above, or as: obj.outer_fieldset - inner_fieldset-third_field the first hyphen being minus and the second being part of the identifier. How do we decide which '-' are valid identifier components -- hyphens and which minus-signs? So to state my point differently: The grammar of python is well-defined It has a 'sub-grammar' of strings that is completely* free-for-all ie just about anything can be put into a string literal. The border between the orderly and the wild world are the quote-marks. Remove that border and you get complete grammatical chaos. [Maybe I should have qualified my reference to 'spaces'. Algol-68 allowed spaces in identifiers (for readability!!) The result was chaos] I used the spaces case to indicate the limit of chaos. Other characters (that already have uses) are just as problematic. * Oh well there are some restrictions like quotes need to be escaped, no newlines etc etc -- minor enough to be ignored. -- https://mail.python.org/mailman/listinfo/python-list
Print a text at a specific location on the page
Hi all
This is my first post on this list :-)
I have a web-application (developped using a python framework). In this
web-app, I would like to print certificates for some courses.
The principle :
The course teacher has a "default" certificates, with placeholders for the
name, and the certification name. ("Congratulations ___ you successfully
passed the __ course")
He puts the certificate in his printer, and my app prints the name, and the
certification on a specific location, to fill the placeholders.
I looked at ReportLab, and Pod. They seems powerfull to build complex reports,
but I wonder if it exists a simpler solution just to print a text at a specific
place on the page...
Thank you
--
https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
Op 04-12-13 11:09, rusi schreef: > On Wednesday, December 4, 2013 2:27:28 PM UTC+5:30, Ian wrote: >> On Tue, Dec 3, 2013 at 11:31 PM, rusi wrote: >>> Its a more fundamental problem than that: >>> It emerges from the OP's second post) that he wants '-' in the attributes. >>> Is that all? >>> >>> Where does this syntax-enlargement stop? Spaces? Newlines? >> >> At non-strings. >> > setattr(foo, 21+21, 42) >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: attribute name must be string, not 'int' > > Not sure what's your point. > > OP wants attribute identifiers like outer_fieldset-inner_fieldset-third_field. > Say I have a python expression: > obj.outer_fieldset-inner_fieldset-third_field > > It can (in the proposed extension) be parsed as above, or as: > obj.outer_fieldset - inner_fieldset-third_field > the first hyphen being minus and the second being part of the identifier. > > How do we decide which '-' are valid identifier components -- hyphens > and which minus-signs? > > So to state my point differently: > The grammar of python is well-defined > It has a 'sub-grammar' of strings that is completely* free-for-all ie just > about anything can be put into a string literal. > The border between the orderly and the wild world are the quote-marks. > Remove that border and you get complete grammatical chaos. > [Maybe I should have qualified my reference to 'spaces'. > Algol-68 allowed spaces in identifiers (for readability!!) > The result was chaos] > > I used the spaces case to indicate the limit of chaos. Other characters (that > already have uses) are just as problematic. I don't agree with the latter. As it is now python can make the distinction between from A import Band fromAimportB. I see no a priori reason why this should be limited to letters. A language designer might choose to allow a bigger set of characters in identifiers like '-', '+' and others. In that case a-b would be an identifier and a - b would be the operation. Just as in python fromAimportB is an identifier and from A import B is an import statement. -- Antoon Pardon -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wed, Dec 4, 2013 at 9:09 PM, rusi wrote: > OP wants attribute identifiers like outer_fieldset-inner_fieldset-third_field. > Say I have a python expression: > obj.outer_fieldset-inner_fieldset-third_field I don't think so. What the OP asked for was: my_object.'valid-attribute-name-but-not-valid-identifier' Or describing it another way: A literal string instead of a token. This is conceivable, at least, but I don't think it gives any advantage over a dictionary. What you could do, though, is create a single object that can be indexed either with dot notation or as a dictionary. For that to work, there'd have to be some restrictions (eg no leading underscores - at very least, __token__ should be special still), but it wouldn't be hard to do - two magic methods and the job's done, I think; you might even be able to manage on one. (Code golf challenge, anyone?) Of course, there's still the question of whether that even is an advantage. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: using ffmpeg command line with python's subprocess module
On Wed, Dec 4, 2013 at 8:38 PM, Andreas Perstinger wrote: > "fp" is a file object, but subprocess expects a list of strings as > its first argument. More fundamentally: The subprocess's arguments must include the *name* of the file. This means you can't use TemporaryFile at all, as it's not guaranteed to return an object that actually has a file name. There's another problem, too, and that's that you're not closing the file before expecting the subprocess to open it. And once you do that, you'll find that the file no longer exists once it's been closed. In fact, you'll need to research the tempfile module a bit to be able to do what you want here; rather than spoon-feed you an exact solution, I'll just say that there is one, and it can be found here: http://docs.python.org/3.3/library/tempfile.html ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: any use case of logging.config.listen()?
On Wed, Dec 4, 2013 at 8:09 PM, Zhang Weiwu wrote: > Either case I don't find use of logging.config.listen(), even though I am > looking hard for every way to reuse existing code. > That's not a problem. It's a feature that doesn't quite fit your task, so you don't use it. It's like trying to install an operating system on a new computer and deciding that emacs isn't the one for you. *dives for cover* ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Print a text at a specific location on the page
[email protected] wrote: > Hi all > > This is my first post on this list :-) > > I have a web-application (developped using a python framework). In this > web-app, I would like to print certificates for some courses. > > The principle : > The course teacher has a "default" certificates, with placeholders for the > name, and the certification name. ("Congratulations ___ you > successfully passed the __ course") He puts the certificate in his > printer, and my app prints the name, and the certification on a specific > location, to fill the placeholders. > > I looked at ReportLab, and Pod. They seems powerfull to build complex > reports, but I wonder if it exists a simpler solution just to print a text > at a specific place on the page... > > Thank you I have the following quick-and-dirty wrapper for cairographics lying around -- just added the demo. #/usr/bin/env python3 import cairo import math from contextlib import contextmanager A4 = 595, 842 _mm = 72/25.4 def mm(x): """Convert mm to cairo-native (point)""" return x * _mm class Context(object): """Wrapper for a cairo context object. Methods it doesn't provide are delegated to the cairo.Context instance. """ def __init__(self, width, height, context): self.width = width self.height = height self.context = context def __getattr__(self, name): """Unknown attribute, delegate to cairo context """ return getattr(self.context, name) @contextmanager def fontsize(self, size): """Set fontsize temporarily to something other than 12pt""" self.context.set_font_size(size) yield self.context.set_font_size(12) def line(self, start_x, start_y, end_x, end_y): """Draw a line from (start_x, start_y) to (end_x, end_y)""" self.context.move_to(start_x, start_y) self.context.line_to(end_x, end_y) def text_at(self, left, top, text): """Draw `text` at position (left, top)""" self.context.move_to(left, top) self.context.text_path(text) def setup_context( filename, size, landscape, font="Times New Roman", slant=cairo.FONT_SLANT_NORMAL): """Create a cairo drawing context suitable for printing in landscape format. """ width, height = size # http://cairographics.org/documentation/using_the_postscript_surface/ # recommends the following for printing in landscape # # the "natural" approach (swapping width and height directly without # dsc_comment, translate, rotate, looked OK in Okular resulted in misplaced # (large left/top offset, bottom right corner clipped) output in print surface = cairo.PSSurface(filename, width, height) if landscape: surface.dsc_comment("%%PageOrientation: Landscape") context = cairo.Context(surface) context.translate(0, height) context.rotate(-math.pi/2) width, height = height, width else: context = cairo.Context(surface) context.select_font_face( font, slant, cairo.FONT_WEIGHT_NORMAL) context.set_font_size(12) context.set_line_width(.5) return Context(width, height, context) if __name__ == "__main__": def demo(): context = setup_context("tmp.ps", A4, landscape=False, font="Times") with context.fontsize(18): context.text_at(mm(20), mm(100), "Max Mustermann") context.text_at(mm(120), mm(100), "Brewing") context.fill() demo() If that's too dirty for you consider using cairographics directly... -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 2013-12-04 21:33, Chris Angelico wrote: > I don't think so. What the OP asked for was: > > my_object.'valid-attribute-name-but-not-valid-identifier' > > Or describing it another way: A literal string instead of a token. > This is conceivable, at least, but I don't think it gives any > advantage over a dictionary. In both cases (attribute-access-as-dict-functionality and attribute-access-as-avoiding-setattr), forcing a literal actually diminishes Python's power. I like the ability to do a[key.strip().lower()] = some_value setattr(thing, key.strip().lower(), some_value) which can't be done (?) with mere literal notation. What would they look like? a.(key.strip().lower()) = some_value (note that "key.strip().lower()" not actually a "literal" that ast.literal_eval would accept). That's pretty ugly, IMHO :-) -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 4:03:14 PM UTC+5:30, Chris Angelico wrote: > On Wed, Dec 4, 2013 at 9:09 PM, rusi wrote: > > OP wants attribute identifiers like > > outer_fieldset-inner_fieldset-third_field. > > Say I have a python expression: > > obj.outer_fieldset-inner_fieldset-third_field > > I don't think so. What the OP asked for was: > > my_object.'valid-attribute-name-but-not-valid-identifier' > > Or describing it another way: A literal string instead of a token. This is just pushing the issue one remove away. Firstly a literal string is very much a token -- lexically. Now consider the syntax as defined by the grammar. Let Ident = Set of strings* that are valid python identifiers -- something like [a-zA-Z][a-zA-Z0-9]* Let Exp = Set to strings* that are python expressions * Note that I am using string from the language implementers pov not language user ie the python identifier var is the implementers string "var" whereas the python string literal "var" is the implementer's string "\"var\"" Now clearly Ident is a proper subset of Exp. Now what is the proposal? You want to extend the syntactically allowable a.b set. If the b's can be any arbitrary expression we can have var.fld(1,2) with the grammatical ambiguity that this can be (var.fld)(1,2) -- the usual interpretation Or var.(fld(1,2)) -- the new interpretation -- ie a computed field name. OTOH if you say superset of Ident but subset of Exp, then we have to determine what this new limbo set is to be. ie what is the grammatical category of 'what-follows-a-dot' ?? Some other-language notes: 1. In C there is one case somewhat like this: #include "string" the "string" cannot be an arbitrary expression as the rest of C. But then this is not really C but the C preprocessor 2. In lisp the Ident set is way more permissive than in most languages -- allowing operators etc that would be delimiters in most languages. If one wants to go even beyond that and include say spaces and parenthesis -- almost the only delimiters that lisp has -- one must write |ident with spaces| ie for identifiers the bars behave somewhat like strings' quote marks. Because the semantics of identifiers and strings are different -- the lexical structures need to reflect that difference -- so you cannot replace the bars by quotes. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
rusi writes: > On Wednesday, December 4, 2013 2:27:28 PM UTC+5:30, Ian wrote: > > On Tue, Dec 3, 2013 at 11:31 PM, rusi wrote: > > > Its a more fundamental problem than that: > > > It emerges from the OP's second post) that he wants '-' in the > > > attributes. Is that all? > > > > > > Where does this syntax-enlargement stop? Spaces? Newlines? > > > > At non-strings. > > > > >>> setattr(foo, 21+21, 42) > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: attribute name must be string, not 'int' > > Not sure what's your point. > > OP wants attribute identifiers like > outer_fieldset-inner_fieldset-third_field. > Say I have a python expression: > obj.outer_fieldset-inner_fieldset-third_field > > It can (in the proposed extension) be parsed as above, or as: > obj.outer_fieldset - inner_fieldset-third_field > the first hyphen being minus and the second being part of the > identifier. > > How do we decide which '-' are valid identifier components -- > hyphens and which minus-signs? I think the OP might be after the JavaScript mechanism where an attribute name can be any string, the indexing brackets are always available, and the dot notation is available when the attribute name looks like a simple identifier. That could be made to work. (I'm not saying should, or should not. Just that it seems technically simple.) Hm. Can't specific classes be made to behave this way even now by implementing suitable underscored methods? -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wed, Dec 4, 2013 at 10:30 PM, Jussi Piitulainen wrote: > Hm. Can't specific classes be made to behave this way even now by > implementing suitable underscored methods? Yup. Definitely possible. I don't think it'd be a good idea, though, not without somehow changing every dict method into a stand-alone function. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 3:59:06 PM UTC+5:30, Antoon Pardon wrote: > Op 04-12-13 11:09, rusi schreef: > > I used the spaces case to indicate the limit of chaos. > > Other characters (that > > already have uses) are just as problematic. > > I don't agree with the latter. As it is now python can make the > distinction between > > from A import Band fromAimportB. > > I see no a priori reason why this should be limited to letters. A > language designer might choose to allow a bigger set of characters > in identifiers like '-', '+' and others. In that case a-b would be > an identifier and a - b would be the operation. Just as in python > fromAimportB is an identifier and from A import B is an import > statement. Im not sure what you are saying. Sure a language designer can design a language differently from python. I mentioned lisp. Cobol is another behaving exactly as you describe. My point is that when you do (something like) that, you will need to change the lexical and grammatical structure of the language. And this will make for rather far-reaching changes ALL OVER the language not just in what-follows-dot. IOW: I dont agree that we have a disagreement :-) -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
Op 04-12-13 13:01, rusi schreef: > On Wednesday, December 4, 2013 3:59:06 PM UTC+5:30, Antoon Pardon wrote: >> Op 04-12-13 11:09, rusi schreef: >>> I used the spaces case to indicate the limit of chaos. >>> Other characters (that >>> already have uses) are just as problematic. >> >> I don't agree with the latter. As it is now python can make the >> distinction between >> >> from A import Band fromAimportB. >> >> I see no a priori reason why this should be limited to letters. A >> language designer might choose to allow a bigger set of characters >> in identifiers like '-', '+' and others. In that case a-b would be >> an identifier and a - b would be the operation. Just as in python >> fromAimportB is an identifier and from A import B is an import >> statement. > > Im not sure what you are saying. > Sure a language designer can design a language differently from python. > I mentioned lisp. Cobol is another behaving exactly as you describe. > > My point is that when you do (something like) that, you will need to change > the > lexical and grammatical structure of the language. And this will make > for rather far-reaching changes ALL OVER the language not just in > what-follows-dot. No you don't need to change the lexical and grammatical structure of the language. Changing the characters allowed in identifiers, is not a change in lexical structure. The only difference in lexical structuring would be that '-', '>=' and other similars symbols would have to be treated like keyword like 'from', 'as' etc instead of being recognizable by just being present. And the grammatical structure of the language wouldn't change at all. Sure a-b would now be an identifier and not an operation but that is of no concern for the parser. People would have to be careful to insert spaces around operators and that might make the language somewhat error prone but that doesn't mean the syntactical structure is different. -- Antoon Pardon -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 6:02:18 PM UTC+5:30, Antoon Pardon wrote: > Op 04-12-13 13:01, rusi schreef: > > On Wednesday, December 4, 2013 3:59:06 PM UTC+5:30, Antoon Pardon wrote: > >> Op 04-12-13 11:09, rusi schreef: > >>> I used the spaces case to indicate the limit of chaos. > >>> Other characters (that > >>> already have uses) are just as problematic. > >> > >> I don't agree with the latter. As it is now python can make the > >> distinction between > >> > >> from A import Band fromAimportB. > >> > >> I see no a priori reason why this should be limited to letters. A > >> language designer might choose to allow a bigger set of characters > >> in identifiers like '-', '+' and others. In that case a-b would be > >> an identifier and a - b would be the operation. Just as in python > >> fromAimportB is an identifier and from A import B is an import > >> statement. > > > > Im not sure what you are saying. > > Sure a language designer can design a language differently from python. > > I mentioned lisp. Cobol is another behaving exactly as you describe. > > > > My point is that when you do (something like) that, you will need to change > > the > > lexical and grammatical structure of the language. And this will make > > for rather far-reaching changes ALL OVER the language not just in > > what-follows-dot. > > No you don't need to change the lexical and grammatical structure of > the language. Changing the characters allowed in identifiers, is not a > change in lexical structure. The only difference in lexical structuring > would be that '-', '>=' and other similars symbols would have to be > treated like keyword like 'from', 'as' etc instead of being recognizable > by just being present. Well I am mystified… Consider the string a-b in a program text. A Cobol or Lisp system sees this as one identifier. Python, C (and most modern languages) see this ident, operator, ident. As I understand it this IS the lexical structure of the language and the lexer is the part that implements this: - in cobol/lisp keeping it as one - in python/C breaking it into 3 Maybe you understand in some other way the phrase "lexical structure"? > And the grammatical structure of the language wouldn't change at all. > Sure a-b would now be an identifier and not an operation but that is > of no concern for the parser. About grammar maybe what you are saying will hold: presumably if the token-set is the same, one could keep the same grammar, with the differences being entirely inter-lexeme ones. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
In article <[email protected]>, Tim Roberts wrote: > Piotr Dobrogost wrote: > > > >Attribute access syntax being very concise is very often preferred > >to dict's interface. > > It is not "very concise". It is slightly more concise. > > x = obj.value1 > x = dct['value1'] > > You have saved 3 keystrokes. That is not a significant enough savings to > create new syntax. Remember the Python philosophy that there ought to be > one way to do it. I'll trade typing [ ' ' ] for . any day. Easier to type, easier to read. It's not just the character count, it's that you need to move your fingers off the home row (or, at the very least, a big stretch with your pinkie) to reach the brackets. I suppose that depends on your particular keyboard layout and typing style/skill. -- https://mail.python.org/mailman/listinfo/python-list
simple ElementTree based parser that allows entity definition map
I'm tasked with writing a 'simple' ElementTree based parser with support for
unknown entities eg &foo;.
This code derived from FL's old documentation fails in both python 2 and 3.
import xml.etree.ElementTree as ET
try:
ascii
except:
from future_builtins import ascii
class EchoTarget:
def start(self, tag, attrib):
print("start %s %s"%(tag, ascii(attrib)))
def end(self, tag):
print("end %s"%tag)
def data(self, data):
print("data %s" % ascii(data))
def close(self):
print("close")
def __getattr__(self,a):
print('target attempting to get attribute %s' % a)
target = EchoTarget()
parser = ET.XMLParser(target=target)
parser.entity['foo'] = b'&fum;'
parser.entity['fum'] = b''
print("parser.entity=%s" % ascii(parser.entity))
parser.feed("some text &foo;")
parser.feed("")
parser.close()
The entity value doesn't seem to get referenced.
I tried this derived from
http://stackoverflow.com/questions/7237466/python-elementtree-support-for-parsing-unknown-xml-entities
__all__=tuple(filter(None,'''
Xml2TT
EntityMap
'''.split()))
import xml.etree.ElementTree as ET
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class EntityMap(dict):
def __getitem__(self,key):
try:
r = dict.__getitem__(self,key)
except:
r = '&' + key +';'
return r
class Xml2TT:
'''
create a callable object that can turns xml into a tupletree
if mutable is set to True then it's really a list tree
'''
def __init__(self,mutable=False,entityMap=None):
self._mutable = mutable
self._parser = parser = ET.XMLParser()
parser.parser.UseForeignDTD(True)
parser.entity = self._entityMap = entityMap
def __call__(self,xml):
r = self._mtt(ET.ElementTree().parse(StringIO(xml.strip()),
parser=self._parser))
return r[0]
def _mtt(self,node):
t = [node.text] if node.text else []
e = t.extend
for c in node:
e(self._mtt(c))
t = (node.tag,node.attrib,t,None)
if self._mutable:
t = list(t)
return [t,node.tail] if node.tail else [t]
if __name__=='__main__':
print(repr(Xml2TT()('a22')))
print(repr(Xml2TT()('a=&=b< >')))
print(repr(Xml2TT(entityMap=EntityMap({'mu': '…','foo':
'AAA&fum;BBB','fum':'CCC'}))('amp=& moo=&moo; lt=< gt=> mu=ÎĽ
foo=&foo;')))
and it sort of works in python2, fails in python3 with
AttributeError: 'xml.etree.ElementTree.XMLParser' object has no attribute
'parser'
Even in python 2 there's a subtle bug as the output is
('a', {}, ['a', ('b', {}, ['', ('c', {'ca': '123'}, [], None), '22'],
None)], None)
('a', {}, ['a=&=b< >'], None)
('a', {}, [u'amp=& moo=&moo; lt=< gt=> mu=… foo=AAA&fum;BBB'], None)
ie the result of the &foo; lookup is not re-parsed so &fum; is not translated.
Is there a way to get a simple ElementTree based parser that can do what I want?
I have several hundred entities and the size of the DTD would probably be larger
than 99% of the strings I need to parse. I think I can live with the
non-reparsing of the map output, but can I get Python 3 to do the UseForeignDTD
thing?
--
Robin Becker
--
https://mail.python.org/mailman/listinfo/python-list
Re: Python Unicode handling wins again -- mostly
Le mardi 3 décembre 2013 15:26:45 UTC+1, Ethan Furman a écrit : > On 12/02/2013 12:38 PM, Ethan Furman wrote: > > > On 11/29/2013 04:44 PM, Steven D'Aprano wrote: > > >> > > >> Out of the nine tests, Python 3.3 passes six, with three tests being > > >> failures or dubious. If you believe that the native string type should > > >> operate on code-points, then you'll think that Python does the right > > >> thing. > > > > > > I think Python is doing it correctly. If I want to operate on "clusters" > > I'll normalize the string first. > > > > Hrmm, well, after being educated ;) I think I may have to reverse my > position. Given that not every cluster can be > > normalized to a single code point perhaps Python is doing it the best > possible way. On the other hand, we have a > > uni*code* type, not a uni*char* type. Maybe 3.5 can have that. ;) > > -- Yon intuitively pointed a very important feature of "unicode". However, it is not necessary, this is exactly what unicode does (when used properly). jmf -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Unicode handling wins again -- mostly
On 04/12/2013 13:52, [email protected] wrote: [snip all the double spaced stuff] Yon intuitively pointed a very important feature of "unicode". However, it is not necessary, this is exactly what unicode does (when used properly). jmf Presumably using unicode correctly prevents messages being sent across the ether with superfluous, extremely irritating double spacing? Or is that down to poor tools in combination with the ignorance of their users? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] Managing Google Groups headaches
On 2013-12-04, alex23 wrote: > On 3/12/2013 5:13 PM, Steven D'Aprano wrote: >> You poor fools you, this is what happens when you give control >> of the tools you use to a (near) monopolist whose incentives >> are not your incentives. > > To paraphrase Franklin: those who would give up control to > purchase convenience deserve neither. A lesson hard learned :( But Franklin's quote doesn't apply when free alternatives exist. I can use a non-open email system until I don't want to any more, and switch out when it no longer please me. The cost of switching isn't zero, but it's much easier than emmigrating from a police state. Moreover, I'll always feel that I deserve more than I actually do deserve. -- Neil Cerutti -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Unicode handling wins again -- mostly
On 2013-12-04, [email protected] wrote: > Yon intuitively pointed a very important feature of "unicode". > However, it is not necessary, this is exactly what unicode does > (when used properly). Unicode only provides character sets. It's not a natural language parsing facility. -- Neil Cerutti -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
(comments from a lurker on python-list) - Google "groups" is a disaster. It's extremely poorly-run, and is in fact a disservice to Usenet -- which is alive and well, tyvm, and still used by many of the most senior and experienced people on the Internet. (While some newsgroups are languishing and some have almost no traffic, others are thriving. As it should be.) I could catalog the litany of egregious mistakes that Google has made, but what's the point? They're clearly uninterested in fixing them. Their only interest is in slapping the "Google" label on Usenet -- which is far more important in the evolution of the Internet than Google will ever be -- so that they can use it as a marketing vehicle. Worse, Google has completely failed to control outbound abuse from Google groups, which is why many consider it a best practice to simply drop all Usenet traffic originating there. - That said, there is value in bidirectionally gatewaying mailing lists with corresponding Usenet newsgroups. Usenet's propagation properties often make it the medium of choice for many people, particularly those in areas with slow, expensive, erratic, etc. connectivity. Conversely, delivery of Usenet traffic via email is a better solution for others. Software like Mailman facilitates this fairly well, even given the impedance mismatch between SMTP and NNTP. - Mailing lists/Usenet newsgroups remain, as they've been for a very long time, the solutions of choice for online discussions. Yes, I'm aware of web forums: I've used hundreds of them. They suck. They ALL suck, they just all suck differently. I could spend the next several thousand lines explaining why, but instead I'll just abbreviate: they don't handle threading, they don't let me use my editor of choice, they don't let me build my own archive that I can search MY way including when I'm offline, they are brittle and highly vulnerable to abuse and security breaches, they encourage worst practices in writing style (including top-posting and full-quoting), they translate poorly to other formats, they are difficult to archive, they're even more difficult to migrate (whereas Unix mbox format files from 30 years ago are still perfectly usable today), they aren't standardized, they aren't easily scalable, they're overly complex, they don't support proper quoting, they don't support proper attribution, they can't be easily forwarded, they...oh, it just goes on. My point being that there's a reason that the IETF and the W3C and NANOG and lots of other groups that could use anything they want use mailing lists: they work. - That said, they work *if configured properly*, which unfortunately these days includes a hefty dose of anti-abuse controls. This list (for the most part) isn't particularly targeted, but it is occasionally and in the spirit of trying to help out, I can assist with that. (I think it's fair to say I have a little bit of email expertise.) If any of the list's owners are reading this and want help, please let me know. - They also work well *if used properly*, which means that participants should use proper email/news etiquette: line wrap, sane quoting style, reasonable editing of followups, preservation of threads, all that stuff. The more people do more of that, the smoother things work. On the other hand, if nobody does that, the result is impaired communication and quite often, a chorus of "mailing lists suck" even though the problem is not the mailing lists: it's the bad habits of the users on them. (And of course changing mediums won't fix that.) - To bring this back around to one of the starting points for this discussion: I think the current setup is functioning well, even given the sporadic stresses placed on it. I think it would be best to invest effort in maintaining/improving it as it stands (which is why I volunteered to do so, see above) rather than migrating to something else. ---rsk -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] Managing Google Groups headaches
On 04/12/2013 14:34, Neil Cerutti wrote: On 2013-12-04, alex23 wrote: On 3/12/2013 5:13 PM, Steven D'Aprano wrote: You poor fools you, this is what happens when you give control of the tools you use to a (near) monopolist whose incentives are not your incentives. To paraphrase Franklin: those who would give up control to purchase convenience deserve neither. A lesson hard learned :( But Franklin's quote doesn't apply when free alternatives exist. Free at the point of delivery, someone, somewhere, has given blood, toil, tears and sweat. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Input without line break, is it possible?
The source code: for i in range(8): n = input() When we run it, consider the numbers below is the user input, 1 2 3 4 5 6 (and so forth) my question, can i make it in just a single line like, 1 2 3 4 5 6 (and so forth) Can I? -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
On Thu, Dec 5, 2013 at 1:52 AM, Rich Kulawiec wrote: > Mailing lists/Usenet newsgroups remain, as they've been for a very > long time, the solutions of choice for online discussions. Yes, I'm > aware of web forums: I've used hundreds of them. They suck. They ALL > suck, they just all suck differently. I absolutely agree. And Mailman lists are both easy and powerful - I've deployed a number of them and subscribed to many MANY more - and play nicely with other internet standards. Instead of having to remember to check umpteen web-based forums, I just check my emails, which I do constantly anyway. Adding another mailing list costs me nothing; adding another forum costs me quite a bit of time. Ultimately it comes down to this: It would take an enormous amount of effort for something else to replicate the power of SMTP and/or NNTP, ergo nothing has achieved that. The open standards mean there are myriad clients available, and no new protocol or system can ever hope to compete with that. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Input without line break, is it possible?
On 2013-12-04 07:38, [email protected] wrote: > for i in range(8): >n = input() > > When we run it, consider the numbers below is the user input, > > 1 > 2 > 3 > 4 > 5 > 6 > (and so forth) > > my question, can i make it in just a single line like, > > 1 2 3 4 5 6 (and so forth) Not easily while processing the input one at a time. You can, however, read one line of input and then split it: s = input() bits = s.split() if len(bits) != 8: what_now("?") else: for bit in bits: do_something(bit) You could make it a bit more robust with something like: answers = [] while len(answers) < 8: s = input() answers.append(s.split()) del answers[8:] # we only want 8, so throw away extras for answer in answers: do_something(answer) which would at least ensure that you have 8 entries. -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
On 2013-12-04, Cameron Simpson wrote: > On 30Nov2013 14:25, [email protected] wrote: >> Dennis Lee Bieber writes: >> > [NNTP] clients provide full-fledged editors >>and conversely full-fledged editors provide >>NNTP clients > > GNU Emacs is a LISP operating system disguised as a word processor. > - Doug Mohney, in comp.arch Unix: A set of device drivers used to support the the Emacs operating system. - Don't remember who, where, or when -- Grant Edwards grant.b.edwardsYow! I feel like a wet at parking meter on Darvon! gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Input without line break, is it possible?
On 04/12/2013 15:38, [email protected] wrote: The source code: for i in range(8): n = input() When we run it, consider the numbers below is the user input, 1 2 3 4 5 6 (and so forth) my question, can i make it in just a single line like, 1 2 3 4 5 6 (and so forth) Can I? Yes you can get them on a single line, see the response from Tim Chase. But just to be crystal clear, are you aware that you're getting string representations of numbers, and not the numbers themselves? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Input without line break, is it possible? [correction]
On 2013-12-04 09:55, Tim Chase wrote: > You could make it a bit more robust with something like: > > answers = [] > while len(answers) < 8: > s = input() > answers.append(s.split()) this should be answers.extend(s.split()) instead of .append() That's what I get for coding in my inbox rather than copy/pasting from tested Python code. -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
On 04/12/2013 15:50, Grant Edwards wrote: On 2013-12-04, Cameron Simpson wrote: On 30Nov2013 14:25, [email protected] wrote: Dennis Lee Bieber writes: [NNTP] clients provide full-fledged editors and conversely full-fledged editors provide NNTP clients GNU Emacs is a LISP operating system disguised as a word processor. - Doug Mohney, in comp.arch Unix: A set of device drivers used to support the the Emacs operating system. - Don't remember who, where, or when It's a funny thing the computing world, with some people deriving operating systems from raincoats, and others editing code with a domestic household cleaner, what next, I ask myself? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Input without line break, is it possible?
On Thu, Dec 5, 2013 at 3:04 AM, Mark Lawrence wrote: > On 04/12/2013 15:38, [email protected] wrote: >> >> The source code: >> >> for i in range(8): >> n = input() > > Yes you can get them on a single line, see the response from Tim Chase. But > just to be crystal clear, are you aware that you're getting string > representations of numbers, and not the numbers themselves? Just to clarify, this is assuming that you're using Python 3. Geezle, if you're using Python 2, you need to not use input() for anything - use raw_input() instead, which will do what we're describing here. I yearn for the day when nobody uses Python 2 any more so this doesn't need to be asked. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Input without line break, is it possible?
On 12/04/2013 08:38 AM, [email protected] wrote: > my question, can i make it in just a single line like, > > 1 2 3 4 5 6 (and so forth) > > Can I? Yes of course. raw_input() is going to give you a string that you can then parse any way you want. -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
On 12/4/13 11:07 AM, Mark Lawrence wrote: On 04/12/2013 15:50, Grant Edwards wrote: On 2013-12-04, Cameron Simpson wrote: On 30Nov2013 14:25, [email protected] wrote: Dennis Lee Bieber writes: [NNTP] clients provide full-fledged editors and conversely full-fledged editors provide NNTP clients GNU Emacs is a LISP operating system disguised as a word processor. - Doug Mohney, in comp.arch Unix: A set of device drivers used to support the the Emacs operating system. - Don't remember who, where, or when It's a funny thing the computing world, with some people deriving operating systems from raincoats, and others editing code with a domestic household cleaner, what next, I ask myself? Computing with vacuum cleaners is on the decline at least: http://www.vax.co.uk/vacuum-cleaners --Ned. -- https://mail.python.org/mailman/listinfo/python-list
Re: status of regex modules
On 24/10/2013 22:47, Mark Lawrence wrote: The new module is now five years old. PEP 429 Python 3.4 release schedule has it listed under "Other proposed large-scale changes" but I don't believe this is actually happening. Lots of issues on the bug tracker have been closed as fixed in the new module, see issue 2636 for more data. Some work is still being carried out on the old re module. So where do we stand? Is the new module getting into Python 3.x, Python 4.y or what? If no do all the old issues have to be reopened and applied to the re module? Who has to make the final decision on all of this? Note that I've no direct interest as I rarely if ever use the little perishers, I just find this situation bizarre. Anybody? And FTR I'll break Armed Forces Rule No. 1 and volunteer my own pitifully poor servies if I can help take this forward, as I think it's daft having issues marked as fixed on the bug tracker but the fix not being available in the standard library, only on pypi. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Input without line break, is it possible?
On 04/12/2013 16:14, Chris Angelico wrote: On Thu, Dec 5, 2013 at 3:04 AM, Mark Lawrence wrote: On 04/12/2013 15:38, [email protected] wrote: The source code: for i in range(8): n = input() Yes you can get them on a single line, see the response from Tim Chase. But just to be crystal clear, are you aware that you're getting string representations of numbers, and not the numbers themselves? Just to clarify, this is assuming that you're using Python 3. Geezle, if you're using Python 2, you need to not use input() for anything - use raw_input() instead, which will do what we're describing here. Good point, I saw input() and automatically assumed Python 3, what a sin! The assumption obviously, not Python 3!! I yearn for the day when nobody uses Python 2 any more so this doesn't need to be asked. I'm contemplating what it would be like migrating code from Python 1.x to Python 4.0, the fun and games that could be :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
On Dec 4, 2013, at 6:52 AM, Rich Kulawiec wrote: > Yes, I'm > aware of web forums: I've used hundreds of them. They suck. They ALL > suck, they just all suck differently. I could spend the next several > thousand lines explaining why, but instead I'll just abbreviate: they > don't handle threading, they don't let me use my editor of choice, > they don't let me build my own archive that I can search MY way including > when I'm offline, they are brittle and highly vulnerable to abuse > and security breaches, they encourage worst practices in writing > style (including top-posting and full-quoting), they translate poorly > to other formats, they are difficult to archive, they're even more > difficult to migrate (whereas Unix mbox format files from 30 years ago > are still perfectly usable today), they aren't standardized, they > aren't easily scalable, they're overly complex, they don't support > proper quoting, they don't support proper attribution, they can't > be easily forwarded, they...oh, it just goes on. My point being that > there's a reason that the IETF and the W3C and NANOG and lots of other > groups that could use anything they want use mailing lists: they work. One of the best rants I’ve ever read. Full mental harmonic resonance while I read this. Hope you don’t mind, but I think I’ll be plagiarizing your comments in the future. Maybe I’ll post it on a couple of the web forums I currently have the luxury of regularly hating. -- https://mail.python.org/mailman/listinfo/python-list
Re: Input without line break, is it possible?
On Thu, Dec 5, 2013 at 3:27 AM, Mark Lawrence wrote: > I'm contemplating what it would be like migrating code from Python 1.x to > Python 4.0, the fun and games that could be :) I never used Python 1.x seriously, but when I went digging in one of my OS/2 machines a while ago, I found several Pythons, including a 1.something. Fortunately for my task at hand, there was also a 2.5 or 2.6 or somesuch, which served my purposes :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
On 04/12/2013 16:21, Ned Batchelder wrote: On 12/4/13 11:07 AM, Mark Lawrence wrote: On 04/12/2013 15:50, Grant Edwards wrote: On 2013-12-04, Cameron Simpson wrote: On 30Nov2013 14:25, [email protected] wrote: Dennis Lee Bieber writes: [NNTP] clients provide full-fledged editors and conversely full-fledged editors provide NNTP clients GNU Emacs is a LISP operating system disguised as a word processor. - Doug Mohney, in comp.arch Unix: A set of device drivers used to support the the Emacs operating system. - Don't remember who, where, or when It's a funny thing the computing world, with some people deriving operating systems from raincoats, and others editing code with a domestic household cleaner, what next, I ask myself? Computing with vacuum cleaners is on the decline at least: http://www.vax.co.uk/vacuum-cleaners --Ned. Well it shouldn't be. It's a well known fact that VMS stands for Very Much Safer. I'd compare it to inferior products, but not even the threat of The Comfy Chair will make me type the names. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Input without line break, is it possible?
On 04/12/2013 16:23, Michael Torrie wrote: On 12/04/2013 08:38 AM, [email protected] wrote: my question, can i make it in just a single line like, 1 2 3 4 5 6 (and so forth) Can I? Yes of course. raw_input() is going to give you a string that you can then parse any way you want. That's it lad, you're in detention for one hour. You will write repeatedly "I should be selling Python 3 instead of Python 2" :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/04/2013 03:30 AM, Jussi Piitulainen wrote: rusi writes: How do we decide which '-' are valid identifier components -- hyphens and which minus-signs? I think the OP might be after the JavaScript mechanism where an attribute name can be any string, the indexing brackets are always available, and the dot notation is available when the attribute name looks like a simple identifier. That could be made to work. (I'm not saying should, or should not. Just that it seems technically simple.) Hm. Can't specific classes be made to behave this way even now by implementing suitable underscored methods? No. It is possible to provide attribute access along with key access, but not currently possible to provide attribute access with quoted values -- which is what the OP wants. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
Op 04-12-13 14:02, rusi schreef: > On Wednesday, December 4, 2013 6:02:18 PM UTC+5:30, Antoon Pardon wrote: >> Op 04-12-13 13:01, rusi schreef: >>> On Wednesday, December 4, 2013 3:59:06 PM UTC+5:30, Antoon Pardon wrote: Op 04-12-13 11:09, rusi schreef: > I used the spaces case to indicate the limit of chaos. > Other characters (that > already have uses) are just as problematic. I don't agree with the latter. As it is now python can make the distinction between from A import Band fromAimportB. I see no a priori reason why this should be limited to letters. A language designer might choose to allow a bigger set of characters in identifiers like '-', '+' and others. In that case a-b would be an identifier and a - b would be the operation. Just as in python fromAimportB is an identifier and from A import B is an import statement. >>> >>> Im not sure what you are saying. >>> Sure a language designer can design a language differently from python. >>> I mentioned lisp. Cobol is another behaving exactly as you describe. >>> >>> My point is that when you do (something like) that, you will need to change >>> the >>> lexical and grammatical structure of the language. And this will make >>> for rather far-reaching changes ALL OVER the language not just in >>> what-follows-dot. >> >> No you don't need to change the lexical and grammatical structure of >> the language. Changing the characters allowed in identifiers, is not a >> change in lexical structure. The only difference in lexical structuring >> would be that '-', '>=' and other similars symbols would have to be >> treated like keyword like 'from', 'as' etc instead of being recognizable >> by just being present. > > Well I am mystified… > Consider the string a-b in a program text. > A Cobol or Lisp system sees this as one identifier. > Python, C (and most modern languages) see this ident, operator, ident. > > As I understand it this IS the lexical structure of the language and the lexer > is the part that implements this: > - in cobol/lisp keeping it as one > - in python/C breaking it into 3 > > Maybe you understand in some other way the phrase "lexical structure"? Yes I do. The fact that a certain string is lexically evaluated differently is IMO not enough to conclude the language has a different lexical structure. It only means that the values allowed within the structure are different. What I see here is that some languages have an other alphabet over which identifiers are allowed. >> And the grammatical structure of the language wouldn't change at all. >> Sure a-b would now be an identifier and not an operation but that is >> of no concern for the parser. > > About grammar maybe what you are saying will hold: presumably if the token-set > is the same, one could keep the same grammar, with the differences being > entirely inter-lexeme ones. And the question is. If the token-set is the same, how is then is the lexical structure different rather than just the possible values associate with the tokens? -- Antoon Pardon -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 6:45:05 AM UTC+1, Tim Roberts wrote: > > It is not "very concise". It is slightly more concise. > > x = obj.value1 > x = dct['value1'] > > You have saved 3 keystrokes. Actually only 1 as you should have compared these: x = obj.'value-1' x = dct['value-1'] Unless we compare with what we have now, which gives 9 (without space) or 10 (with space): x = obj.'value-1' x = getattr(obj, 'value-1') > That is not a significant enough savings to create new syntax. Well, 9 characters is probably significant enough saving to create new syntax but saving these characters is only a side effect and is not the most important aspect of this proposal which leads us to the next point. > Remember the Python philosophy that there ought to be one way to do it. Funny you use this argument against my idea as this idea comes from following this rule whereas getattr goes against it. Using dot is the main syntax to access attributes. Following this, the syntax I'm proposing is much more in line with this primary syntax than getattr is. If there ought to be only one way to access attributes then it should be dot notation. Regards, Piotr -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 2:06:44 AM UTC+1, Tim Chase wrote: > > I think random832 is saying that the designed purpose of setattr() > was to dynamically set attributes by name, so they could later be > accessed the traditional way; not designed from the ground-up to > support non-identifier names. But because of the getattr/setattr > machinery (dict key/value pairs), it doesn't prevent you from having > non-identifiers as names as long as you use only the getattr/setattr > method of accessing them. Right. If there's already a way to have attributes with these "non-standard" names (which is a good thing) then for uniformity with dot access to attributes with "standard" names there should be a variant of dot access allowing to access these "non-standard" named attributes, too. Regards, Piotr -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 04/12/2013 20:35, Piotr Dobrogost wrote: On Wednesday, December 4, 2013 2:06:44 AM UTC+1, Tim Chase wrote: I think random832 is saying that the designed purpose of setattr() was to dynamically set attributes by name, so they could later be accessed the traditional way; not designed from the ground-up to support non-identifier names. But because of the getattr/setattr machinery (dict key/value pairs), it doesn't prevent you from having non-identifiers as names as long as you use only the getattr/setattr method of accessing them. Right. If there's already a way to have attributes with these "non-standard" names (which is a good thing) then for uniformity with dot access to attributes with "standard" names there should be a variant of dot access allowing to access these "non-standard" named attributes, too. Regards, Piotr The obvious thing to do is to either raise this on python ideas, or if you're that confident about it raise an issue on the bug tracker with a patch, which would include changes to unit tests and documentation as well as code, get it reviewed and approved and Bob's your uncle, job done. Too late for Python 3.4 of course, but no problem for 3.5. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/04/2013 12:07 PM, Piotr Dobrogost wrote: If there ought to be only one way to access attributes then it should be dot notation. Not "only one way", it's "one obvious way". The obvious way to deal with objects that do not have legal identifier names is with a dict. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 04/12/2013 20:22, Ethan Furman wrote: On 12/04/2013 12:07 PM, Piotr Dobrogost wrote: If there ought to be only one way to access attributes then it should be dot notation. Not "only one way", it's "one obvious way". -- ~Ethan~ Not "one obvious way" it's "There should be one-- and preferably only one --obvious way to do it.". Get it right lad :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wed, Dec 4, 2013 at 3:35 PM, Piotr Dobrogost wrote: > Right. If there's already a way to have attributes with these "non-standard" > names (which is a good thing) then for uniformity with dot access to > attributes with "standard" names there should be a variant of dot access > allowing to access these "non-standard" named attributes, too. Given the follow code, what do you think should print? class My_Class(object): pass bar = 1 my_object = My_Class() setattr(my_object, 'foo', 10) setattr(my_object, 'bar', 100) setattr(my_object, 'foo-bar', 1000) print(my_object.foo-bar) Today (in python 3.3), it prints 9, because my_object.foo is 10, the local variable bar is equal to 1, and 10 minus 1 is 9.. Under your new proposal, it would print 1000, right? Is there any way for your proposal to be backwards compatible? -- Jerry -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 2:23:24 PM UTC+1, Roy Smith wrote: > In article <[email protected]>, > > Tim Roberts <> wrote: > > > Piotr Dobrogost <> wrote: > > > >Attribute access syntax being very concise is very often preferred > > >to dict's interface. > > > It is not "very concise". It is slightly more concise. > > > x = obj.value1 > > x = dct['value1'] > > > You have saved 3 keystrokes. That is not a significant enough savings to > > create new syntax. Remember the Python philosophy that there ought to be > > one way to do it. > > I'll trade typing [ ' ' ] for . any day. Easier to type, easier to > read. It's not just the character count, it's that you need to move > your fingers off the home row (or, at the very least, a big stretch with > your pinkie) to reach the brackets. I suppose that depends on your > particular keyboard layout and typing style/skill. Very true. Just a remark it's actually trading getattr(o,'x') for o.'x' (saving of 11 keystrokes - don't forget shifts :)) as attribute is quite a different beast then key in a dictionary so comparing this to dict's interface is comparing apples to oranges. Regards, Piotr -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/04/2013 12:58 PM, Jerry Hill wrote: On Wed, Dec 4, 2013 at 3:35 PM, Piotr Dobrogost wrote: Right. If there's already a way to have attributes with these "non-standard" names (which is a good thing) then for uniformity with dot access to attributes with "standard" names there should be a variant of dot access allowing to access these "non-standard" named attributes, too. Given the follow code, what do you think should print? class My_Class(object): pass bar = 1 my_object = My_Class() setattr(my_object, 'foo', 10) setattr(my_object, 'bar', 100) setattr(my_object, 'foo-bar', 1000) print(my_object.foo-bar) Actually, under his proposal it would be: print(my_object."foo-bar") and it would print 1000, while yours would still print 9. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 2013-12-04, Piotr Dobrogost wrote: > On Wednesday, December 4, 2013 2:06:44 AM UTC+1, Tim Chase wrote: >> >> I think random832 is saying that the designed purpose of setattr() >> was to dynamically set attributes by name, so they could later be >> accessed the traditional way; not designed from the ground-up to >> support non-identifier names. But because of the getattr/setattr >> machinery (dict key/value pairs), it doesn't prevent you from having >> non-identifiers as names as long as you use only the getattr/setattr >> method of accessing them. > > Right. If there's already a way to have attributes with these > "non-standard" names (which is a good thing) At best its a neutral thing. You can use dict for the same purpose with very little effort and no(?) loss of efficiency. > then for uniformity with dot access to attributes with > "standard" names there should be a variant of dot access > allowing to access these "non-standard" named attributes, too. New syntax needs more than theoretical justifications; it needs persuasive use cases. Using invalid identifiers as attributes is generally a bad idea, not something to do commonly. Your proposed syntax leaves the distinction between valid and invalid identifiers a problem the programmer has to deal with. It doesn't unify access to attributes the way the getattr and setattr do. -- Neil Cerutti -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/04/2013 12:55 PM, Mark Lawrence wrote: On 04/12/2013 20:22, Ethan Furman wrote: On 12/04/2013 12:07 PM, Piotr Dobrogost wrote: If there ought to be only one way to access attributes then it should be dot notation. Not "only one way", it's "one obvious way". Not "one obvious way" it's "There should be one-- and preferably only one --obvious way to do it.". Get it right lad :) I was paraphrasing. ;) -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 10:41:49 PM UTC+1, Neil Cerutti wrote: > > not something to do commonly. Your proposed syntax leaves the > distinction between valid and invalid identifiers a problem the > programmer has to deal with. It doesn't unify access to > attributes the way the getattr and setattr do. Taking into account that obj.'x' would be equivalent to obj.x any attribute can be accessed with the new syntax. I don't see how this is not unified access compared to using getattr instead dot... Regards, Piotr -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Tuesday, December 3, 2013 6:48:38 PM UTC+1, Dave Angel wrote: > On Tue, 3 Dec 2013 09:14:49 -0800 (PST), Piotr Dobrogost > > wrote: > > > What is the reason there's no "natural" syntax allowing to access > > attributes with names not being valid Python identifiers in a similar > > way to other attributes? > > There is. Just use a dictionary. Object's attributes and dictionary's keys are quite different things. What about descriptors? Regards, Piotr -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/4/2013 3:07 PM, Piotr Dobrogost wrote: You have proposed to make non-identifier attribute names 'official', rather than discouraged, by abbreviating > x = getattr(obj, 'value-1') or x = obj.__dict__['value-1'] # implementation detail as x = obj.'value-1' The discussion of enlarging the scope of 'identifier' is not relevant as you are not proposing that. In particular, you are not asking that obj.value-1 get the 'value-1' attribute of obj. The discussion of keystrokes is also a side-track. What you are proposing, I believe, is a new grammatical category: attribute-name := identifier or string-literal. This would break the symmetry of the grammatical form identifier '.' identifier and change it to the asymmetrical identifier '.' attribute-name, and that is the problem. Most identifiers are attributes of a namespace and many attributes are set *and accessed* as undotted names in module or class code. The symmetry is at least partly inherent and breaking it does not work very well. >>> len is __builtins__.len True >>> __globals__ = __import__(__name__) >>> a = 1 >>> a is __globals__.a True To put it another way, how does 'obj' get the non-standard attribute 'value-1', when obj is a module or class? The workaround given above for module attributes will not work for classes. Remember the Python philosophy that there ought to be one way to do it. Funny you use this argument against my idea as this idea comes from following this rule whereas getattr goes against it. Not really. As others have pointed out, getattr is the preferred way to get the value of an attribute when you have an object with attributes and a run-time-only reference to the name in a string variable. It would also be the case that "obj.'value' is obj.value", so the proposal *would* add duplication. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 10:41:49 PM UTC+1, Neil Cerutti wrote: > On 2013-12-04, Piotr Dobrogost <> wrote: > > > Right. If there's already a way to have attributes with these > > "non-standard" names (which is a good thing) > > At best its a neutral thing. You can use dict for the same > purpose with very little effort and no(?) loss of efficiency. As much as many people in this topic would like to put equal sign between attributes and dictionary's keys they are not the same thing. AFAIK descriptor protocol works only with attributes, right? Regards, Piotr -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wed, 4 Dec 2013 14:05:11 -0800 (PST), Piotr Dobrogost wrote: Object's attributes and dictionary's keys are quite different things. Right. So if you need arbitrary keys, use a dict. Attributes are keyed by identifiers, which are constrained. No problem. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
On 03Dec2013 17:39, rusi wrote: > On Wednesday, December 4, 2013 6:10:05 AM UTC+5:30, Cameron Simpson wrote: > > My first act on joining any mailing list is to download the entire > > archive into my local mail store. I have a script for this, for > > mailman at least. > > and you happen to own >1 thingys that have general computing > functionality -- phones, laptops, desktops, etc -- do you sync > all your mailing-lists with all of them? No. I'm using a laptops my primary host, and it has the mailing lists (and all my email). It is usually on and fetches and files my email; it also forwards _specific_ stuff to a separate mail account accessed by my phone. I used to use a home server, but the remote access, while fairly transparent (script to "ssh then run mutt"), was irritating. And when I didn't have remote access, very very irritating. So I'm choosing the better environment with my email local to the laptop and a select copy of important things (work and friends) copied to an account for my phone. [...] > And inspite of all that it still sometimes happens that one has > to work on a 'machine' that is not one's own. What then? Fingers crossed the important stuff gets to my phone. If urgent I can reply from that, and I'm somewhat up to date on what I care about. The phone also has (disabled) access to my primary mail spool for circumstances when the laptop is offline. When online, the laptop empties that spool ad forwards particulars. When offline, I can consult what's queuing up. > The unfortunate and inexorable conclusion is that when the > (wo)man <-> computer relation goes from 1-1 to 1-many, data and > functionality will move away from 'own-machine' to the cloud. > Will the data be subject to privacy-abuse and worse? Sure > Will the functionality be as good as something one can fine-tune > on one's own computer? heck no! I'm striving to resist that for now. Privacy. Security. Dependence on others' hardware and (not mine => wrong!) technical choices of software. Cheers, -- Cameron Simpson All it takes is working on someone elses program to understand why they call it "code". - Henry O. Farad -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/04/2013 02:13 PM, Piotr Dobrogost wrote: On Wednesday, December 4, 2013 10:41:49 PM UTC+1, Neil Cerutti wrote: On 2013-12-04, Piotr Dobrogost <> wrote: Right. If there's already a way to have attributes with these "non-standard" names (which is a good thing) At best its a neutral thing. You can use dict for the same purpose with very little effort and no(?) loss of efficiency. As much as many people in this topic would like to put equal sign between attributes and dictionary's keys they are not the same thing. AFAIK descriptor protocol works only with attributes, right? Correct. It is looking very unlikely that you are going to get enough support for this change. Perhaps you should look at different ways of spelling your identifiers? Why can't you use an underscore instead of a hyphen? -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wednesday, December 4, 2013 11:11:56 PM UTC+1, Terry Reedy wrote: > > The discussion of enlarging the scope of 'identifier' is not relevant as > you are not proposing that. In particular, you are not asking that > obj.value-1 get the 'value-1' attribute of obj. Right. > The discussion of keystrokes is also a side-track. To great degree, yes. Having said that I find extra 11 keystrokes needed to access some attributes to be a freaking big and unjustifiable number. > What you are proposing, I believe, is a new grammatical category: > attribute-name := identifier or string-literal. This would break the > symmetry of the grammatical form identifier '.' identifier and change it > to the asymmetrical identifier '.' attribute-name, and that is the Nice description. > To put it another way, how does 'obj' get the non-standard attribute > 'value-1', when obj is a module or class? The workaround given above for > module attributes will not work for classes. I'm not sure I see your point. Do you mean that being inside class declaration there's no name that referrs to the current namespace (the way __globals__ refer to module's namespace) thus we can't use proposed syntax to access non-standard attributes from this namespace? > > >> Remember the Python philosophy that there ought to be one way to do > >> it. > > > Funny you use this argument against my idea as this idea comes from > > following this rule whereas getattr goes against it. > > Not really. As others have pointed out, getattr is the preferred way to > get the value of an attribute when you have an object with attributes > and a run-time-only reference to the name in a string variable. Yes, and I think it's very unfortunate in itself. Attribute access is fundamental operation and it's not accident that "operator" for this action is very concise in many languages being one char only. Having to switch to global function to access attribute in case its name is known only at run time is very awkward both when writing and reading code. > It would also be the case that "obj.'value' is obj.value", so the > proposal *would* add duplication. This is not a big deal and that's what you get when someone had already decided that in expression a.b, b is treated literally. Regards, Piotr -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Thursday, December 5, 2013 12:09:52 AM UTC+1, Ethan Furman wrote: > Perhaps you should look > at different ways of spelling your identifiers? Why can't you use an > underscore instead of a hyphen? So that underscore could be left for use inside fields' names? However I think we could use some unique Unicode character for this instead hyphen as long as Python allows any alphanumeric Unicode character inside identifiers which I think it does... Regards, Piotr -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/04/2013 03:57 PM, Piotr Dobrogost wrote: On Thursday, December 5, 2013 12:09:52 AM UTC+1, Ethan Furman wrote: Perhaps you should look at different ways of spelling your identifiers? Why can't you use an underscore instead of a hyphen? So that underscore could be left for use inside fields' names? However I think we could use some unique Unicode character for this instead hyphen as long as Python allows any alphanumeric Unicode character inside identifiers which I think it does... Yes, although I don't remember at which version that became true... -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Managing Google Groups headaches
In article , Rich Kulawiec wrote: > Yes, I'm > aware of web forums: I've used hundreds of them. They suck. They ALL > suck, they just all suck differently. I could spend the next several > thousand lines explaining why, but instead I'll just abbreviate: they > don't handle threading, they don't let me use my editor of choice, > they don't let me build my own archive that I can search MY way including > when I'm offline, they are brittle and highly vulnerable to abuse > and security breaches, they encourage worst practices in writing > style (including top-posting and full-quoting), they translate poorly > to other formats, they are difficult to archive, they're even more > difficult to migrate (whereas Unix mbox format files from 30 years ago > are still perfectly usable today), they aren't standardized, they > aren't easily scalable, they're overly complex, they don't support > proper quoting, they don't support proper attribution, they can't > be easily forwarded, they...oh, it just goes on. The real problem with web forums is they conflate transport and presentation into a single opaque blob, and are pretty much universally designed to be a closed system. Mail and usenet were both engineered to make a sharp division between transport and presentation, which meant it was possible to evolve each at their own pace. Mostly that meant people could go off and develop new client applications which interoperated with the existing system. But, it also meant that transport layers could be switched out (as when NNTP gradually, but inexorably, replaced UUCP as the primary usenet transport layer). -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
In article , Dennis Lee Bieber wrote: > Spaces? I present to you two FORTRAN statements > > DO 10 I = 3 . 14159 > and > DO10I = 3 , 1 4 1 5 9 > > Which is the loop and which is the assignment? I know it's rude to quote oneself, but: http://www.python.org/doc/humor/#bad-habits -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/4/13 6:57 PM, Piotr Dobrogost wrote: On Thursday, December 5, 2013 12:09:52 AM UTC+1, Ethan Furman wrote: Perhaps you should look at different ways of spelling your identifiers? Why can't you use an underscore instead of a hyphen? So that underscore could be left for use inside fields' names? However I think we could use some unique Unicode character for this instead hyphen as long as Python allows any alphanumeric Unicode character inside identifiers which I think it does... Regards, Piotr You object to typing [''] but you don't mind typing an unusual Unicode character? --Ned. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python and PEP8 - Recommendations on breaking up long lines?
Hi Victor,
I use PyCharm which is set up by default to warn when line length exceeds 120
chars, not 80. Perhaps times have changed?
I often break comprehensions at the for, in and else clauses. It's often not
for line length reasons but because it's easier to follow the code that way. I
have heard this is how Haskell programmers tend to use comprehensions
(comprehensions are from Haskell originally):
location=random.choice([loc['pk']
for loc
in locations.whole_register()
if loc['fields']['provider_id'] == provider_id])))
The other suggestion I have is to put the with clauses in a generator function.
This saves you a level or more of indentation and modularises the code
usefully. Here's an example:
def spreadsheet(csv_filename):
with open(csv_filename) as csv_file:
for csv_row in list(csv.DictReader(csv_file, delimiter='\t')):
yield csv_row
then invoked using:
for row in spreadsheet("...")
# your processing code here
Cheers,
Nick
--
https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 04/12/2013 20:07, Piotr Dobrogost wrote: [...] Unless we compare with what we have now, which gives 9 (without space) or 10 (with space): x = obj.'value-1' x = getattr(obj, 'value-1') That is not a significant enough savings to create new syntax. Well, 9 characters is probably significant enough saving to create new syntax but saving these characters is only a side effect and is not the most important aspect of this proposal which leads us to the next point. Remember the Python philosophy that there ought to be one way to do it. Funny you use this argument against my idea as this idea comes from following this rule whereas getattr goes against it. Using dot is the main syntax to access attributes. Following this, the syntax I'm proposing is much more in line with this primary syntax than getattr is. If there ought to be only one way to access attributes then it should be dot notation. I believe that you are missing the point of getattr. It's not there so that one can use arbitrary strings as attribute names; it's there so that one can get attributes with names that aren't known until run time. For this purpose the dot-notation-with-quotes you suggest above is not good enough. For suppose e.g. that one does this: name = 'attribute' x.name How would the interpreter know whether you're asking for getattr(x, name) or getattr(x, 'name')? -- https://mail.python.org/mailman/listinfo/python-list
Re: extracting a heapq in a for loop - there must be more elegant solution
On 04Dec2013 09:44, Helmut Jarausch wrote:
> On Wed, 04 Dec 2013 08:13:03 +1100, Cameron Simpson wrote:
> > I iterate over Queues so often that I have a personal class called
> > a QueueIterator which is a wrapper for a Queue or PriorityQueue
> > which is iterable, and an IterablePriorityQueue factory function.
> > Example:
> >
> > from cs.queues import IterablePriorityQueue
> >
> > IPQ = IterablePriorityQueue()
> > for item in [1,2,3,7,6,5,9,4]:
> > IPQ.put(item)
> >
> > for item in IPQ:
> > ... do stuff with item ...
>
> Many thanks!
> I think you QueueIterator would be a nice addition to Python's library.
I'm not convinced. I'm still sorting out the edge cases, and it's
my own code and use cases!
The basic idea is simple enough:
class QueueIterator:
def __init__(self, Q, sentinel=None):
self.q = Q
self.sentinel = sentinel
def __next__(self):
item = self.q.get()
if item is self.sentinel:
# queue sentinel again for other users
self.q.put(item)
raise StopIteration
return item
def put(self, item):
if item is self.sentinel:
raise ValueError('.put of sentinel object')
return self.q.put(item)
def close(self):
self.q.put(self.sentinel)
QI = QueueIterator(Queue())
Note that it does not work well for PriorityQueues unless you can
ensure the sentinel sorted later than any other item.
But you really need to be sure nobody does a .get() in the internal
queue, or the close protocol doesn't work. This is why the above
does not expose a .get() method.
You want to prevent .put() on the queue after close().
Of course, I have use cases where I _want_ to allow .put() after
close:-(
You may want to issue a warning if more than one call to
.close happens.
And so on.
And I have a some weird cases where the close situation has trouble,
which probably points to .close() not being a great mapping to
my termination scenarios.
It is easy to code for the simple data-in, data-out case though.
Cheers,
--
Cameron Simpson
Computer manufacturers have been failing to deliver working systems on
time and to budget since Babbage. - Jack Schofield, in The Guardian
--
https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Wed, Dec 4, 2013 at 3:09 AM, rusi wrote: > On Wednesday, December 4, 2013 2:27:28 PM UTC+5:30, Ian wrote: >> On Tue, Dec 3, 2013 at 11:31 PM, rusi wrote: >> > Its a more fundamental problem than that: >> > It emerges from the OP's second post) that he wants '-' in the attributes. >> > Is that all? >> > >> > Where does this syntax-enlargement stop? Spaces? Newlines? >> >> At non-strings. >> >> >>> setattr(foo, 21+21, 42) >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: attribute name must be string, not 'int' > > Not sure what's your point. There was no point. My comment was only meant to be amusing. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/4/2013 3:46 PM, Mark Lawrence wrote:
On 04/12/2013 20:35, Piotr Dobrogost wrote:
On Wednesday, December 4, 2013 2:06:44 AM UTC+1, Tim Chase wrote:
I think random832 is saying that the designed purpose of setattr()
was to dynamically set attributes by name, so they could later be
accessed the traditional way; not designed from the ground-up to
support non-identifier names. But because of the getattr/setattr
machinery (dict key/value pairs), it doesn't prevent you from having
non-identifiers as names as long as you use only the getattr/setattr
method of accessing them.
Right. If there's already a way to have attributes with these
"non-standard" names
Fact.
(which is a good thing)
Opinion, not universally shared by developers, or 'good thing only as
long as kept obscure'.
>> then for uniformity with dot access to attributes with "standard" names
In a later post (after you wrote this) I explained that standard names
are not always accessed with a dot, and that uniformity is impossible.
>> there should be a variant of dot access allowing to access
>> these "non-standard" named attributes, too.
More opinion. I am sure that I am not the only developer who disagrees.
The obvious thing to do is to either raise this on python ideas, or if
you're that confident about it raise an issue on the bug tracker with a
patch, which would include changes to unit tests and documentation as
well as code, get it reviewed and approved and Bob's your uncle, job
done.
I think the latter would be foolish. Syntax changes have a high bar for
acceptance. They should do more than save a few keystrokes. Use of new
syntax makes code backward incompatible. New or changed Python modules
can be backported (as long as they do not use new syntax ;-) either
privately or publicly (on PyPI).
3.2 had no syntax changes; 3.3 one that I know of ('yield from'), which
replaced about 15-20 *lines* of very tricky code; 3.4 has none that I
can remember.
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/04/2013 06:58 PM, Terry Reedy wrote: On 12/4/2013 3:46 PM, Mark Lawrence wrote: On 04/12/2013 20:35, Piotr Dobrogost wrote: there should be a variant of dot access allowing to access these "non-standard" named attributes, too. More opinion. I am sure that I am not the only developer who disagrees. +1 The obvious thing to do is to either raise this on python ideas, or if you're that confident about it raise an issue on the bug tracker with a patch, which would include changes to unit tests and documentation as well as code, get it reviewed and approved and Bob's your uncle, job done. I think the latter would be foolish. Syntax changes have a high bar for acceptance. They should do more than save a few keystrokes. +1 -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On 12/4/2013 6:42 PM, Piotr Dobrogost wrote: On Wednesday, December 4, 2013 11:11:56 PM UTC+1, Terry Reedy wrote: The discussion of keystrokes is also a side-track. To great degree, yes. Having said that I find extra 11 keystrokes needed to access some attributes to be a freaking big and unjustifiable number. Given that there is almost no need to ever use operator chars in attribute names and given that syntax changes have the major undesirable consequence of backward incompatibility, I find it to be a small and inconsequential number. What you are proposing, I believe, is a new grammatical category: attribute-name := identifier or string-literal. This would break the symmetry of the grammatical form identifier '.' identifier and change it to the asymmetrical identifier '.' attribute-name, and that is the Nice description. To put it another way, how does 'obj' get the non-standard attribute 'value-1', when obj is a module or class? The workaround given above for module attributes will not work for classes. The module workaround, which I find pretty ugly, is this: >>> len is __builtins__.len True >>> __globals__ = __import__(__name__) >>> a = 1 >>> a is __globals__.a True I have not checked that the import trick will work when a module is imported, but I believe it will. I'm not sure I see your point. Do you mean that being inside class declaration there's no name that referrs to the current namespace (the way __globals__ refer to module's namespace) thus we can't use proposed syntax to access non-standard attributes from this namespace? Right. Class objects are not created until after the class code runs. Not really. As others have pointed out, getattr is the preferred way to get the value of an attribute when you have an object with attributes and a run-time-only reference to the name in a string variable. Yes, and I think it's very unfortunate in itself. Do you prefer obj.__dict__['name'] to getattr(obj, 'name')? -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
The Python license
The third clause of the PSF license requires you to include a brief summary of changes in Python-derived software. Why? How exactly to comply with it? I think that this condition is not suitable for using Python in closed-source software. I suggest to remove it. -- https://mail.python.org/mailman/listinfo/python-list
Re: The Python license
In article , [email protected] wrote: Now that's the kind of software license I like. Short, and easy to understand. -- https://mail.python.org/mailman/listinfo/python-list
Re: The Python license
On 12/4/2013 10:17 PM, [email protected] wrote: The third clause of the PSF license requires you to include a brief summary of changes in Python-derived software. "In the event Licensee prepares a derivative work that is based on or incorporates Python 3.3.3 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 3.3.3." A program written in Python uses some Python interpreter to execute but is not a derivative work of any of them, as meant above. (Similarly, a Standard C program is not a derivative work of any of the numerous C compilers.) Examples where the above does or might apply: Stackless Python 2.7 is based on CPython 2.7, but it alters the core interpreter a bit to make some things work (or work better). In the process, I believe that some 2.7 code is broken. So it should explain how the 'Stackless 2.7' language is slightly different from 'Python 2.7' (beside any bugfixes not ported back yet). (For one thing, we don't want bug reports like "I ran this code on Stackless and it worked. When I ran it on CPython, it failed. Please fix CPython.") ActiveState Python x.y is CPython x.y, including the stdlib, plus some 3rd party modules, plus propriety code, including a package manager for Windows. They *should* explain that, both to promote their distribution, and to avoid misunderstanding about what is included with the PSF distribution of CPython. Some Python applications bundle the exact Python interpreter they work with. If they alter the bundled Python *and expose it to users*, as a scripting language, then they should explain the language changes. If they do not alter the bundled Python, there is nothing to explain (other than the version), even if it is exposed. For instance, Libre Office 4.0 included a *nix-style copy of Python 3.3.0 for scripting purposes. So the clause is needed, appropriate, and almost certainly not applicable to you. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: status of regex modules
On 12/4/2013 11:21 AM, Mark Lawrence wrote: On 24/10/2013 22:47, Mark Lawrence wrote: The new module is now five years old. PEP 429 Python 3.4 release schedule has it listed under "Other proposed large-scale changes" but I don't believe this is actually happening. Lots of issues on the bug tracker have been closed as fixed in the new module, see issue 2636 for more data. Some work is still being carried out on the old re module. So where do we stand? Is the new module getting into Python 3.x, Python 4.y or what? Good question. I hope so. If no do all the old issues have to be reopened and applied to the re module? I would prefer not. Who has to make the final decision on all of this? Ultimately Guido, with a lot of input Note that I've no direct interest as I rarely if ever use the little perishers, I just find this situation bizarre. It is definitely unfortunate and even embarrassing. At one time, the hangup was a minor feature incompatibility between re and regex. Guido was reluctant to make a switch that would occasionally break code. I believe that this is fixed -- by deciding to call it regex rather then re. My impression from http://bugs.python.org/issue2636 Stage: patch review and pydev discussion is that regex did not land in 3.4 because no one did the rest of the needed review. I do not really know what needs to be done next. Being coded in C does not help speed review. And FTR I'll break Armed Forces Rule No. 1 and volunteer my own pitifully poor servies if I can help take this forward, as I think it's daft having issues marked as fixed on the bug tracker but the fix not being available in the standard library, only on pypi. Are you volunteering to list issues to be reopened, or to help with code review? -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?
On Thursday, December 5, 2013 8:13:49 AM UTC+5:30, Ian wrote: > On Wed, Dec 4, 2013 at 3:09 AM, rusi wrote: > > On Wednesday, December 4, 2013 2:27:28 PM UTC+5:30, Ian wrote: > >> On Tue, Dec 3, 2013 at 11:31 PM, rusi wrote: > >> > Its a more fundamental problem than that: > >> > It emerges from the OP's second post) that he wants '-' in the > >> > attributes. > >> > Is that all? > >> > > >> > Where does this syntax-enlargement stop? Spaces? Newlines? > >> > >> At non-strings. > >> > >> >>> setattr(foo, 21+21, 42) > >> Traceback (most recent call last): > >> File "", line 1, in > >> TypeError: attribute name must be string, not 'int' > > > > Not sure what's your point. > > There was no point. My comment was only meant to be amusing. Duh! Im dense! -- https://mail.python.org/mailman/listinfo/python-list
