Re: Classic OOP in Python
El miércoles, 17 de junio de 2015, 21:44:51 (UTC+2), Ned Batchelder escribió: On Wednesday, June 17, 2015 at 3:21:32 PM UTC-4, Jason P. wrote: Hello Python community. I come from a classic background in what refers to OOP. Mostly Java and PHP ( 5.3). I'm used to abstract classes, interfaces, access modifiers and so on. Don't get me wrong. I know that despite the differences Python is fully object oriented. My point is, do you know any book or resource that explains in deep the pythonic way of doing OOP? For example, I'm gonna try to develop a modest application from ground up using TDD. If it had been done in Java for instance, I would made extensive use of interfaces to define the boundaries of my system. How would I do something like that in Python? Many thanks! What other languages do with interfaces, Python does with duck-typing. You can build something like interfaces in Python, but many people don't bother. I don't know if your project will be web-based, but here is an entire book about developing Python web sites with a TDD approach: http://www.obeythetestinggoat.com/ (Don't mind the unusual domain name, it's a bit of an inside joke...) TDD and interfaces are separate concepts, and I'm not sure they even intersect. TDD is about writing tests as a way to design the best system, and putting testing at the center of your development workflow. It works great with Python even without interfaces. --Ned. I'm aware of duck typing. The point in using interfaces is to be explicit about the boundaries of a system. Quite a red Growing Object-Oriented Software, Guided by Tests, by the way. In fact interfaces are key components in the style of building software they propose, in good company with TDD. Thx! -- https://mail.python.org/mailman/listinfo/python-list
Re: Documenting a function signature (was: Set a flag on the function or a global?)
On Wed, Jun 17, 2015, at 20:14, Chris Angelico wrote: Mostly. That would imply that object is a mandatory parameter, which AIUI isn't the case for Steven's edir. The downside of this kind of signature is that it's hard to show the parameters that have unusual defaults (either sentinel objects and custom code to cope, or they're pulled out of *a or **kw). My instinct would be to put =... for that case and explain in the documentation If foo is not provided, [behavior]. Of course, that runs the risk of people thinking you actually mean Ellipsis, or that providing Ellipsis explicitly will give the same behavior as the default. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classic OOP in Python
On Thu, Jun 18, 2015 at 1:03 PM, Fabien fabien.mauss...@gmail.com wrote: On 06/17/2015 11:16 PM, sohcahto...@gmail.com wrote: You don't need interfaces with Python. Duck typing makes that all possible. Yes, but I also like interfaces (or in python: mimicked interfaces with NotImplementedError) for their clarity and documentation purposes. Would you consider the following kind of program unpythonic? class MovingObject(object): Great doc about what a moving object is def move(self): Great doc about move raise NotImplementedError() class Dog(MovingObject): def move(self): print Dog is moving class Car(MovingObject): def move(self): print Car is moving (Disclaimer: I learned OOP with Java) I think this is what abstract base classes are for in Python. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classic OOP in Python
El miércoles, 17 de junio de 2015, 21:44:51 (UTC+2), Ned Batchelder escribió: On Wednesday, June 17, 2015 at 3:21:32 PM UTC-4, Jason P. wrote: Hello Python community. I come from a classic background in what refers to OOP. Mostly Java and PHP ( 5.3). I'm used to abstract classes, interfaces, access modifiers and so on. Don't get me wrong. I know that despite the differences Python is fully object oriented. My point is, do you know any book or resource that explains in deep the pythonic way of doing OOP? For example, I'm gonna try to develop a modest application from ground up using TDD. If it had been done in Java for instance, I would made extensive use of interfaces to define the boundaries of my system. How would I do something like that in Python? Many thanks! What other languages do with interfaces, Python does with duck-typing. You can build something like interfaces in Python, but many people don't bother. I don't know if your project will be web-based, but here is an entire book about developing Python web sites with a TDD approach: http://www.obeythetestinggoat.com/ (Don't mind the unusual domain name, it's a bit of an inside joke...) TDD and interfaces are separate concepts, and I'm not sure they even intersect. TDD is about writing tests as a way to design the best system, and putting testing at the center of your development workflow. It works great with Python even without interfaces. --Ned. I forgot to mention that the book you recommend seems to be a good starting point ;) -- https://mail.python.org/mailman/listinfo/python-list
Re: Classic OOP in Python
Todd toddr...@gmail.com: On Thu, Jun 18, 2015 at 1:03 PM, Fabien fabien.mauss...@gmail.com wrote: Would you consider the following kind of program unpythonic? class MovingObject(object): Great doc about what a moving object is def move(self): Great doc about move raise NotImplementedError() class Dog(MovingObject): def move(self): print Dog is moving class Car(MovingObject): def move(self): print Car is moving (Disclaimer: I learned OOP with Java) I think this is what abstract base classes are for in Python. And they can be ok as long as you're not making them into a habit. Marko -- https://mail.python.org/mailman/listinfo/python-list
[issue24465] Make tar files created by shutil.make_archive() have deterministic sorting
Changes by Sam Thursfield sam.thursfi...@codethink.co.uk: -- keywords: +patch Added file: http://bugs.python.org/file39728/tarfile-stable-ordering.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24465 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24465] Make tarfile have deterministic sorting
R. David Murray added the comment: This would go beyond what the tar command itself does. I'm not sure we want to do that, as we are pretty much modeling our behavior on tar. However, that doesn't automatically mean we can't do it. We'll see what other people think. Personally I'm -0. I've changed the issue title since your proposed patch is to tarfile, not shutil. -- nosy: +r.david.murray title: Make tar files created by shutil.make_archive() have deterministic sorting - Make tarfile have deterministic sorting versions: +Python 3.6 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24465 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24464] Got warning when compiling sqlite3 module on Mac OSX
New submission from Vajrasky Kok: I got this warning when compiling sqlite3 module. gcc -Wno-unused-result -Wsign-compare -g -O0 -Wall -Wstrict-prototypes -Werror=declaration-after-statement -DMODULE_NAME=sqlite3 -DSQLITE_OMIT_LOAD_EXTENSION=1 -IModules/_sqlite -I/usr/include -I./Include -I. -IInclude -I/usr/local/include -I/Users/sky/Code/python/cpython/Include -I/Users/sky/Code/python/cpython -c /Users/sky/Code/python/cpython/Modules/_sqlite/module.c -o build/temp.macosx-10.10-x86_64-3.6-pydebug/Users/sky/Code/python/cpython/Modules/_sqlite/module.o /Users/sky/Code/python/cpython/Modules/_sqlite/module.c:136:10: warning: 'sqlite3_enable_shared_cache' is deprecated: first deprecated in OS X 10.7 [-Wdeprecated-declarations] rc = sqlite3_enable_shared_cache(do_enable); ^ /usr/include/sqlite3.h:5006:16: note: 'sqlite3_enable_shared_cache' has been explicitly marked deprecated here SQLITE_API int sqlite3_enable_shared_cache(int) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0, __MAC_10_7, __I... ^ 1 warning generated. The enable_shared_cache method will fail if it is used afterwards. Changing the shared_cache flag failed Here is the patch to remove the warning. -- components: Macintosh files: remove_warning_compile__sqlite.patch keywords: patch messages: 245463 nosy: ned.deily, ronaldoussoren, vajrasky priority: normal severity: normal status: open title: Got warning when compiling sqlite3 module on Mac OSX versions: Python 3.4, Python 3.5 Added file: http://bugs.python.org/file39726/remove_warning_compile__sqlite.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24464 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Classic OOP in Python
El miércoles, 17 de junio de 2015, 22:39:31 (UTC+2), Marko Rauhamaa escribió: Ned Batchelder n...@nedbatchelder.com: TDD is about writing tests as a way to design the best system, and putting testing at the center of your development workflow. It works great with Python even without interfaces. I wonder how great it really is. Testing is important, that's for sure, but to make it a dogmatic starting point of development is not that convincing. The way it was explained to me was that in TDD you actually don't write code to any requirements or design: you simply do the least to pass the tests. Thus, say you need to write a program that inputs a string and outputs the same string surrounded by parentheses (the requirement), the starting point might be this test case: - run the program - give it the word hello as input - check that the program prints out (hello) The right TDD thing would be to satisfy the test with this program: input() print((hello)) That *ought* to be the first version of the program until further test cases are added that invalidate it. Another interesting ism I have read about is the idea that the starting point of any software project should be the user manual. The developers should then go and build the product that fits the manual. Marko The refactor phase is key in TDD (red-green-refactor). Again, GOOS is an advisable source of knowledge in this matter. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classic OOP in Python
On Thursday, June 18, 2015 at 7:21:29 AM UTC-4, Jason P. wrote: El miércoles, 17 de junio de 2015, 21:44:51 (UTC+2), Ned Batchelder escribió: On Wednesday, June 17, 2015 at 3:21:32 PM UTC-4, Jason P. wrote: Hello Python community. I come from a classic background in what refers to OOP. Mostly Java and PHP ( 5.3). I'm used to abstract classes, interfaces, access modifiers and so on. Don't get me wrong. I know that despite the differences Python is fully object oriented. My point is, do you know any book or resource that explains in deep the pythonic way of doing OOP? For example, I'm gonna try to develop a modest application from ground up using TDD. If it had been done in Java for instance, I would made extensive use of interfaces to define the boundaries of my system. How would I do something like that in Python? Many thanks! What other languages do with interfaces, Python does with duck-typing. You can build something like interfaces in Python, but many people don't bother. I don't know if your project will be web-based, but here is an entire book about developing Python web sites with a TDD approach: http://www.obeythetestinggoat.com/ (Don't mind the unusual domain name, it's a bit of an inside joke...) TDD and interfaces are separate concepts, and I'm not sure they even intersect. TDD is about writing tests as a way to design the best system, and putting testing at the center of your development workflow. It works great with Python even without interfaces. --Ned. I'm aware of duck typing. The point in using interfaces is to be explicit about the boundaries of a system. Quite a red Growing Object-Oriented Software, Guided by Tests, by the way. In fact interfaces are key components in the style of building software they propose, in good company with TDD. Yes, that book uses interfaces, because that book uses Java. Different languages offer different tools. You can make interfaces in Python, but you don't need to. They aren't enforced by Python, so you aren't gaining much other than documentation from them, so why not just use documentation? Abstract classes provide another tool. They can insist that you provide implementations of abstract methods. In my experience, it is easy to get to a point where you are struggling to satisfy your simple-minded abstract classes, rather than writing the code that you know you need to solve your actual problem. As Chris just mentioned elsewhere in this thread, you have to be very careful how you define your abstract classes. I've worked in Java projects where I had to provide 10 dummy implementations of methods I knew I wasn't going to need, just because the interface insisted they had to exist. The Python culture is to document your expectations, and write enough tests to verify that your code does what it claims to do. You are already planning on a TDD flow, so you will have plenty of tests. Try doing without interfaces or abstract classes. See how it goes. It's the Python way. :) --Ned. -- https://mail.python.org/mailman/listinfo/python-list
Re: Posting gzip'd image file - server says Malformed Upload?
On Wed, Jun 17, 2015, at 20:23, Chris Angelico wrote: On Thu, Jun 18, 2015 at 7:55 AM, Paul Hubert phbr...@gmail.com wrote: f_in = open(dafile, 'rb') f_out = gzip.open('/Users/Paul/Desktop/scripts/pic.jpg.gz', 'wb') f_out.writelines(f_in) f_out.close() f_in.close() Are you sure you want iteration and writelines() here? I would be inclined to avoid those for any situation that isn't plain text. If the file isn't too big, I'd just read it all in a single blob and then write it all out at once. Is there a reason not to use shutil.copyfileobj? -- https://mail.python.org/mailman/listinfo/python-list
[issue24465] Make tar files created by shutil.make_archive() have deterministic sorting
New submission from Sam Thursfield: I want shutil.make_archive() to produce deterministic output when given identical data as inputs. Right now there are two holes in this. One is that mtimes might not match. This can be fixed by the caller. The second is that the order that files in a subdirectory get added to the tarfile is not deterministic. This can't be fixed by the caller. Attached is a trivial patch to sort the results of os.listdir() to ensure the output tarfile is stable. This only applies to the 'tar' format. I've attached my testcase for this, which creates 3 tarfiles in /tmp. When this patch is applied, the 3 tarfiles it creates are identical according to `sha1sum`. Without this patch, they are all different. -- components: Library (Lib) files: tar-reproducible-testcase.py messages: 245464 nosy: samthursfield priority: normal severity: normal status: open title: Make tar files created by shutil.make_archive() have deterministic sorting type: enhancement Added file: http://bugs.python.org/file39727/tar-reproducible-testcase.py ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24465 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: ctypes and byte order
Jean-Michel Pichavant wrote: - Original Message - From: Peter Otten __pete...@web.de becomes $ cat be2.py import ctypes, sys iarray_be = ctypes.c_uint32.__ctype_be__*5 class Foo_be(ctypes.BigEndianStructure): _fields_ = [('bar', iarray_be)] print sys.version f_be = Foo_be((0,1,2,3,0x11223344)) print hex(f_be.bar[4]) $ python be2.py 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] 0x11223344L which might do what you want. Brilliant ! I've tested it and it yields the exact same results (binary file content wise) than my workaround structure. But that's way better since my actual structure is more complex and arrays will be required. Though I'm slightly puzzled by the ctypes author(s) choice, this is not documented and requires to peek into the source code. Dunder attributes are rarely part of an interface. On further reflection it dawned on me that what may have made this work is passing in the tuple instead of an array: import ctypes array = ctypes.c_uint32 * 3 class B(ctypes.BigEndianStructure): ... _fields_ = [(bar, array)] ... b = B((1,2,3)) b.bar ctypes._endian.c_uint_be_Array_3 object at 0x7f87700798c0 b.bar[2] 3L b = B(array(1,2,3)) Traceback (most recent call last): File stdin, line 1, in module TypeError: incompatible types, c_uint_Array_3 instance instead of c_uint_be_Array_3 instance Oops... So the only thing that doesn't work transparently is initialising a data structure (or at least array) from its other-endian twin. -- https://mail.python.org/mailman/listinfo/python-list
Re: ctypes and byte order
- Original Message - From: Peter Otten __pete...@web.de becomes $ cat be2.py import ctypes, sys iarray_be = ctypes.c_uint32.__ctype_be__*5 class Foo_be(ctypes.BigEndianStructure): _fields_ = [('bar', iarray_be)] print sys.version f_be = Foo_be((0,1,2,3,0x11223344)) print hex(f_be.bar[4]) $ python be2.py 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] 0x11223344L which might do what you want. Brilliant ! I've tested it and it yields the exact same results (binary file content wise) than my workaround structure. But that's way better since my actual structure is more complex and arrays will be required. Though I'm slightly puzzled by the ctypes author(s) choice, this is not documented and requires to peek into the source code. Dunder attributes are rarely part of an interface. Anyway, thanks for your help ! JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: help in understanding the stackless code
On 2015-06-18 08:41, ravi wrote: hi, I am new to python and need to know why the calling of switch(1) invokes the function listen twice in the below program? import stackless class EventHandler: def __init__(self,*outputs): if outputs==None: self.outputs=[] else: self.outputs=list(outputs) self.channel = stackless.channel() stackless.tasklet(self.listen)() def listen(self): print in listen()... while 1: val = self.channel.receive() self.processMessage(val) for output in self.outputs: self.notify(output) def processMessage(self,val): pass def notify(self,output): pass def registerOutput(self,output): print in registerOutput()... self.outputs.append(output) def __call__(self,val): print in __call__ ... self.channel.send(val) class Switch(EventHandler): def __init__(self,initialState=0,*outputs): EventHandler.__init__(self,*outputs) self.state = initialState def processMessage(self,val): print in processMessage() of Switch... self.state = val def notify(self,output): print in notify() of switch... output((self,self.state)) class Reporter(EventHandler): def __init__(self,msg=%(sender)s send message %(value)s): EventHandler.__init__(self) self.msg = msg def processMessage(self,msg): print in processMessage() of Reporter... sender,value=msg print self.msg % {'sender':sender,'value':value} if __name__ == __main__: reporter = Reporter() switch = Switch(0,reporter) switch(1) output: = in __call__ ... in listen()... in listen()... in processMessage() of Switch... in notify() of switch... in __call__ ... in processMessage() of Reporter... __main__.Switch instance at 0x8d822cc send message 1 Is it because EventHandler has 2 subclasses, namely Switch and Reporter, and you have an instance of each? -- https://mail.python.org/mailman/listinfo/python-list
thinking with laziness
http://begriffs.com/posts/2015-06-17-thinking-with-laziness.html -- https://mail.python.org/mailman/listinfo/python-list
[issue24463] Python 3.4 bugs
Skip Montanaro added the comment: Not a bug. The two elements of w are references to the same list: w = [[0] * 2] * 2 w [[0, 0], [0, 0]] [id(elt) for elt in w] [21743952, 21743952] -- nosy: +skip.montanaro resolution: - not a bug status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24463 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Classic OOP in Python
On Thu, Jun 18, 2015 at 9:03 PM, Fabien fabien.mauss...@gmail.com wrote: Would you consider the following kind of program unpythonic? class MovingObject(object): Great doc about what a moving object is def move(self): Great doc about move raise NotImplementedError() class Dog(MovingObject): def move(self): print Dog is moving class Car(MovingObject): def move(self): print Car is moving (Disclaimer: I learned OOP with Java) Now try extending the concept to two, three, or four such interfaces. Files can be moved, opened, copied, and unlinked. Should they share any sort of interface with dogs, boxes, handwriting, and railway carriages? It's much better to simply define the attributes of each object separately; most non-trivial cases don't involve simple methods with no additional arguments, and the chances of an incompatibility (or worse, a forced compatibility) go up. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
[issue24465] Make tarfile have deterministic sorting
Lars Gustäbel added the comment: You don't need to patch the tarfile module. You could use os.walk() in shutil._make_tarball() and add each file with TarFile.add(recursive=False). -- nosy: +lars.gustaebel ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24465 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24450] Add gi_yieldfrom calculated property to generator object
Benno Leslie added the comment: I've tried to address all the issues raised in the review of the first patch. -- Added file: http://bugs.python.org/file39725/gi_yieldfrom.v1.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24450 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Classic OOP in Python
On 06/17/2015 11:16 PM, sohcahto...@gmail.com wrote: You don't need interfaces with Python. Duck typing makes that all possible. Yes, but I also like interfaces (or in python: mimicked interfaces with NotImplementedError) for their clarity and documentation purposes. Would you consider the following kind of program unpythonic? class MovingObject(object): Great doc about what a moving object is def move(self): Great doc about move raise NotImplementedError() class Dog(MovingObject): def move(self): print Dog is moving class Car(MovingObject): def move(self): print Car is moving (Disclaimer: I learned OOP with Java) Fabien -- https://mail.python.org/mailman/listinfo/python-list
Re: Posting gzip'd image file - server says Malformed Upload?
On Thu, Jun 18, 2015 at 10:38 PM, random...@fastmail.us wrote: On Wed, Jun 17, 2015, at 20:23, Chris Angelico wrote: On Thu, Jun 18, 2015 at 7:55 AM, Paul Hubert phbr...@gmail.com wrote: f_in = open(dafile, 'rb') f_out = gzip.open('/Users/Paul/Desktop/scripts/pic.jpg.gz', 'wb') f_out.writelines(f_in) f_out.close() f_in.close() Are you sure you want iteration and writelines() here? I would be inclined to avoid those for any situation that isn't plain text. If the file isn't too big, I'd just read it all in a single blob and then write it all out at once. Is there a reason not to use shutil.copyfileobj? If the file is too big (or might be too big) to want to fit into memory, then sure. But a typical JPEG image isn't going to be gigabytes of content; chances are it's going to be a meg or so at most, and that doesn't justify the overhead of chunking. Just read it, write it, job done. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classic OOP in Python
python -m doctest application.py And from there, I would build up extra doc tests An extra doc test that fails #!/usr/bin/env python NewsGroup comp.lang.python Subject .. Classic OOP in Python Date . 2015-06-17 Post_By .. Steven D'Aprano Edit_By .. Stanley C. Kitching def bracket( s ) : Return string s bracketed in parentheses. bracket( Hello ) '(Hello)' bracket( Yo Mama is a Perl Monkey ) '(Yo Mama is a Java Monkey') return (%s) % s -- Stanley C. Kitching Human Being Phoenix, Arizona -- https://mail.python.org/mailman/listinfo/python-list
[issue19542] WeakValueDictionary bug in setdefault()pop()
Antoine Pitrou added the comment: Yes, we need to fix this. Sorry for being a bit slow. -- versions: +Python 3.5, Python 3.6 -Python 3.3 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19542 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Time saving tips for Pythonists
On Thursday, June 18, 2015 at 6:11:11 AM UTC-4, Productivi .co wrote: What are your best time saving tips when programming Python? PyCharm! -- https://mail.python.org/mailman/listinfo/python-list
[issue24466] extend_path explanation in documentation is ambiguous
New submission from alanf: The description of pkgutil.extend_path in the doc (e.g., https://docs.python.org/2/library/pkgutil.html , https://docs.python.org/3/library/pkgutil.html ) is so ambiguous that I had to run a test to understand its behavior. The doc says: This will add to the package’s __path__ all subdirectories of directories on sys.path named after the package. It wasn't clear to me how this should be parsed. Using parentheses to group the clauses, there's this possibility : (1) This will add to the package’s __path__ all (subdirectories of directories on sys.path) named after the package. That is, given all subdirectories of directories on sys.path, find the ones that are named after the package, and add them to the package's __path__. or: (2) This will add to the package’s __path__ all subdirectories of (directories on sys.path named after the package). That is, given all directories on sys.path that are named after the package, add all their subdirectories to the package's __path__. or: (3) This will add to the package’s __path__ all subdirectories of ((directories on sys.path) named after the package). That is, given all directories on sys.path that are named after the package, add all their subdirectories to the package's __path__. or: (4) This will add to the package’s __path__ all (subdirectories of (directories on sys.path)) named after the package. That is, given all directories on sys.path, add any of their subdirectories that are named after the package to the package's __path__. It was also unclear to me whether the subdirectories were meant to be traversed recursively. My testing indicates that (4) is the correct parse, and that the subdirectories are not meant to be traversed recursively. I suggest this wording: For each directory on sys.path that has a subdirectory that matches the package name, add the subdirectory to the package's __path__. -- assignee: docs@python components: Documentation messages: 245468 nosy: alanf, docs@python priority: normal severity: normal status: open title: extend_path explanation in documentation is ambiguous type: enhancement versions: Python 2.7, Python 3.4 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24466 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24465] Make tarfile have deterministic sorting
Sam Thursfield added the comment: Thanks for the comments! Would you be happy for the patch to be merged if it was implemented by modifying shutil.make_archive() instead? I will rework it if so. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24465 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: thinking with laziness
On Thu, 18 Jun 2015 11:10 pm, Neal Becker wrote: http://begriffs.com/posts/2015-06-17-thinking-with-laziness.html I wanted to think about that post, but I'm too lazy to read it. My-apologies-I-couldn't-resist-it-ly y'rs, -- Steven -- https://mail.python.org/mailman/listinfo/python-list
[issue19542] WeakValueDictionary bug in setdefault()pop()
Tin Tvrtković added the comment: We're actually getting bitten by this in production through the Riak Python client, so this isn't a strictly theoretical problem. -- nosy: +tinchester ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19542 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24465] Make tarfile have deterministic sorting
Raymond Hettinger added the comment: I don't see any downside for this simple patch and think there is some merit for wanting a reproducible archive. -- nosy: +rhettinger ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24465 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
executable egg?
Hi all, Here's my directory structure: myegg/ pkg1/ __init__.py ... pkg2/ __init__.py ... pkg3/ __init__.py ... setup.py I can make an egg with python setup.py bdist_egg and it works just fine. I'd like to make it executable with python myegg.egg which is supposed to be doable in 2.6+. According to everything I can find, all I need is to add myegg/ __main__.py The end result, however, is /usr/bin/python: can't find '__main__' module. It is correct: checking the egg with unzip -l shows that __main__.py is indeed not in it. So I played with options for including package data, also made a stab or two at entry_points with no luck. So, what am I missing. Or does it only work with one package in the egg? (I'm using 2.7 2.6 on centos 7 6 resp.) TIA, -- https://mail.python.org/mailman/listinfo/python-list
[issue24419] In argparse action append_const doesn't work for positional arguments
paul j3 added the comment: You can give the positional any custom name (the first parameter). You just can't reuse it (by giving 2 positionals the same name). And if you don't like what the 'help' shows, you can set the 'metavar'. That way only you see the positional's name. The name of a positional can be the 'dest' of an optional. But wouldn't that be confusing? Setting the same attribute with a required postional and one or more optional optionals? 'nargs' is another way of assigning more than one value to a Namespace attribute. You just can't put an optional between two such values. `argparse` is a parser, a way of identifying what the user gives you. It is better to err on the side of preserving information. Different argument dests does that. You can always combine values after parsing. args.foo.append(args.bar) # or .extend() args.x = [args.foo, args.bar] Don't try to force argparse to do something special when you can just as easily do that later with normal Python expressions. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24419 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19235] Add a dedicated subclass for recursion errors
Elazar Gershuni added the comment: So what holds it back now? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19235 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue23255] SimpleHTTPRequestHandler refactor for more extensible usage.
Ent added the comment: Thanks Ned Berker, I can only imagine the amount of work the core devs have to deal with. Hope my patch makes it through in next version. Regards, Ent -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue23255 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: thinking with laziness
On 18/06/2015 14:53, Steven D'Aprano wrote: On Thu, 18 Jun 2015 11:10 pm, Neal Becker wrote: http://begriffs.com/posts/2015-06-17-thinking-with-laziness.html I wanted to think about that post, but I'm too lazy to read it. My-apologies-I-couldn't-resist-it-ly y'rs, Reminds me of last night's AGM of the Apathy Society, which was an outstanding success as nobody turned up. -- 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: thinking with laziness
On Fri, Jun 19, 2015 at 2:15 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: Reminds me of last night's AGM of the Apathy Society, which was an outstanding success as nobody turned up. How do you know for sure? Nobody bothered to take minutes. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: ctypes and byte order
On 6/18/2015 5:39 AM, Jean-Michel Pichavant wrote: I'm currently writing python code that writes a small binary file to be used by another device which code is written in C. The python code runs on a little endian CPU, and unfortunately, the other device is using a big endian MIPS. The struct module is designed for this. It reads and writes packed binary data of various types and sizes in either big or little endian order. It should be easier than ctypes. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Documenting a function signature
Laura Creighton l...@openend.se writes: In a message of Thu, 18 Jun 2015 10:04:46 +1000, Ben Finney writes: Since the introduction of keyword-only arguments in Python functions, the question arises of how to communicate this in documentation. I suppose it is way too late to scream I hate keyword-only arguments! It's never too late for screams, go right ahead. If you're hoping those screams will result in the keyword-arguments not being part of Python now and in the future; yes, I think it's too late for that :-) -- \ “If sharing a thing in no way diminishes it, it is not rightly | `\ owned if it is not shared.” —Augustine of Hippo (354–430 CE) | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Python File as the Default PDF handler for Windows
On Fri, Jun 19, 2015 at 11:39 AM, MRAB pyt...@mrabarnett.plus.com wrote: I don't think it should be %s, but %*. Thanks, it's been a while since I fiddled with Windows associations. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
Am 15.06.15 um 07:15 schrieb John McKenzie: from Tkinter import * from blinkstick import blinkstick led = blinkstick.find_first() timered = 0 timeyellow = 0 timeblue = 0 colour = None root = Tk() root.title('eFlag 1') def red1(event): colour = 1 def yellow1(event): colour = 2 def blue1(event): colour = 3 root.bind_all('r', red1) root.bind_all('b', blue1) root.bind_all('y', yellow1) The nonsense starts here: === root.mainloop() while colour == None: led.pulse(red=0, green=255, blue=0, repeats=1, duration=5000, steps=50) while colour == 1: led.pulse(red=255, green=0, blue=0, repeats=1, duration=3000, steps=50) timered += 1 while colour == 2: led.pulse(red=255, green=255, blue=0, repeats=1, duration=3000, steps=50) timeyellow += 1 while colour == 3: led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000, steps=50) timeblue += 1 it seems you don't understand event based programming. root.mainloop() never exits. It waits for the user input and does the dispatching, i.e. when a key is pressed, then according to your bindings, the functions red1, yellow1, blue1 are called, which set a variable but do not do nything else. To see that, just insert a print statement into these functions: def red1(event): colour = 1 print(Red ws called) Now your job is to also do the functionality there, i.e. you have to reformulate your task (waiting for red, then blue...) as a state machine. Alternatively you can circumvent to redo the logic in a state machine by using a coroutine. You should read a text about GUI programming, or more specifically event based programming, to understand your mistake. Christian def exit_handler(): print '\033[0;41;37mRed Team:\033[0m ', timered print '\033[0;43;30mYellow Time:\033[0m ', timeyellow print '\033[0;44;37mBlue Time:\033[0m ', timeblue flog = open('flag1log.text', 'a') flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' + 'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue) + '\n') flog.close() atexit.register(exit_handler) -- https://mail.python.org/mailman/listinfo/python-list
JSON Object to CSV File Troubleshooting
Good Evening, I have a conundrum regarding JSON objects and converting them to CSV: Context I am converting XML files to a JSON object (please see snippet below) and then finally producing a CSV file. Here is a an example JSON object: PAC: { Account: [{ PC: 0, CMC: 0, WC: 0, DLA: 0, CN: null, FC: { Int32: [0, 0, 0, 0, 0] }, F: { Description: null, Code: 0 } In general, when I convert any of the files from JSON to CSV, I have been successful when using the following strategy (credit to Peter Otten): import csv import json import sys def hook(obj): return obj def flatten(obj): for k, v in obj: if isinstance(v, list): yield from flatten(v) else: yield k, v if __name__ == __main__: with open(somefileneame.json) as f: data = json.load(f, object_pairs_hook=hook) pairs = list(flatten(data)) writer = csv.writer(sys.stdout) header = writer.writerow([k for k, v in pairs]) row = writer.writerow([v for k, v in pairs]) #writer.writerows for any other iterable object However with the example JSON object (above) i receive the following error when applying this function: ValueError: too many values to unpack Here are some more samples. FC: {Int32: [0,0,0,0,0,0]} PBA: {Double: [0,0,0,0,0,0,0,0]} 3. PBDD: { DateTime: [1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM] }, In the above example, I would like to remove the keys Int32, Double and DateTime. I am wondering if there is a function or methodology that would allow me to remove such nested keys and reassign the new keys to the outer key (in this case above FC, PBA and PBDD) as column headers in a CSV and concatenate all of the values within the list (as corresponding fields). Also, here is how I strategized my XML to CSV conversion (if this is of any use): import xml.etree.cElementTree as ElementTree from xml.etree.ElementTree import XMLParser import json import csv import tokenize import token try: from collections import OrderedDict import json except ImportError: from ordereddict import OrderedDict import simplejson as json import itertools import six import string from csvkit import CSVKitWriter class XmlListConfig(list): def __init__(self, aList): for element in aList: if element: # treat like dict if len(element) == 1 or element[0].tag != element[1].tag: self.append(XmlDictConfig(element)) # treat like list elif element[0].tag == element[1].tag: self.append(XmlListConfig(element)) elif element.text: text = element.text.strip() if text: self.append(text) class XmlDictConfig(dict): ''' Example usage: tree = ElementTree.parse('your_file.xml') root = tree.getroot() xmldict = XmlDictConfig(root) Or, if you want to use an XML string: root = ElementTree.XML(xml_string) xmldict = XmlDictConfig(root) And then use xmldict for what it is..a dictionary. ''' def __init__(self, parent_element): if parent_element.items(): self.update(dict(parent_element.items())) for element in parent_element: if element: # treat like dict - we assume that if the first two tags # in a series are different, then they are all different. if len(element) == 1 or element[0].tag != element[1].tag: aDict = XmlDictConfig(element) # treat like list - we assume that if the first two tags
[issue24468] Expose compiler flag constants as code object attributes
Changes by Nick Coghlan ncogh...@gmail.com: -- dependencies: +Awaitable ABC incompatible with functools.singledispatch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24468 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24468] Expose compiler flag constants as code object attributes
New submission from Nick Coghlan: As part of the PEP 492 implementation, Yury has needed to hardcode compile flag contants in various places, with adjacent comments explaining what the magic numbers mean. It occurred to me that there's a way we could make those constants readily available to any code manipulating code objects: expose them as read-only attributes via the code object type. Does this seem like a reasonable idea? If yes, would it be reasonable to classify it as part of the PEP 492 implementation process and include it during the 3.5 beta cycle? -- messages: 245487 nosy: gvanrossum, larry, ncoghlan, yselivanov priority: normal severity: normal stage: needs patch status: open title: Expose compiler flag constants as code object attributes type: enhancement versions: Python 3.5, Python 3.6 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24468 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue23883] __all__ lists are incomplete
Jacek Kołodziej added the comment: ftplib and threading have more functions I've meant function and exceptions, of course. Sorry for the noise. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue23883 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Python File as the Default PDF handler for Windows
On Thursday, June 18, 2015 at 5:05:15 PM UTC-4, Naftali wrote: Long time lurker. I'm looking to register a python script as the default pdf reader for windows. I assume I can just register the .py in the section windows section for registering default handlers, but I'm wondering how to access the file from within the program. The issue is this: We have Java application that outputs user uploaded pdf files. It does this simply by instructing windows to open the downloaded pdf file and windows takes it from there. The data entry person will view the pdf and usually upload it into another part of the system. Problem is the second leg of the system modifies the pdf, and thus crashes when the pdf is protected against writing. Data entry make use of a program to unlock them as needed but it is an extra step and it only comes to their awareness after their client crashes on the locked pdf (because it doesn't make sense to check them proactively. I cannot change the Java system. What I want to do is write a pdf handler to handle windows open instruction. In the script I would run a command line pdf unlocker on the file and open the unlocked file with adobe (or the like). I've googled and though I get tons of 'how to open pdf from a python script' I haven't found anything describing how to write and set up my python program to deal with the pdf hand-off from the OS. Thank you, Chris. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python File as the Default PDF handler for Windows
On 2015-06-19 02:18, Chris Angelico wrote: On Fri, Jun 19, 2015 at 11:03 AM, Naftali nmichalow...@gmail.com wrote: I may be missing something in your reply, but I am *not* wondering how to associate python with the .pdf file extension. That I know how to do. What I want to know is how from within the program that I've told windows to run when the user clicks on the file --- how to access the file that the user wishes to open. Windows must somehow make that available to my program. How to I access it. Tomorrow, I'll try doing it an looping through the sys.argvs and see what's there. maybe it's a simple as passing a path into the called program. Oh! I see what you mean. You should get the full path and name of the file in sys.argv, but if you don't, I think what you need to do is add %s to the end of the association definition. My apologies for the prior misunderstanding. I don't think it should be %s, but %*. This has more details: https://technet.microsoft.com/en-us/library/bb490912.aspx -- https://mail.python.org/mailman/listinfo/python-list
[issue24468] Expose compiler flag constants as code object attributes
Nick Coghlan added the comment: In my last set of review comments on issue 24400 I suggested changing the Python level attributes for coroutine objects to cr_frame, cr_code, and cr_running. It's possible that may provide a different way to eliminate some of the current compiler flag checks. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24468 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24468] Expose compiler flag constants as code object attributes
Larry Hastings added the comment: Probably, though I want to see a sample implementation before I agree to anything. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24468 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24400] Awaitable ABC incompatible with functools.singledispatch
Nick Coghlan added the comment: In my last set of review comments, I suggested changing the Python level attributes for coroutine objects to cr_frame, cr_code, and cr_running. That reminded me that now that coroutines are their own type, we should also give them their own state introspection API, matching the API for generators: https://docs.python.org/3/library/inspect.html#current-state-of-a-generator -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24400 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue23883] __all__ lists are incomplete
Changes by Jacek Kołodziej kolodzi...@gmail.com: Added file: http://bugs.python.org/file39734/Issue23883_test_gettext.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue23883 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Python File as the Default PDF handler for Windows
On Fri, Jun 19, 2015 at 11:03 AM, Naftali nmichalow...@gmail.com wrote: I may be missing something in your reply, but I am *not* wondering how to associate python with the .pdf file extension. That I know how to do. What I want to know is how from within the program that I've told windows to run when the user clicks on the file --- how to access the file that the user wishes to open. Windows must somehow make that available to my program. How to I access it. Tomorrow, I'll try doing it an looping through the sys.argvs and see what's there. maybe it's a simple as passing a path into the called program. Oh! I see what you mean. You should get the full path and name of the file in sys.argv, but if you don't, I think what you need to do is add %s to the end of the association definition. My apologies for the prior misunderstanding. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
[issue24450] Add gi_yieldfrom calculated property to generator object
Nick Coghlan added the comment: Marking this as dependent on issue 24400, as that refactors the PEP 492 implementation to make coroutines their own type (albeit one that shares a memory layout and some attribute names with generators at the C layer). I'd suggest cr_await as the calculated property for coroutines that corresponds to gi_yieldfrom for generators. -- dependencies: +Awaitable ABC incompatible with functools.singledispatch nosy: +ncoghlan ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24450 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Why this list of dictionaries doesn't work?
On Fri, 19 Jun 2015 03:57 am, Gilcan Machado wrote: Hi, I'm trying to write a list of dictionaries like: people = ( {'name':'john', 'age':12} , {'name':'kacey', 'age':18} ) I've thought the code below would do the task. Why don't you just use exactly what you have above? Just change the round brackets (parentheses) to square brackets to change people from a tuple to a list: people = [{'name': 'john', 'age': 12}, {'name': 'kacey', 'age': 18}] and you now have a list of two dicts. But it doesn't work. What does it do? Does the computer catch fire? Blue Screen Of Death? Does Python crash, or start printing All work and no play makes Jack a dull boy? over and over again? *wink* You need to explain what you expected to happen and what actually happened, not just it doesn't work. And if I print(people) what I get is not the organize data structure like above. Remember that Python doesn't *pretty-print* lists or dicts by default. If you print people, you'll get all the information, but it may not be displayed in what you consider a particularly pleasing or organized manner: py people = [{'name': 'john', 'age': 12}, {'name': 'kacey', 'age': 18}] py print(people) [{'age': 12, 'name': 'john'}, {'age': 18, 'name': 'kacey'}] If you want it displayed as in your original sample, you will need to write your own print function. #!/usr/bin/env python from collections import defaultdict person = defaultdict(dict) people = list() person['name'] = 'jose' person['age'] = 12 people.append(person) This is a little different from what you have above. It uses a defaultdict instead of a regular dict, I presume you have some good reason for that. person['name'] = 'kacey' person['age'] = 18 This, however, if where you go wrong. You're not creating a second dict, you are modifying the existing one. When you modify a dict, you modify it everywhere it appears. So it doesn't matter whether you look at the variable person, or if you look at the list people containing that dict, you see the same value: print(person) print(people[0]) Both print the same thing, because they are the same dict (not mere copies). Another way to put it, Python does *not* copy the dict when you insert it into a list. So whether you look at people or person[0], you are looking at the same object. people.append(person) And now you append the same dict to the list, so it is in the list twice. Now you have: person people[0] people[1] being three different ways to refer to the same dict, not three different dicts. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Python File as the Default PDF handler for Windows
On Thursday, June 18, 2015 at 5:05:15 PM UTC-4, Naftali wrote: Long time lurker. I'm looking to register a python script as the default pdf reader for windows. I assume I can just register the .py in the section windows section for registering default handlers, but I'm wondering how to access the file from within the program. The issue is this: We have Java application that outputs user uploaded pdf files. It does this simply by instructing windows to open the downloaded pdf file and windows takes it from there. The data entry person will view the pdf and usually upload it into another part of the system. Problem is the second leg of the system modifies the pdf, and thus crashes when the pdf is protected against writing. Data entry make use of a program to unlock them as needed but it is an extra step and it only comes to their awareness after their client crashes on the locked pdf (because it doesn't make sense to check them proactively. I cannot change the Java system. What I want to do is write a pdf handler to handle windows open instruction. In the script I would run a command line pdf unlocker on the file and open the unlocked file with adobe (or the like). I've googled and though I get tons of 'how to open pdf from a python script' I haven't found anything describing how to write and set up my python program to deal with the pdf hand-off from the OS. Thank you for responding, Chris: I may be missing something in your reply, but I am *not* wondering how to associate python with the .pdf file extension. That I know how to do. What I want to know is how from within the program that I've told windows to run when the user clicks on the file --- how to access the file that the user wishes to open. Windows must somehow make that available to my program. How to I access it. Tomorrow, I'll try doing it an looping through the sys.argvs and see what's there. maybe it's a simple as passing a path into the called program. -- https://mail.python.org/mailman/listinfo/python-list
[issue23883] __all__ lists are incomplete
Jacek Kołodziej added the comment: Thank you for feedback, Martin. I've amended the the patch. Next, I've prepared some initial test.support.check__all__ helper, based on generalization of all previous patches. Its name/params' descriptions may be a bit rough - amendments/suggestions for such will be strongly appreciated: Issue23883_support_check__all__.patch I've added missing test.test_gettext.MiscTestCase, based on aforementioned check__all__ helper: Issue23883_test_gettext.patch I've also took the liberty of working on some more modules. These are: csv (using new helper), enum, ftplib, logging, optparse, pickletools, threading and wave: Issue23883_all.patch ftplib and threading have more functions (missing in their __all__ variables) that appear to be documented than mentioned in msg240217 - namely: * ftplib.error_temp https://docs.python.org/3/library/ftplib.html#ftplib.error_temp * ftplib.error_proto https://docs.python.org/3/library/ftplib.html#ftplib.error_proto * threading.main_thread https://docs.python.org/3/library/threading.html#threading.main_thread so I've added them as well. -- Added file: http://bugs.python.org/file39735/Issue23883_all.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue23883 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: JSON Object to CSV Question
On Wed, 17 Jun 2015 17:49:35 -0400, Saran Ahluwalia ahlusar.ahluwa...@gmail.com wrote: Good Evening Everyone: I would like to have this JSON object written out to a CSV file so that the You've already said that in another thread, and got several answers. What are you? Some kind of troll? -- Steve Hayes from Tshwane, South Africa Web: http://www.khanya.org.za/stevesig.htm Blog: http://khanya.wordpress.com E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk -- https://mail.python.org/mailman/listinfo/python-list
Re: JSON Object to CSV File Troubleshooting
On Thu, 18 Jun 2015 18:47:30 -0700 (PDT), Sahlusar ahlusar.ahluwa...@gmail.com wrote: Good Evening, I have a conundrum regarding JSON objects and converting them to CSV: That's the THIRD time you've asked this, in three separate threads. Why don't you read the answers you were given the first time? [follow-ups set] -- Steve Hayes from Tshwane, South Africa Web: http://www.khanya.org.za/stevesig.htm Blog: http://khanya.wordpress.com E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk -- https://mail.python.org/mailman/listinfo/python-list
[issue24400] Awaitable ABC incompatible with functools.singledispatch
Yury Selivanov added the comment: Another iteration of the patch is attached. Nick, I think it's ready for your review. -- stage: needs patch - patch review type: - enhancement Added file: http://bugs.python.org/file39729/corotype.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24400 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Why this list of dictionaries doesn't work?
On 2015-06-18 18:57, Gilcan Machado wrote: Hi, I'm trying to write a list of dictionaries like: people = ( {'name':'john', 'age':12} , {'name':'kacey', 'age':18} ) That's not a list; it's a tuple. If you want a list, use '[' and ']'. I've thought the code below would do the task. But it doesn't work. And if I print(people) what I get is not the organize data structure like above. Thanks of any help! []s Gilcan #!/usr/bin/env python from collections import defaultdict You don't need a defaultdict, just a normal dict. This creates an empty defaultdict whose default value is a dict: person = defaultdict(dict) people = list() This puts some items into the dict: person['name'] = 'jose' person['age'] = 12 This puts the dict into the list: people.append(person) This _reuses_ the dict and overwrites the items: person['name'] = 'kacey' person['age'] = 18 This puts the dict into the list again: people.append(person) The list 'people' now contains 2 references to the _same_ dict. for person in people: print( person['nome'] ) Initially there's no such key as 'nome' (not the spelling), so it creates one with the default value, a dict. If you print out the people list, you'll see: [defaultdict(class 'dict', {'name': 'kacey', 'age': 18, 'nome': {}}), defaultdict(class 'dict', {'name': 'kacey', 'age': 18, 'nome': {}})] -- https://mail.python.org/mailman/listinfo/python-list
[issue24429] msvcrt error when embedded
eryksun added the comment: shapely's installation instructions from windows are to use chris gohlke's prebuilt binaries from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ Christoph Gohlke's Shapely‑1.5.9‑cp27‑none‑win_amd64.whl includes a version of geos_c.dll that has the VC90 manifest embedded as resource 2, just like python27.dll. The DLL also exports a GEOSFree function, which is what shapely actually uses. That said, the geos.py module still defines a global free() using cdll.msvcrt.free. As far as I can see, it never actually calls it. Otherwise it would surely crash the process due to a heap mismatch. Steve, since you haven't closed this issue, have you considered my suggestion to export _Py_ActivateActCtx and _Py_DeactivateActCtx for use by C extensions such as _ctypes.pyd? These functions are better than manually creating a context from the manifest that's embedded in python27.dll because they use the context that was active when python27.dll was initially loaded. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24429 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: CLI Arguments That Call Functions?
On Thu, Jun 18, 2015 at 11:56 AM, Tony the Tiger tony@tiger.invalid wrote: I would have assumed there would be something built in to the ArgumentParser, but I can't detect anything that seems to do what I want, so I wrote the following: [SNIP] So, is there something already in the Python libs? Do I continue with this? Or what? There ought to be something already built in to Python, but I think I've missed it. Sure hope so. I'd hate to continue with this mess. You can specify custom actions for arguments. See https://docs.python.org/3.4/library/argparse.html#action-classes For example (untested): class AppendCallable(argparse.Action): def __call__(self, parser, namespace, values, option_string): callables = getattr(namespace, self.dest, None) or [] callables.append(functools.partial(self.const, *values)) setattr(namespace, self.dest, callables) def main(): parser = argparse.ArgumentParser() parser.add_argument( '-a', '--alfa', action=AppendCallable, const=option_alfa, dest='callables', nargs=1, type=int) parser.add_argument( '-b', '--bravo', action=AppendCallable, const=option_bravo, dest='callables', nargs=0) args = parser.parse_args() for callable in args.callables: callable() You might also be interested in reading https://docs.python.org/3.4/library/argparse.html#sub-commands in case that's related to what you're trying to accomplish. -- https://mail.python.org/mailman/listinfo/python-list
Re: CLI Arguments That Call Functions?
On 06/18/2015 12:08 PM, Tony the Tiger wrote: Forgot to add, I don't read or see anything posted from outside of the groups. Posting from the mailing list here. I assume the nntp gateway is two-way. Unless you're manually blocking message originating in google groups, I don't see why you wouldn't pick them up (bad formatting and all) on Usenet. If not, you're not missing anything, nor are we here outside of usenet. -- https://mail.python.org/mailman/listinfo/python-list
Why this list of dictionaries doesn't work?
Hi, I'm trying to write a list of dictionaries like: people = ( {'name':'john', 'age':12} , {'name':'kacey', 'age':18} ) I've thought the code below would do the task. But it doesn't work. And if I print(people) what I get is not the organize data structure like above. Thanks of any help! []s Gilcan #!/usr/bin/env python from collections import defaultdict person = defaultdict(dict) people = list() person['name'] = 'jose' person['age'] = 12 people.append(person) person['name'] = 'kacey' person['age'] = 18 people.append(person) for person in people: print( person['nome'] ) -- https://mail.python.org/mailman/listinfo/python-list
python program without stackless.run()
Hi, I could not understand how the below program executes function fun without calling stackless.run() in the program? Here fun runs as a tasklet and as per my knowledge for that stackless.run() is must. - import stackless class A: def __init__(self,name): self.name = name self.ch = stackless.channel() stackless.tasklet(self.fun)() def __call__(self,val): self.ch.send(val) def fun(self): while 1: v = self.ch.receive() print hi , v if __name__ == __main__: obj = A(sh) obj(6) - output: -- hi 6 thanks, ravi -- https://mail.python.org/mailman/listinfo/python-list
how to dump tasklets status in python
hi, I have a complex python program running 100 tasklets simultaneously. I want to take dump of all the running tasklets including their current status and back trace at the time of exception. Can any one let me know how can this be done ? Thanks, ravi -- https://mail.python.org/mailman/listinfo/python-list
[issue19235] Add a dedicated subclass for recursion errors
Elazar Gershuni added the comment: Well that's a déjà vu. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19235 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24419] In argparse action append_const doesn't work for positional arguments
py.user added the comment: paul j3 wrote: You can give the positional any custom name (the first parameter). The dest argument is not required for giving name for an optional. You can either make it automatically or set by dest, it's handy and clear. import argparse parser = argparse.ArgumentParser() _ = parser.add_argument('-a', '--aa') _ = parser.add_argument('-b', '--bb', dest='x') args = parser.parse_args([]) print(args) Namespace(aa=None, x=None) But if you do the same thing with a positional, it throws an exception. Why? (I'm a UNIX user and waiting predictable behaviour.) And the situation with another action (not only append_const, but future extensions) shows that dest may be required. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24419 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19235] Add a dedicated subclass for recursion errors
Yury Selivanov added the comment: +1. This, unfortunately, can't go in 3.5 (too late), but I can commit this in 3.6. -- assignee: - yselivanov nosy: +yselivanov versions: +Python 3.6 -Python 3.5 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19235 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: help in understanding the stackless code
yes It has instance of both Reporter and Switch. moreover I could not get why instance reporter is passed to class Switch as a parameter ? reporter = Reporter() switch = Switch(0,reporter) switch(1) thanks On Thursday, June 18, 2015 at 5:45:08 PM UTC+5:30, MRAB wrote: On 2015-06-18 08:41, ravi wrote: hi, I am new to python and need to know why the calling of switch(1) invokes the function listen twice in the below program? import stackless class EventHandler: def __init__(self,*outputs): if outputs==None: self.outputs=[] else: self.outputs=list(outputs) self.channel = stackless.channel() stackless.tasklet(self.listen)() def listen(self): print in listen()... while 1: val = self.channel.receive() self.processMessage(val) for output in self.outputs: self.notify(output) def processMessage(self,val): pass def notify(self,output): pass def registerOutput(self,output): print in registerOutput()... self.outputs.append(output) def __call__(self,val): print in __call__ ... self.channel.send(val) class Switch(EventHandler): def __init__(self,initialState=0,*outputs): EventHandler.__init__(self,*outputs) self.state = initialState def processMessage(self,val): print in processMessage() of Switch... self.state = val def notify(self,output): print in notify() of switch... output((self,self.state)) class Reporter(EventHandler): def __init__(self,msg=%(sender)s send message %(value)s): EventHandler.__init__(self) self.msg = msg def processMessage(self,msg): print in processMessage() of Reporter... sender,value=msg print self.msg % {'sender':sender,'value':value} if __name__ == __main__: reporter = Reporter() switch = Switch(0,reporter) switch(1) output: = in __call__ ... in listen()... in listen()... in processMessage() of Switch... in notify() of switch... in __call__ ... in processMessage() of Reporter... __main__.Switch instance at 0x8d822cc send message 1 Is it because EventHandler has 2 subclasses, namely Switch and Reporter, and you have an instance of each? -- https://mail.python.org/mailman/listinfo/python-list
[issue19235] Add a dedicated subclass for recursion errors
Yury Selivanov added the comment: Larry, is there any chance this can be committed in 3.5 (the change is fully backwards compatible)? -- nosy: +larry ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19235 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: thinking with laziness
On Thu, Jun 18, 2015 at 6:15 PM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 18/06/2015 14:53, Steven D'Aprano wrote: On Thu, 18 Jun 2015 11:10 pm, Neal Becker wrote: http://begriffs.com/posts/2015-06-17-thinking-with-laziness.html I wanted to think about that post, but I'm too lazy to read it. My-apologies-I-couldn't-resist-it-ly y'rs, Reminds me of last night's AGM of the Apathy Society, which was an outstanding success as nobody turned up. I thought about it, but couldn't be bothered to find the address. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why this list of dictionaries doesn't work?
On 06/18/2015 10:57 AM, Gilcan Machado wrote: Hi, I'm trying to write a list of dictionaries like: people = ( {'name':'john', 'age':12} , {'name':'kacey', 'age':18} ) I've thought the code below would do the task. But it doesn't work. Never say it doesn't work on this list. Tell us what it did, and what you expected. Provide a copy of the full error message. That's much more helpful than making us guess. And if I print(people) what I get is not the organize data structure like above. Thanks of any help! []s Gilcan #!/usr/bin/env python from collections import defaultdict person = defaultdict(dict) If you want *two* different dictionaries, you'll have to create *two* of them. You code creates only this one. people = list() person['name'] = 'jose' person['age'] = 12 people.append(person) Here's where you need to create the second one. person['name'] = 'kacey' person['age'] = 18 people.append(person) for person in people: print( person['nome'] ) Typo here: 'name', not 'nome'. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
[issue24419] In argparse action append_const doesn't work for positional arguments
paul j3 added the comment: (Important correction at the end of this post) The test that you are complaining about occurs at the start of the 'add_argument' method: def add_argument(self, *args, **kwargs): add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...) # if no positional args are supplied or only one is supplied and # it doesn't look like an option string, parse a positional # argument chars = self.prefix_chars if not args or len(args) == 1 and args[0][0] not in chars: if args and 'dest' in kwargs: raise ValueError('dest supplied twice for positional argument') kwargs = self._get_positional_kwargs(*args, **kwargs) # otherwise, we're adding an optional argument else: kwargs = self._get_optional_kwargs(*args, **kwargs) ... and the 2 methods it calls: def _get_positional_kwargs(self, dest, **kwargs): # code to deduce the 'required' parameter ... # return the keyword arguments with no option strings return dict(kwargs, dest=dest, option_strings=[]) def _get_optional_kwargs(self, *args, **kwargs): # determine short and long option strings # infer destination, '--foo-bar' - 'foo_bar' and '-x' - 'x' dest = kwargs.pop('dest', None) if dest is None: if long_option_strings: dest_option_string = long_option_strings[0] else: dest_option_string = option_strings[0] dest = dest_option_string.lstrip(self.prefix_chars) if not dest: msg = _('dest= is required for options like %r') raise ValueError(msg % option_string) dest = dest.replace('-', '_') # return the updated keyword arguments return dict(kwargs, dest=dest, option_strings=option_strings) At the 'add_argument' stage, a big difference between positionals and optionals is in how 'dest' is deduced. Note the doc string. During parsing, positionals are distinguished from optionals by the 'option_strings' attribute (empty or not). 'dest' is not used during parsing, except by the Action '__call__'. - I just thought of another way around this constraint - set 'dest' after the action is created: p=argparse.ArgumentParser() a1=p.add_argument('foo',action='append') a2=p.add_argument('bar',action='append') a1.dest='x' a2.dest='x' args=p.parse_args(['one','two']) produces Namespace(x=['one', 'two']) This works because after the action has been created, no one checks whether the 'dest' value is duplicated or even looks pretty (except when trying to format it for the help. You could also write a custom Action class, one that mangles the 'dest' to your heart's delight. The primary use of 'self.dest' is in the expression: setattr(namespace, self.dest, items) you could replace this line in the Action '__call__' with setattr(namespace, 'secret#dest', items) - I was mistaken on one thing - you can reuse positional 'names': a1=p.add_argument('foo',action='append') a2=p.add_argument('foo',action='append',type=int) p.parse_args(['a','3']) produces: Namespace(foo=['a', 3]) There is a 'name' conflict handler, but it only pays attention to the option strings (flags for optionals). You can't have two arguments using '-f' or '--foo'. But you can have 2 or more positionals with the same 'dest'. You just have to set the dest the right way. This last point renders the whole issue moot. But I'll leave it at the end to reflect my train of thought. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24419 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Python File as the Default PDF handler for Windows
Long time lurker. I'm looking to register a python script as the default pdf reader for windows. I assume I can just register the .py in the section windows section for registering default handlers, but I'm wondering how to access the file from within the program. The issue is this: We have Java application that outputs user uploaded pdf files. It does this simply by instructing windows to open the downloaded pdf file and windows takes it from there. The data entry person will view the pdf and usually upload it into another part of the system. Problem is the second leg of the system modifies the pdf, and thus crashes when the pdf is protected against writing. Data entry make use of a program to unlock them as needed but it is an extra step and it only comes to their awareness after their client crashes on the locked pdf (because it doesn't make sense to check them proactively. I cannot change the Java system. What I want to do is write a pdf handler to handle windows open instruction. In the script I would run a command line pdf unlocker on the file and open the unlocked file with adobe (or the like). I've googled and though I get tons of 'how to open pdf from a python script' I haven't found anything describing how to write and set up my python program to deal with the pdf hand-off from the OS. -- https://mail.python.org/mailman/listinfo/python-list
Re: python program without stackless.run()
On Friday, June 19, 2015 at 1:41:36 AM UTC+5:30, Ian wrote: On Thu, Jun 18, 2015 at 1:47 PM, ravi temp@gmail.com wrote: I could not understand how the below program executes function fun without calling stackless.run() in the program? Here fun runs as a tasklet and as per my knowledge for that stackless.run() is must. You seem to have a lot of questions about stackless. You might find that you get a better, more focused response if you ask your questions on the stackless mailing list: http://www.stackless.com/mailman/listinfo/stackless thanks for your pointer. I will post my queries to stackless mailing list. -- https://mail.python.org/mailman/listinfo/python-list
Reassigning keys in dictionary of lists and then writing out to CSV file?
I am currently attempting to work on converting a fairly sizeable JSON object and convert it into a CSV format. However, when I attempt to do so, using a conventional approach (that seems to work with other files). I am presented with a ValueError: too many values to unpack I have tried to flatten the JSON object using this function: # def flatten(d, parent_key=''): # items = [] # for k, v in d.items(): # try: # items.extend(flatten(v, '%s%s_' % (parent_key, k)).items()) # except AttributeError: # items.append(('%s%s' % (parent_key, k), v)) # return dict(items) However this concatenates the keys. I am now attempting to remove the nested key and reassigning to the outer key. Here are some samples. I would remove Int32, Double and DateTime. I am wondering if there is a function that would then allow me to assign the new keys as column headers in a CSV and concatenate all of the values within the list (as corresponding fields). I hope that I was clear in my description. Thank you all for your help. FC: {Int32: [0,0,0,0,0,0]} and PBA: {Double: [0,0,0,0,0,0,0,0]} and such examples: PBDD: { DateTime: [1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM, 1/1/0001 12:00:00 AM] }, -- https://mail.python.org/mailman/listinfo/python-list
[issue24429] msvcrt error when embedded
Steve Dower added the comment: Steve, since you haven't closed this issue, have you considered my suggestion to export _Py_ActivateActCtx and _Py_DeactivateActCtx for use by C extensions such as _ctypes.pyd? These functions are better than manually creating a context from the manifest that's embedded in python27.dll because they use the context that was active when python27.dll was initially loaded. I'm always fairly slow to close issues - don't read too much into that :) I don't see any value in exporting them for other C extensions, since they can also capture the initial context when they are loaded. They really need exports for Python. windll.python27._Py_ActivateActCtx would suffice and I wouldn't want to go any further than that - this is *very* advanced functionality that I would expect most people to get wrong. Someone prepare a patch. I'm not -1 yet (and of course, I'm not the sole gatekeeper here, so one of the core devs who's still working on 2.7 can fix it too). -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24429 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue24400] Awaitable ABC incompatible with functools.singledispatch
Changes by Yury Selivanov yseliva...@gmail.com: Added file: http://bugs.python.org/file39730/corotype.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24400 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Keypress Input
On 06/18/2015 01:35 PM, Oscar Benjamin wrote: I use the following. I found in testing that when you push the button it prints 'Button pressed' 10 times a second (in actual use it calls poweroff so I guess bounce isn't an issue there). Is there some reason it needs to be cleverer in this case? Yes, that would be expected, given your code has a while loop that never exits. Just curious what you expect the code to do that it's not doing. You are probably right that debouncing isn't important in your application. So just add your poweroff command after the print() statement, and break out of the loop: ... while True: time.sleep(0.1) if not GPIO.input(PIN_NUM): print('Button pressed') # run shutdown command here os.system('/usr/sbin/shutdown') break -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On Wed, 17 Jun 2015 at 02:23 Michael Torrie torr...@gmail.com wrote: On 06/16/2015 02:49 PM, Grant Edwards wrote: On 2015-06-16, John McKenzie dav...@bellaliant.net wrote: It never occurred to me something so simple as keystrokes would not be present in Python, a language rated as being terrific by everyone I know who knows it. Ah, but in reality keystrokes is not simple at all. Keyboards and input handling is a very messy, complicated area. If you do choose to go with the GPIO route, unless your code for accessing the GPIO lines does debouncing, you will have to debounce the key. There are lots of examples out there (most in C on the arduino, but still applicable). Most of them check for a button press, then do a timer count-down to let things settle out before recording a button press. So it's still complicated even if you talk directly to the buttons! No way around some complexity though. I use the following. I found in testing that when you push the button it prints 'Button pressed' 10 times a second (in actual use it calls poweroff so I guess bounce isn't an issue there). Is there some reason it needs to be cleverer in this case? #!/usr/bin/env python import RPi.GPIO as GPIO import subprocess import time PIN_NUM = 21 GPIO.setmode(GPIO.BCM) GPIO.setup(PIN_NUM, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: time.sleep(0.1) if not GPIO.input(PIN_NUM): print('Button pressed') -- Oscar -- https://mail.python.org/mailman/listinfo/python-list
[issue6839] zipfile can't extract file
Changes by Sean Goodwin sean.e.good...@gmail.com: -- nosy: +Sean Goodwin ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6839 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: python program without stackless.run()
On Thu, Jun 18, 2015 at 1:47 PM, ravi temp@gmail.com wrote: I could not understand how the below program executes function fun without calling stackless.run() in the program? Here fun runs as a tasklet and as per my knowledge for that stackless.run() is must. You seem to have a lot of questions about stackless. You might find that you get a better, more focused response if you ask your questions on the stackless mailing list: http://www.stackless.com/mailman/listinfo/stackless -- https://mail.python.org/mailman/listinfo/python-list
Re: Documenting a function signature (was: Set a flag on the function or a global?)
In a message of Thu, 18 Jun 2015 10:04:46 +1000, Ben Finney writes: Since the introduction of keyword-only arguments in Python functions, the question arises of how to communicate this in documentation. I suppose it is way too late to scream I hate keyword-only arguments! The lone asterisk showing the separation of keyword-only arguments from the rest is confusing to me. Not least because it is (if I understand correctly) invalid syntax to actually have that in Python code. Me too. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Posting gzip'd image file - server says Malformed Upload?
I got to this party late. One way to get the malformed upload message is is you gzip something that already is gzipped, and send that up the pipe. worth checking. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Hotspot Locater
yes. wifi https://wifi.readthedocs.org/en/latest/ see this answer, not raspberry pi specific http://stackoverflow.com/questions/20470626/python-script-for-raspberrypi-to-connect-wifi-automatically but is linux specific, what OS do you need? Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: help in understanding the stackless code
You need to send your message over here. http://www.stackless.com/mailman/listinfo/stackless I think I know the answer, from my work in duplicating stackless for greenlets in pypy. But that's the answer in theory. In practice, you need real stackless users. Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Classic OOP in Python
In a message of Thu, 18 Jun 2015 11:50:28 +0100, Mark Lawrence writes: Throw in http://clonedigger.sourceforge.net/ as well and you've a really awesome combination. Mark Lawrence I didn't know about that one. Hey thank you, Mark. Looks great. It needs its own entry in https://wiki.python.org/moin/PythonTestingToolsTaxonomy You add it, or me? Laura -- https://mail.python.org/mailman/listinfo/python-list
Re: Python File as the Default PDF handler for Windows
On Fri, Jun 19, 2015 at 7:04 AM, Naftali nmichalow...@gmail.com wrote: What I want to do is write a pdf handler to handle windows open instruction. In the script I would run a command line pdf unlocker on the file and open the unlocked file with adobe (or the like). I've googled and though I get tons of 'how to open pdf from a python script' I haven't found anything describing how to write and set up my python program to deal with the pdf hand-off from the OS. Possibly the reason you've found nothing is that this isn't actually a Python issue :) What you want to do is tell your OS that when you double-click on a PDF, it should run this program. That's better referred to as file associations. Different versions of Windows put that in different places, but poke around in your GUI or on the internet and you should be able to find something on updating associations. If you're having trouble getting a Python program to run in that situation, it may help to explicitly name a Python interpreter - an executable binary. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
[issue18383] test_warnings modifies warnings.filters when running with -W default
Martin Panter added the comment: FWIW there is a new message currently being triggered by test___all__. The patch here also stops this message. $ hg update 4335d898be59 $ ./python -bWall -m test test___all__ [1/1] test___all__ Warning -- warnings.filters was modified by test___all__ 1 test altered the execution environment: test___all__ -- versions: +Python 3.6 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18383 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Hotspot Locater
Hi everyone: There is interest in our group in the development of Python code to locate WiFi hotspots. My question: Is there a Python solution in the location of WiFi hotspots? Hal-- https://mail.python.org/mailman/listinfo/python-list
[issue15745] Numerous utime ns tests fail on FreeBSD w/ ZFS (update: and NetBSD w/ FFS, Solaris w/ UFS)
Martin Panter added the comment: The commit causes test_os to emit DeprecationWarning warnings, which it didn’t before: [vadmium@localhost cpython]$ hg update 4335d898be59 0 files updated, 0 files merged, 0 files removed, 0 files unresolved [vadmium@localhost cpython]$ ./python -bWdefault -m test test_os [1/1] test_os /media/disk/home/proj/python/cpython/Lib/unittest/case.py:638: DeprecationWarning: stat_float_times() is deprecated function(*args, **kwargs) [× 11 . . .] -- nosy: +vadmium ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue15745 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Get off the list
Hi, How can i get off this mailing list? Best regards / Med venlig hilsen Deogratius Musiige Software Development Engineer Sennheiser Communications A/S Industriparken 27 DK-2750 Ballerup Direct +45 5618 0320 Mail d...@senncom.com Webwww.sennheiser.com -- https://mail.python.org/mailman/listinfo/python-list
Re: JSON Object to CSV file
On Wednesday, June 17, 2015 at 2:21:05 PM UTC-4, Peter Otten wrote: Sahlusar wrote: On Wednesday, June 17, 2015 at 11:00:24 AM UTC-4, Saran A wrote: I would like to have this JSON object written out to a CSV file so that the keys are header fields (for each of the columns) and the values are values that are associated with each header field. Is there a best practice for working with this? Ideally I would like to recursively iterate through the key value pairs. Thank you in advance. I am using Python 3.4 on Windows. My editor is Sublime 2. { CF: { A: 5, FEC: 1/1/0001 12:00:00 AM, TE: null, Locator: null, Message: Transfer Fee, AT: null, FT: null, FR: True, FY: null, FR: null, FG: 0, Comment: null, FUD: null, cID: null, GEO: null, ISO: null, TRID: null, XTY: 931083, ANM: null, NM: null }, CF: Fee, ID: 2 } My apologies: I originally parsed this from an XML file. It really should be: { Fee: { A: 5, FEC: 1/1/0001 12:00:00 AM, TE: null, Locator: null, Message: Transfer Fee, AT: null, FT: null, FR: True, FY: null, FR: null, FG: 0, Comment: null, FUD: null, cID: null, GEO: null, ISO: null, TRID: null, XTY: 931083, ANM: null, NM: null }, CF: Fee, ID: 2 } The value, Fee associated with the key, CF does should not be included as a column header. The CSV file, when opened with an application such as MS Excel, should be as follows: (Column Header) CF A FEC (Field Value) Fee 51/1/0001 12:00:00 AM My apologies for an confusion. Forget about Excel, what should the CSV look like when opened in a text editor? Here's my guess: $ cat input.json { Fee: { A: 5, FEC: 1/1/0001 12:00:00 AM, TE: null, Locator: null, Message: Transfer Fee, AT: null, FT: null, FR: True, FY: null, FR: null, FG: 0, Comment: null, FUD: null, cID: null, GEO: null, ISO: null, TRID: null, XTY: 931083, ANM: null, NM: null }, CF: Fee, ID: 2 } $ cat json2csv.py import csv import json import sys def hook(obj): return obj def flatten(obj): for k, v in obj: if isinstance(v, list): yield from flatten(v) else: yield k, v if __name__ == __main__: with open(input.json) as f: data = json.load(f, object_pairs_hook=hook) pairs = list(flatten(data)) writer = csv.writer(sys.stdout) writer.writerow([k for k, v in pairs]) writer.writerow([v for k, v in pairs]) $ python3 json2csv.py A,FEC,TE,Locator,Message,AT,FT,FR,FY,FR,FG,Comment,FUD,cID,GEO,ISO,TRID,XTY,ANM,NM,CF,ID 5,1/1/0001 12:00:00 AM,,,Transfer Fee,,,True,,,0,,,931083,,,Fee,2 But do you really want duplicate column names? @Peter Otten: Thank you for your feedback. No, I do not want to have duplicates. Any thoughts on how to avoid this? -- https://mail.python.org/mailman/listinfo/python-list
JSON Object to CSV Question
Good Evening Everyone: I would like to have this JSON object written out to a CSV file so that the keys are header fields (for each of the columns) and the values are values that are associated with each header field. Is there a best practice for working with this? Ideally I would like to recursively iterate through the key value pairs. Thank you in advance. I am using Python 3.4 on Windows. My editor is Sublime 2. Here is the JSON object: { Fee: { A: 5, FEC: 1/1/0001 12:00:00 AM, TE: null, Locator: null, Message: Transfer Fee, AT: null, FT: null, FR: True, FY: null, FR: null, FG: 0, Comment: null, FUD: null, cID: null, GEO: null, ISO: null, TRID: null, XTY: 931083, ANM: null, NM: null }, CF: Fee, ID: 2 } The value, Fee associated with the key, CF should not be included as a column header (only as a value of the key CF). Other than the former, the keys should be headers and the corresponding tuples - the field values. In essence, my goal is to the following: You get a dictionary object (the outer dictionary) You get the data from the CF key (fixed name?) which is a string (Fee in your example) You use that value as a key to obtain another value from the same outer dictionary, which should be a another dictionary (the inner dictionary) You make a CSV file with: - a header that contains CF plus all keys in the inner dictionary that have an associated value - the value from key CF in the outer dictionary plus all non-null values in the inner dictionary. I have done the following: import csv import json import sys def hook(obj): return obj def flatten(obj): for k, v in obj: if isinstance(v, list): yield from flatten(v) else: yield k, v if __name__ == __main__: with open(data.json) as f: data = json.load(f, object_pairs_hook=hook) pairs = list(flatten(data)) writer = csv.writer(sys.stdout) writer.writerow([k for k, v in pairs]) writer.writerow([v for k, v in pairs]) The output is as follows: $ python3 json2csv.py A,FEC,TE,Locator,Message,AT,FT,FR,FY,FR,FG,Comment,FUD, cID,GEO,ISO,TRID,XTY,ANM,NM,CF,ID 5,1/1/0001 12:00:00 AM,,,Transfer Fee,,,True,,,0,,,931083,,,Fee,2 I do not want to have duplicate column names. Any advice on other best practices that I may utilize? -- https://mail.python.org/mailman/listinfo/python-list
Re: Get off the list
On Wednesday 17 Jun 2015 09:09 CEST, Deogratius Musiige wrote: How can i get off this mailing list? Looking at the headers: List-Unsubscribe: https://mail.python.org/mailman/options/python-list, mailto:python-list-requ...@python.org?subject=unsubscribe So I would send an email with the email account you are subscribed to the list, with the subject ‘unsubscribe’. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
[issue23255] SimpleHTTPRequestHandler refactor for more extensible usage.
Berker Peksag added the comment: Ned is correct. I started to review the patch, but couldn't find time to do a complete review. I'll take a look at it in a week or two. Thanks! -- assignee: - berker.peksag ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue23255 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Time saving tips for Pythonists
Hello Pythonists! I'm preparing an article to show up at simplilearn.com about the best time saving tips Pyhonists use, and thus, conducting interviews with Pythonists like you. The interview question I would like to ask you is: *What are your best time saving tips when programming Python?* Looking forward to your replies to this question, and will keep you updated about the article. Thanks. Abder-Rahman productivi.co *Let The Productivity Journey Begin.* -- https://mail.python.org/mailman/listinfo/python-list
Re: Get off the list
On Thursday 18 Jun 2015 09:36 CEST, Ian Kelly wrote: On Thu, Jun 18, 2015 at 1:05 AM, Cecil Westerhof ce...@decebal.nl wrote: On Wednesday 17 Jun 2015 09:09 CEST, Deogratius Musiige wrote: How can i get off this mailing list? Looking at the headers: List-Unsubscribe: https://mail.python.org/mailman/options/python-list, mailto:python-list-requ...@python.org?subject=unsubscribe So I would send an email with the email account you are subscribed to the list, with the subject ‘unsubscribe’. Not to the list. python-list and python-list-request are different addresses. Oops, I was not specific enough again. :'-( The email address was shown, but it would be very easy to overlook it. Personally though, I'd just use the web interface. That is the other option. I prefer sending an email, but for someone asking how to unsubscribe, the web interface probably is a better option. Next time I should think better about the receiver of the information. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
help in understanding the stackless code
hi, I am new to python and need to know why the calling of switch(1) invokes the function listen twice in the below program? import stackless class EventHandler: def __init__(self,*outputs): if outputs==None: self.outputs=[] else: self.outputs=list(outputs) self.channel = stackless.channel() stackless.tasklet(self.listen)() def listen(self): print in listen()... while 1: val = self.channel.receive() self.processMessage(val) for output in self.outputs: self.notify(output) def processMessage(self,val): pass def notify(self,output): pass def registerOutput(self,output): print in registerOutput()... self.outputs.append(output) def __call__(self,val): print in __call__ ... self.channel.send(val) class Switch(EventHandler): def __init__(self,initialState=0,*outputs): EventHandler.__init__(self,*outputs) self.state = initialState def processMessage(self,val): print in processMessage() of Switch... self.state = val def notify(self,output): print in notify() of switch... output((self,self.state)) class Reporter(EventHandler): def __init__(self,msg=%(sender)s send message %(value)s): EventHandler.__init__(self) self.msg = msg def processMessage(self,msg): print in processMessage() of Reporter... sender,value=msg print self.msg % {'sender':sender,'value':value} if __name__ == __main__: reporter = Reporter() switch = Switch(0,reporter) switch(1) output: = in __call__ ... in listen()... in listen()... in processMessage() of Switch... in notify() of switch... in __call__ ... in processMessage() of Reporter... __main__.Switch instance at 0x8d822cc send message 1 thanks. -- https://mail.python.org/mailman/listinfo/python-list
[issue24462] bytearray.find Buffer Over-read
DmitryJ added the comment: Quick analysis tells this can be attributed to the following code (in 2.7): https://hg.python.org/cpython/file/a8e24d776e99/Objects/stringlib/fastsearch.h#l110 https://hg.python.org/cpython/file/a8e24d776e99/Objects/stringlib/fastsearch.h#l116 Suppose i = 0, then s[i+m] causes OOB access when m=n. Note only one iteration is possible in case of m=n due to loop condition of i = (w = n-m = 0). Theoretically, one can try disclosing one adjacent byte, but more likely results are nothing (or potentially invalid match result) or a potential crash in an unlucky case of s[m] hitting an unmapped page. The same code lives in 3.2 (and likely any prior 3.x release), and 3.3 seems to be affected as well. 3.4 code has a modified version, but has the same problem (ss = s + m - 1; if (!STRINGLIB_BLOOM(mask, ss[i+1])) ...). -- nosy: +dev_zzo ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue24462 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com