Re: Please don't make unfounded legalistic demands (was: [a, b, c, d] = 1, 2, 3, 4)
- Original Message - From: Chris Angelico ros...@gmail.com Cc: python-list@python.org Sent: Wednesday, 26 August, 2015 6:11:51 PM Subject: Re: Please don't make unfounded legalistic demands (was: [a, b, c, d] = 1, 2, 3, 4) On Thu, Aug 27, 2015 at 1:09 AM, Terry Reedy tjre...@udel.edu wrote: How about instead you augment your signature with Please ignore the boilerplate below. Heh, I like this! Or: -- BOILERPLATE TROPHY COLLECTION I am a collector of stupid legal boilerplate. Here's my latest acquisition: Then let your legal guys see one of your posts. Maybe they'll relent and let you not post it any more. ChrisA I wish I could, problem is, if the mail recipient is within the company, no legal boilerplate is added making the joke fall flat. Nice suggestion though. I may send it to my IT guys though, I'm sure they'll have a good laugh :) 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: [a,b,c,d] = 1,2,3,4
- Original Message - From: Joel Goldstick joel.goldst...@gmail.com its called list unpacking or packing (?) the right side is considered a tuple because of the commas a = 1,2,3 a (1, 2, 3) a[1] 2 To add to Joel's answer, the right side can be *any* sequence, and is not restricted to lists or tuples. a, b, c = (x for x in range(3)) # a generator for instance That would be a generator unpacking combined with a tuple packing (is packing restricted to tuples and lists ? probably) 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: [a,b,c,d] = 1,2,3,4
- Original Message - From: Chris Angelico ros...@gmail.com Cc: python-list@python.org Sent: Wednesday, 26 August, 2015 3:04:05 PM Subject: Re: [a,b,c,d] = 1,2,3,4 On Wed, Aug 26, 2015 at 12:59 AM, Jean-Michel Pichavant jeanmic...@sequans.com wrote: To add to Joel's answer, the right side can be *any* sequence, and is not restricted to lists or tuples. a, b, c = (x for x in range(3)) # a generator for instance FWIW, a generator is not a sequence; this works because the right side can be any *iterable*, even more general than sequences. ChrisA Sorry about that, I've been mislead by the tutorial which uses sequence where it should have used iterable, so I though they where the same but they're not. https://docs.python.org/2/library/stdtypes.html There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects. I stand corrected. 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: Please don't make unfounded legalistic demands (was: [a, b, c, d] = 1, 2, 3, 4)
- Original Message - From: Ben Finney ben+pyt...@benfinney.id.au 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. Misleading, intimidating, hostile nonsense. If you want to participate here, please do so from a mail system which does not make these legalistic demands. I agree with you. Unfortunately my request for removing this nonsense has been denied by my employer. To the point where I'm restrincting myself from posting from time to time. I will probably restrict myself even more. 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: [a,b,c,d] = 1,2,3,4
- Original Message - From: ast nom...@invalid.com To: python-list@python.org Sent: Tuesday, 25 August, 2015 4:16:17 PM Subject: [a,b,c,d] = 1,2,3,4 [a,b,c,d] = 1,2,3,4 a 1 b 2 c 3 d 4 I have never seen this syntax before. Is it documented. Is there a name for that ? thx You probably have already seen something like: a,b,c,d = 1,2,3,4 which is the same code than yours with the list replaced by a tuple. Moreover: https://docs.python.org/2/tutorial/datastructures.html x, y, z = t This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking. It's slightly confusing because it mentions a list of variable and then a tuple packing while the example uses a tuple. Fortunately, lists and tuples can be used in both cases. 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: Best strategy for testing class and subclasses in pytest?
From: C.D. Reimer ch...@cdreimer.com Greetings, I'm writing a chess engine to learn about Python classes and inheritance, and using pytest for the unit test. [snip] I tried to create a separate class and/or module to import the common tests for each class and subclass. My attempts often ended in failure with the RuntimeError: super(): no arguments message. I couldn't find a working example on the Internet on how to do that. The pytest documentation is all over the place. Is there a way to reuse tests in pytest? Or should I test everything in the class and test only the implemented functionality in the subclasses? Thank you, Chris R. I've played a little bit with pytest, I was interested in trying since it claims to add less boilerplate than unittest. I've created 2 classes, Piece and Queen, both have the 'isPiece' and 'name' property (for the sake of demo). If you execute the code (python 2.7) with pytest, you'll see that the TestQueen class actually execute 2 tests, one inherited from its base test class TestPiece. So in the end, I'd say that you may put all common tests in TestPiece, and each specific implementation into TestQueen. import pytest class Piece(object): @property def isPiece(self): #for the sake of demo return True @property def name(self): raise NotImplementedError # Piece is a sort of abstract class class Queen(Piece): @property def name(self): return 'Queen' class TestPiece(object): cls = Piece def test_isPiece(self): assert self.cls().isPiece def test_name(self): with pytest.raises(NotImplementedError): assert self.cls().name class TestQueen(TestPiece): cls = Queen def test_name(self): assert self.cls().name == 'Queen' py.test test.py platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2 4 passed in 0.01 seconds -- 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: Most Pythonic way to store (small) configuration
- Original Message - From: Cecil Westerhof ce...@decebal.nl To: python-list@python.org Sent: Sunday, 2 August, 2015 12:11:28 PM Subject: Most Pythonic way to store (small) configuration There are a lot of ways to store configuration information: - conf file - xml file - database - json file - and possible a lot of other ways I want to write a Python program to display cleaned log files. I do not think I need a lot of configuration to be stored: - some things relating to the GUI - default behaviour - default directory - log files to display, including some info - At least until where it was displayed Because of this I think a human readable file would be best. Personally I do not find XML very readable. So a conf or json file looks the most promising to me. And I would have a slight preference for a json file. Any comments, thoughts or tips? -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list Did you consider using serpent ? It's a python serializer than can produce human readable text format. If your configuration is a dictionary for instance, there's possibly no work to do. see for yourself at : https://pypi.python.org/pypi/serpent Regards, 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: Python 3 May Become Relevant Now
- Original Message - From: Mark Lawrence breamore...@yahoo.co.uk To: python-list@python.org Sent: Monday, 3 August, 2015 2:25:08 AM Subject: Python 3 May Become Relevant Now rr should have a field day with this one http://nafiulis.me/python-3-may-become-relevant-now.html -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence The problem was with a function (buried deep in the source code as one of many decorators) that usually returned a list but under a certain circumstances, it returned None [...] I'm not saying that the person who originally wrote the code is a bad programmer. I'll leave that up to you. What I am saying is that python allows you to make such silly mistakes. I do this all the time ... :( Well not exactly, with lists I'm trying to return an empty list but I may return None in certain situations, most of the time when a method cannot do its job because of missing data but this particular method does not know if it's expected or not, so it returns None like to tell the caller, can't do it, deal with it. I really prefer to handle errors with a : if foo() is not None: ... than a try expect stupid block. But if I get things right, with python 3.5 type hint checker, I'd be screwed, as it is spefificaly designed to track this kind of problem. What's the use of None then ? Any method returning None can only return None or suffer the type checker retribution. I don't get it. 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: Optimal solution for coloring logging output
Original Message - From: c buhtz c.bu...@posteo.jp To: python-list@python.org Sent: Monday, 3 August, 2015 11:13:37 AM Subject: Optimal solution for coloring logging output I don't want to ask how to do this because there are so many solutions about it. http://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output There are so much different and part of unpythontic solutions I can not decide myself. What do you (as real pythontics) think about that. Which of the solutions fit to concepts of Python and its logging package? Coloring means here not only the message itself. The (levelname) should be included in the coloring. For myself coloring the (levelname) would be enough to avoid to much color in the output. 1. The solution itself shouldn't care about plattform differences because there are still some packages which are able to offer plattform-independent console-coloring. Which would you prefere? ;) 2. Some solutions derive from StreamHandler or much more bad hacking the emit() function. I think both of them are not responsible for how the output should look or be presented. 3. How to present the output is IMO the responsibility of a Formater, isn't it? So I should derive from the Formater. What do you as Pythonics think of that? ;) This is more or less how it could be done: 1/ use the module curses to get terminal colors (the doc suggests to use the Console moduel on windows) 2/ write a logging Formatter that will replace DEBUG/INFO/ERROR message by their colored version. import curses import logging import string import re curses.setupterm() class ColorFormat: #{ Foregroung colors BLACK = curses.tparm(curses.tigetstr('setaf'), curses.COLOR_BLACK) RED = curses.tparm(curses.tigetstr('setaf'), curses.COLOR_RED) GREEN = curses.tparm(curses.tigetstr('setaf'), curses.COLOR_GREEN) YELLOW = curses.tparm(curses.tigetstr('setaf'), curses.COLOR_YELLOW) BLUE = curses.tparm(curses.tigetstr('setaf'), curses.COLOR_BLUE) MAGENTA = curses.tparm(curses.tigetstr('setaf'), curses.COLOR_MAGENTA) CYAN = curses.tparm(curses.tigetstr('setaf'), curses.COLOR_CYAN) WHITE = curses.tparm(curses.tigetstr('setaf'), 9) # default white is 7, the 9 is a better white #{ Backgrounds colors BG_BLACK = curses.tparm(curses.tigetstr('setab'), curses.COLOR_BLACK) BG_RED = curses.tparm(curses.tigetstr('setab'), curses.COLOR_RED) BG_GREEN = curses.tparm(curses.tigetstr('setab'), curses.COLOR_GREEN) BG_YELLOW = curses.tparm(curses.tigetstr('setab'), curses.COLOR_YELLOW) BG_BLUE = curses.tparm(curses.tigetstr('setab'), curses.COLOR_BLUE) BG_MAGENTA = curses.tparm(curses.tigetstr('setab'), curses.COLOR_MAGENTA) BG_CYAN = curses.tparm(curses.tigetstr('setab'), curses.COLOR_CYAN) BG_WHITE = curses.tparm(curses.tigetstr('setab'), curses.COLOR_WHITE) #{ Format codes BOLD = curses.tparm(curses.tigetstr('bold'), curses.A_BOLD) UNDERLINE = curses.tparm(curses.tigetstr('smul'), curses.A_UNDERLINE) BLINK = curses.tparm(curses.tigetstr('blink'), curses.A_BLINK) NO_FORMAT = curses.tparm(curses.tigetstr('sgr0'), curses.A_NORMAL) NO_COLOR = curses.tigetstr('sgr0') #} def setFormat(attributeList): _set = '' # avoid collision with the builtin set type for attribute in attributeList: _set += getattr(ColorFormat, attribute, '') return _set class ColorFormatter(logging.Formatter): def format(self, record): parameters = record.__dict__.copy() parameters['message'] = record.getMessage() # -- # Log Level Format : %(levelname) # -- fmt = self._fmt pattern = r'(%\(levelname\)(?:-?\d+)?s)' if record.levelno = logging.DEBUG: fmt = re.sub(pattern, setFormat(['BLUE']) + r'\1' + setFormat(['NO_COLOR']), fmt) elif record.levelno = logging.INFO: fmt = re.sub(pattern, setFormat(['CYAN']) + r'\1' + setFormat(['NO_COLOR']), fmt) elif record.levelno = logging.WARNING: fmt = re.sub(pattern, setFormat(['MAGENTA']) + r'\1' + setFormat(['NO_COLOR']), fmt) elif record.levelno = logging.ERROR: fmt = re.sub(pattern, setFormat(['RED','BOLD']) + r'\1' + setFormat(['NO_COLOR']), fmt) else: fmt =
Re: line error on no. 7
- Original Message - From: ltc hotspot ltc.hots...@gmail.com To: python-list@python.org Python-list@python.org Sent: Tuesday, 28 July, 2015 10:21:59 PM Subject: line error on no. 7 Hi Everyone, I'm writing python code to read a data text file, split the file into a list of words using the split(function) and to print the results in alphabetical order. The raw python code is located at http://tinyurl.com/oua9uqx The sample data is located at http://tinyurl.com/odt9nhe Desired Output: ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder'] There is a line error on no. 7 What is the cause of this error? Regards, Hal Sent from Surface Hi, It's better to post the code with your question. Python 2.7 fname = raw_input(Enter file name: ) fh = open(fname) lst = list() for line in fh: if fh == list: continue list.split() list.append sorted(fh) print line.rstrip() The main issue is that you've misspelled 'lst' in the for loop. You've used 'list' instead. 'list' is a built-in constructor for lists. You cannot split it. I'm also not sure what if fh == list:continue is supposed to achieve. Try the following untested code: words = [] for line in open(fname): # what if fname does not exist ? words.extend(line.split()) print sorted(words) Regards, 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 Command Question
- Original Message - From: ltc hotspot ltc.hots...@gmail.com To: python-list@python.org Python-list@python.org Sent: Tuesday, 28 July, 2015 6:59:13 PM Subject: Help Command Question Hi Everyone, I'm trying to print a command of list options by using the help command in the iPython interpreter. Read captured copy of the printout as follows: 'Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v. 1500 64 bit (AMD64)] Type copyright, credits or license for more information. IPython 3.2.0 -- An enhanced Interactive Python. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org In [1]: help list File ipython-input-1-823a3ff84bc4, line 1 help list ^ SyntaxError: invalid syntax.' Question: What is the correct help command? Regards, Hal These are very basic questions for which you can find the answer with google. Did you check the ipython documentation ? Anyway, help(list) or list? are what you're looking for. 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: Noob in Python. Problem with fairly simple test case
- Original Message - From: Steven D'Aprano st...@pearwood.info 75% or 90% is not a vast majority. Vast majority implies more than 99%. You could not be more wrong. More than 99% is a stupendous majority, while within 95 to 99% is a tremendous majority. From the official Majority rating 2015 edition, a vast majority would be between 87 and 87.6%. Of course this is only valid in the northern hemisphere (my apologies for stating the obvious). 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: Python File as the Default PDF handler for Windows
Just to update, you are correct, Chris, the file short name is passed into sys.argv. didn't need to add anything to the path. But a gotcha -- Windows didn't like my .py, clicking on the pdf causes Windows to complain about 'file x' is not a valid windows executable. I'm not an expert of windows but you probably need to specify the python interpreter, not the script itself. something like C:\Python2.7\python.exe yourscript.py %* in the windows file association panel. 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: ctypes and byte order
- Original Message - From: Terry Reedy tjre...@udel.edu To: python-list@python.org Sent: Thursday, 18 June, 2015 7:02:16 PM Subject: 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 Yep, I knew about struct but I did go for ctypes because... I wanted to try it and thought it would be a suitable solution (with more capabilities). Looks like I fooled myself (not in the way ctypes is badly designed, it's just not what I needed). Now I'm left with a dilemma: My current ctypes code is working (thanks Peter !), but the code is rather cumbersome. 1/ don't change it, and wish good luck to my next co-worker looking at the code 2/ rewrite everything with struct 3/ rewrite everything with cffi (Laura's suggestion) which has the awsomeness to suppport C code copy/paste. It's still a C Foreign Function Interface like ctypes and could be overkill We all know how this ends up... 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: Catching exceptions with multi-processing
- Original Message - From: Oscar Benjamin oscar.j.benja...@gmail.com A simple way to approach this could be something like: #!/usr/bin/env python3 import math import multiprocessing def sqrt(x): if x 0: return 'error', x else: return 'success', math.sqrt(x) if __name__ == __main__: numbers = [1, 2, 3, -1, -3] pool = multiprocessing.Pool() for ret, val in pool.imap(sqrt, numbers): if ret == 'error': raise ValueError(val) print(val) Just replace the raise statement with whatever you want to do (write to a file etc). Since all errors are handled in the master process there are no issues with writing to a file. -- Oscar The main problem with this approach is that it does not handle unexpected exceptions within subprocesses. 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: Catching exceptions with multi-processing
- Original Message - From: Fabien fabien.mauss...@gmail.com To: python-list@python.org Sent: Friday, 19 June, 2015 4:01:02 PM Subject: Catching exceptions with multi-processing Folks, I am developing a tool which works on individual entities (glaciers) and do a lot of operations on them. There are many tasks to do, one after each other, and each task follows the same interface: def task_1(path_to_glacier_dir): open file1 in path_to_glacier_dir do stuff if dont_work: raise RuntimeError(didnt work) write file2 in path_to_glacier_dir This way, the tasks can be run in parallel very easily: import multiprocessing as mp pool = mp.Pool(4) dirs = [list_of_dirs] pool.map(task1, dirs, chunksize=1) pool.map(task2, dirs, chunksize=1) pool.map(task3, dirs, chunksize=1) ... and so forth. I tested the tool for about a hundred glaciers but now it has to run for thousands of them. There are going to be errors, some of them are even expected for special outliers. What I would like the tool to do is that in case of error, it writes the identifier of the problematic glacier somewhere, the error encountered and more info if possible. Because of multiprocessing, I can't write in a shared file, so I thought that the individual processes should write a unique error file in a dedicated directory. What I don't know how to, however, is how to do this at minimal cost and in a generic way for all tasks. Also, the task2 should not be run if task1 threw an error. Sometimes (for debugging), I'd rather keep the normal behavior of raising an error and stopping the program. Do I have to wrap all tasks with a try: exept: block? How to switch between behaviors? All the solutions I could think about look quite ugly to me. And it seems that this is a general problem that someone cleverer than me had solved before ;-) Thanks, Fabien https://azylstra.net/blog/post/exception-handling-with-python-processes shows how subprocesses can send their exception to the main process. -- 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: 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
ctypes and byte order
Hi list, 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. My problem is the following: I cannot make an array of n int work in big endian, I can workaround the problem by creating n intergers, which is nicely done thanks to list comprehension but that seems to me like a misuse of the ctypes modules. ctypes is expecting a 'c_uint_be_Array_5' (note the _be_ for big endian), and I don't know how to construct such object. I hope I am clear. Thanks, JM here's a code sample (python 2.7): import ctypes, sys iarray = ctypes.c_uint32*5 # array of 5 unsigned 32 bits class Foo(ctypes.Structure): Native byte order, won't work on my big endian device _fields_ = [('bar', iarray)] class Foo_be(ctypes.BigEndianStructure): big endian version, but python code fails _fields_ = [('bar', iarray)] class Foo_be_working(ctypes.BigEndianStructure): Working big endian version, looks more like a workaround. _fields_ = [('bar%i'%i, ctypes.c_uint32) for i in range(5)] print sys.version f = Foo(iarray(0,1,2,3,4)) print uint32 array: , f.bar f_be = Foo_be_working(0,1,2,3,4) print bar0 and bar5: , f_be.bar0, f_be.bar5 f_be = Foo_be(iarray(0,1,2,3,4)) # will raise an exception The output 2.7.3 (default, Mar 13 2014, 11:03:55) [GCC 4.7.2] uint32 array: __main__.c_uint_Array_5 object at 0x1cf4560 bar0 and bar4: 0 4 TypeError: incompatible types, c_uint_Array_5 instance instead of c_uint_be_Array_5 instance 24 --- 25 f_be = Foo_be(iarray(0,1,2,3,4)) 26 -- 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: for...else
- Original Message - From: acdr mail.a...@gmail.com To: Jean-Michel Pichavant jeanmic...@sequans.com Cc: python-list@python.org Sent: Tuesday, 2 June, 2015 2:52:21 PM Subject: Re: for...else That would work for my example, but it would only really work if all the calculations are in a nice function. You cannot blame me for considering the example you provided ;) What about this: class Cleanup(Exception): pass try: for x in it: if c1(): raise Cleanup() c2() if c3(): raise Cleanup() except Cleanup: #do the cleanup pass If you can make c1 c3 raise themselves Cleanup, it's even better. Now if you're able to write a cleanup function that can handle the case when there's nothing to clean, everything becomes crystal clear: from contextlib import contextmanager @contextmanager def cleanup(): yield # here do the cleaning print 'I am cleaning' def do_the_job(): if c1() : return c2() if c3() : return with cleanup(): do_the_job() 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: for...else
- Original Message - From: acdr mail.a...@gmail.com To: python-list@python.org Sent: Tuesday, 2 June, 2015 1:26:42 PM Subject: for...else Hi, Currently, in various places in my code, I have the equivalent of: for x in it: if complicated_calculation_1(): cleanup() break complicated_calculation_2() if complicated_calculation_3(): cleanup() break Hi With the following layout, adding calculation steps is just a matter of adding a line for x ion it: for calc, cbk in [ (complicated_calculation_1, cleanup), (complicated_calculation_2, None), (complicated_calculation_3, cleanup), ]: if calc() and cbk: cbk() break It might give you ideas. 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: for...else
- Original Message - From: acdr mail.a...@gmail.com To: Jean-Michel Pichavant jeanmic...@sequans.com Cc: python-list@python.org Sent: Tuesday, 2 June, 2015 4:00:12 PM Subject: Re: for...else The first solution in your e-mail (with a Cleanup exception) is definitely very close, functionally, to what I want to accomplish. In effect, it's the same structure as my original suggestion of for...then...else, except now it'd be try: for...else...except. That's workable. I can even cheat and rename the Cleanup class to Break for clarity. I'm guessing that there is not much support for functionality like this to be built in, in a much less verbose manner, like the for...else functionality? :P By the way please don't top post in this list. You're right the first solution is not that helpfull. I quite dislike try blocks. But I dislike for else even more. While if else is a correct english construct and means something, for else is not (correct me if I'm wrong). for else works perfectly, I just can never remember on which condition the else block is processed. 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: May I drop list bracket from list?
- Original Message - From: Peter Otten __pete...@web.de To: python-list@python.org Sent: Thursday, 23 April, 2015 12:26:41 PM Subject: Re: May I drop list bracket from list? subhabrata.bane...@gmail.com wrote: Dear Group, list1=[] for file in list_of_files: print file fread1=open(file,r).read() fword=fread1.split() list1.append(fword) Here the list is a list of lists, but I want only one list not list of lists. There is also a dedicated extend() method that takes a list (actually an iterable) and appends all items in that list: list1.extend(fword) If both list1 and fword are lists, you can also write list1 = list1 + fword or list1 += fword 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: A question on the creation of list of lists
- Original Message - From: subhabrata banerji subhabrata.bane...@gmail.com To: python-list@python.org Sent: Wednesday, 22 April, 2015 6:18:30 PM Subject: A question on the creation of list of lists Dear Group, I am trying to open a bunch of files from a directory and trying to put the results in list of lists that is to say, that is to say, I have a list of file names of a directory, I want to read each one of them. After reading each one of them, I want to put the results of each file in a list. These lists would again be inserted to create a list of lists. to do this I am trying to write it as follows: list_of_files = glob.glob('C:\Python27\*.*') print list_of_files list1=[] list2=[] list_N=[list1,list2] for i,j in zip(list_of_files,list_N): print i,j x1=open(i,r).read() x2=j.append(x1) all_sent=list_N print all_sent Am I doing anything wrong? If any one may kindly suggest? Is there any smarter way to do it? I am using Python2.7+ on MS-Windows 7 Professional Edition. Apology for any indentation error. Regards, Subhabrata Banerjee. I'm not sure about what you're trying to do. But here are a couple of remarks: 1/ Your file pattern search will not get files that do not have any dot in their name or will get directory that have a dot in their name. Here's a better way of filtering files: import glob import os filenames = [item for item in glob.glob('C:\Python27\*') if os.path.isfile(item)] 2/ the append method returns always None x2=j.append(x1) will bind x2 to None. That is probably something you don't want. However you never use x2, so you can simply write: j.append(x1) 3/ your for loop seems broken, but I'm not sure as I don't really know what you're trying to do. Here's a simple code that you may start from: filenames = [item for item in glob.glob('C:\Python27\*') if os.path.isfile(item)] content = [] for filename in filenames: with open(filename, 'r') as f: content.append(f.read()) all_sent = [filenames, content] You should end up with a list of list, the first list is the file names, the second their content: with 2 files file1 file2 you should get all_sent : [['file1', 'file2'], [content1, content2]] Is it what you're trying to do ? 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: Code critique please
- Original Message - From: kai peters kai.pet...@gmail.com To: python-list@python.org Sent: Wednesday, 8 April, 2015 12:43:23 AM Subject: Code critique please I just wrote this bit (coming from Pascal) and am wondering how seasoned Python programmers would have done the same? Anything terribly non-python? As always, thanks for all input. K Creates a PNG image from EPD file import os, sys from PIL import Image, ImageFont, ImageDraw # - def RenderByte(draw, byte, x, y): blist = list(bin(byte).lstrip('0b')) # turn byte into list with 8 elements, c = 0# each representing one bit for bit in blist: if bit: draw.point((x + c, y), fcolor) c += 1 return # Apart from what has been already said, you could rewrite your function RenderByte this way (untested): def render_byte(draw, byte, x, y): for point in [(x+c, y) for (c, bit) in enumerate(bin(byte)[2:]) if int(bit)]: draw.point(point, fcolor) it involves important notions in the python language: - list comprehension, this is the [...] part, where it combines filtering a list and applying a function to the values - slicing, bin(byte)[2:] returning the sequence stripped from its 2 first elements Additional remarks : - is fcolor defined ? - your test if bit: was probably wrong as it was testing either 0 or 1 which are both evaluated to True. In other words, bool(0) == True, bool(0) == False Cheers, 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: A simple single line, triple-quoted comment is giving syntax error. Why?
- Original Message - From: Terry Reedy tjre...@udel.edu To: python-list@python.org Sent: Wednesday, 18 March, 2015 10:47:40 PM Subject: Re: A simple single line, triple-quoted comment is giving syntax error. Why? On 3/18/2015 3:53 PM, Thomas 'PointedEars' Lahn wrote: I must strongly object and recommend against getting accustomed to the suggested use of multi-line string literals. I agree. I remember loosing a lot of time finding a bug that can be summarized like this (immagine a much larger list where the temptation of commenting a block is high): a = [ '1', '''shorten the list to speedup tests '2', '3', ''' '4', ] print a ['1', shorten the list to speedup tests\n\t\t'2',\n\t\t'3',\n4] 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: Logging Custom Levels?
- Original Message - From: Didymus lynt...@gmail.com To: python-list@python.org Sent: Tuesday, 31 March, 2015 5:20:52 PM Subject: Logging Custom Levels? Hi, I've create a Python file called log.py and placed in the custom levels: # Performance Debug... logging.addLevelName(PDEBUG_NUM, PDEBUG) def pdebug(self, message, *args, **kws): Performance Debug Message Level self.log(PDEBUG_NUM, message, *args, **kws) logging.Logger.pdebug = pdebug This works except that the %(module) and %(lineno) does not print properly, it instead prints out as the log.py and the line that this is on. I think I figured out a way to get the module and line from the calling custom level: import inspect frame = inspect.currentframe() filename = os.path.splitext(os.path.basename(frame.f_back.f_code.co_filename))[0] linenumber = frame.f_back.f_lineno My question is how do I pass this into the self.log call properly? I've tried a few different things without any luck. Any ideas how I can pass this into the custom logging level and get it to work? Thanks in Advance for any help! Tom A solution is pretty simple, do not use an intermediate log function pdebug. import logging PDEBUG_NUM=20 logging.addLevelName(PDEBUG_NUM, PDEBUG) logger = logging.getLogger('foo') logging.basicConfig(level=logging.DEBUG, format='%(message)s %(lineno)d') logger.log(PDEBUG_NUM, 'This will work :') If you *really* want to go for the hackish way, forget about the inspect module, the following pdebug function should do the trick: def pdebug(self, message, *args, **kws): if self.isEnabledFor(PDEBUG_NUM): self._log(PDEBUG_NUM, message, args, **kws) Cheers, 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: How to Mock a mongodb
- Original Message - From: Xavier Pegenaute xpegena...@poblenousensefils.net To: python-list@python.org Sent: Saturday, 7 February, 2015 11:09:10 PM Subject: How to Mock a mongodb Dear, I am trying to mock the use of a mongo db and I am having some trouble. Appears that I am not able to return a desired value from mongo.find().count(). I made a proof of concept to try to reduce complexity of the real problem. You can find the code which is going to be tested in [1], and the code of the test case in [2]. Do you know exactly wat's wrong with it?, or may you point me to some direction? Thanks, Xavi You've mocked the pymongo.cursor but since you've mocked the entire mongo client, this mocked client will never return a pymongo.cursor, it will return only mock objects. What you can do is mock the entire chain call of you mocked client: from mock import patch from mmongo import MongoHelper class TestMongoHelper(object): @patch(mmongo.pymongo) def test_count_data(self, fake_mongo_client): mhelper = MongoHelper() # mock self.db[MongoHelper.db_name][MongoHelper.coll_name].find().count() fake_mongo_client.__getitem__.return_value.__getitem__.return_value.find.return_value.count.return_value = 5 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: Is there a more elegant way to spell this?
- Original Message - From: Neal Becker ndbeck...@gmail.com To: python-list@python.org Sent: Tuesday, 27 January, 2015 2:15:12 PM Subject: Is there a more elegant way to spell this? Is there a more elegant way to spell this? for x in [_ for _ in seq if some_predicate]: You could use a generator expression for x in (_ for _ in seq if some_predicate): This is very similar but it prevents python from creating a new list. 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: class-based class decorator
- Original Message - From: Albert-Jan Roskam fo...@yahoo.com From: Jean-Michel Pichavant jeanmic...@sequans.com I don't really understand how you successfuly manage positional parameters, since the caller may not name them. I'm asking because if your intend to check only the keyword parameters, there's a much simplier solution. JM Hi, Can you give an example of where/how my code would fail? I do not intend to use *args and **kwargs, if that is what you mean. I am interested in hearing a simpler approach, especially if it would also solve the messed-up-signature problem that I mentioned. Thank you! Albert-Jan In the example you've given you've deprecated only keyword arguments. So I was wondering... would the following *untested* code work ? : def check_deprecated_args(deprecated): def decorator(func): def inner(*args, **kwargs): for p in deprecated: if p in kwargs: print '%s is deprecated' % p return func(*args, **kwargs) return inner return decorator 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: class-based class decorator
- Original Message - From: Albert-Jan Roskam fo...@yahoo.com.dmarc.invalid import functools import inspect import warnings warnings.simplefilter(always) class check_deprecated_args(object): def __init__(self, deprecated_params, msg=None): self.deprecated_params = deprecated_params self.msg = msg def __call__(self, func): @functools.wraps(func) def inner(*args, **kwargs): argspec = inspect.getargspec(func) default_signature = dict(zip(argspec.args[1:], argspec.defaults)) callargs = inspect.getcallargs(func, *args, **kwargs) deprecated_calls = [(p, a) for p, a in callargs.items() if p in self.deprecated_params and a != default_signature[p]] for (param, arg) in deprecated_calls: msg = you're using obsolete parameters in %s: [%s:%s] msg = msg % (func.__name__, param, arg) msg = msg + + self.msg if self.msg else msg warnings.warn(msg, DeprecationWarning, stacklevel=2) return func(*args, **kwargs) functools.update_wrapper(inner, func) return inner if __name__ == __main__: class Foo(object): @check_deprecated_args([old, older], use 'brand_new' param instead) def __init__(self, old=old, older=ancient): print hello @check_deprecated_args(deprecated_params=[old, older]) def bar(self, old=default): print world f = Foo(old=old, older=dino era) f.bar(gnarly) help(f) # now the signature is *args, **kwargs, which makes my Sphinx documentation less readable! Best wishes, Albert-Jan I don't really understand how you successfuly manage positional parameters, since the caller may not name them. I'm asking because if your intend to check only the keyword parameters, there's a much simplier solution. 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: newbie: installing setuptools
- Original Message - From: Surbhi Gupta surbhi.2...@gmail.com OK, the problem is now resolved: I just found out that we need to install from prompt instead of IDLE. Setuptools is installed, but I am not able to use easy_install from prompt. It says: easy_install : The term 'easy_install' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + easy_install + + CategoryInfo : ObjectNotFound: (easy_install:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException still unsuccessful in installing Scipy. Assuming you are using windows, you must first install setuptools using the binary you'll find on the internet. Then you must add some path(s) to your PATH environment variable, something to change in the window configuration menu. Probably something in C:\Python2.7\scripts, I can't remember. full doc: https://docs.python.org/2/using/windows.html 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: How to detect that a function argument is the default one
- Original Message - From: Chris Angelico ros...@gmail.com c1 = Circle((0,0), 10, None) print c1.mass 20 c1.radius = 20 print c1.mass 40 I think that juust might count as scope creep :) ChrisA Here you go :p c1 = Circle((0,0), 10, None) print c1.mass 20 c1.grow(+10) print c1.mass 40 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: How to detect that a function argument is the default one
- Original Message - From: ast nom...@invalid.com Note : what is the mass of a circle ? In fact it's a ball moving in a plan. I will change that name. I would advise to remove the the mass parameter of your Sphere initialization. It could be inconsistent with the radius. To compute the mass you would need the radius and the volumetric mass density. pseudo code: class Sphere(object): def __init__(self, center, radius, density): @property def volume(self): return 4/3.*pi*self.radius^3 @property def mass(self): return self.volume*self.density You'll find no the net the density for most of the materials. 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: How to detect that a function argument is the default one
- Original Message - From: ast nom...@invalid.com I have the idea to write: def __init__(center=(0,0), radius=10, mass=None)): if mass == None: self.mass = radius**2 else: self.mass = mass but maybe Python provides something clever. Thx If you like one-liners, def __init__(self, center=(0,0), radius=10, mass=None): self.center = center self.radius = radius self.mass = (mass is None and radius**2) or mass But there's an issue with that solution: self.mass being computed during the instance initialization, what if radius is changing ? c1 = Circle((0,0), 10, None) print c1.mass 20 c1.radius = 20 print c1.mass 20 # that is unexpected Everytime an attribute is computed from another attribute, it should ring a python bell : property def __init__(self, center, radius, mass): self.center = center self.radius = radius self._mass = mass @property def mass(self): return self._mass if self._mass is not None else self.radius*2 c1 = Circle((0,0), 10, None) print c1.mass 20 c1.radius = 20 print c1.mass 40 JM Note : what is the mass of a circle ? -- 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: serial data and web
- Original Message - From: manduk nas...@nospamxxx.it A web page? Did you mean a Web server? not only upload in a folder of a webserver...I wish to see in real time the datas in a public html page. I get the data from serial port and then I put them in a remote page. Which is the best way to transfer datas from a text file for example and send it on web? One simple solution : Use flask http://flask.pocoo.org/ You'll be able to create a web app very quickly. Accessing a serial port from that app and update the html will be easy. For this solution to work, the machine accessing the serial port and the machine serving the html pages is the same. If you need your html pages to be served by another machine, you can implement the html POST/GET requests (see the flask doc). 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: Maintaining Maximum Line Length When Using Tabs Instead of Spaces?
- Original Message - From: Aahan Krish kr...@aahan.me To: python-list@python.org Sent: Monday, 8 December, 2014 3:15:43 AM Subject: Maintaining Maximum Line Length When Using Tabs Instead of Spaces? My understanding from talking to different people is that many do use tabs (instead of spaces) for indentation in their code. My question is to them (because I want to use tabs too) is: how do you maintain a line-length of 79 characters? E.g. scenario: The tab setting in your editor could be 2 or 4, and in other developer's browser it could be 8. The code will be longer than 79 chars in the latter's editor. I want to know if it's at all possible or if you use some simple and realistic (practical) hacks. *PS: Please avoid, That's why you should use spaces, type of comments. I would like to avoid flame wars.* TY, Aahan You simply need to define the standard width for you tab display. 4 is very common. Those in your team who want to use a different display (3 flowers for instance) can, but they'll have to deal with the 79 limit by themselves which can be tricky. Note that the 79 limit is a legacy value from the time where code was developed in 80 characters terminals with names not exceeding 8 characters (by convention). Given the number of monitors you have and their width, you may extend this limit. For instance, I can easily make a 3 files merge with 160 chars per line without problem. Considering the current state of most developer hardware, a limit around 100 char per line is most of the time a better choice. Remember that breaking a line of 81 characters often leads to readability issue for no (modern) reason. 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: module import questions and question about pytest and module imports
- Original Message - From: sam pendleton samp4...@gmail.com Having to put the garage package on the sys.path seems a little off, why wouldn't relative imports work? Do most people somehow put their packages in sys.path when bundling their python packages up to be shared with setuptools or other python package managers? If so, how? If it feels more natural to you, you can also update the env variable PYTHONPATH and add the path to your dev package. That way you don't need to add python code. But if you plan to distribute your package with setuptools, the solution would probably be to install your package before testing it (and probably use virtualenv). 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: [newbie] how to make program suggest to install missing modules
- Original Message - From: sohcahto...@gmail.com try: import someModule except ImportError: print Module is missing # handle it! Just make sure to attempt to import it again after making the call to pip to install it. Note that ImportError may be raised for other reasons than a missing module. Check https://docs.python.org/2/library/imp.html and the imp.find_module, it could be a safer way to check for a missing module. 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: Most gratuitous comments
- Original Message - From: sohcahto...@gmail.com I was trying to illustrate the point that some professors would demand you write code like this... # increment the line count lineCount += 1 # Check if line count is over 10 if lineCount 10 # Tell the user there are too many lines print 'There are too many lines! ...which is obviously bad commenting style. But I guess my original minimal example was too minimal. The problem is not that every line is commented, the problem is that comments do not add any value. There's always something to tell in real life situations: # assuming all lines look like 'v=1234\n', generate all integers provided by the user values = (int(line.replace('v=', '')) for line in lines) # See SPE-xxx: 10 line max do not change it if len(lines) 10: # TODO: use the logging module print 'There are too many lines! In practice, this yield to a comment every 2 or 3 lines. Of course this much depend on the code itself and may vary slightly from code block to code block. Note that I am not sanctioning the use of comment on import statements :D To go back to your point, some professors may be right when asking a comment every line, because it will be easier then for someone to back off a little bit and comment slightly less. While students with the habit of writing no comment will have much trouble commenting properly. Cheers, 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: Style question: Importing modules from packages - 'from' vs 'as'
- Original Message - From: Chris Angelico ros...@gmail.com To: python-list@python.org Sent: Wednesday, 3 December, 2014 12:02:17 PM Subject: Style question: Importing modules from packages - 'from' vs 'as' When importing a module from a subpackage, it's sometimes convenient to refer to it throughout the code with a one-part name rather than two. I'm going to use 'os.path' for the examples, but my actual use-case is a custom package where the package name is, in the application, quite superfluous. Throughout the code, I want to refer to path.split(), path.isfile(), etc, without the os. in front of them. I could do either of these: import os.path as path from os import path Which one would you recommend? Does it depend on context? An as import works only if it's a module in a package, where the from import can also import other objects (you can't go import pprint.pprint as pprint). I'm fairly sure that's an argument... on one side or another. :) Thoughts? ChrisA -- https://mail.python.org/mailman/listinfo/python-list I know you specifically stated you didn't want to do this but import os os.path.isfile() is the best option imo, especially from the reader point of view (Namespaces are one honking great idea). -- 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: Can you use self in __str__
- Original Message - From: Seymore4Head Seymore4Head@Hotmail.invalid To: python-list@python.org Sent: Friday, 28 November, 2014 4:31:50 AM Subject: Re: Can you use self in __str__ On Thu, 27 Nov 2014 21:49:29 -0500, Dave Angel da...@davea.name wrote: class Hand: def __init__(self): self.hand = [] # create Hand object def __str__(self): s = 'Hand contains ' for x in self.hand: s = s + str(x) + return s I am using 2.7 (Codeskulptor). This is working code. It starts with an empty list that gets appended from a full deck of shuffled cards. dealer=Hand() player=Hand() I don't really know how to post working code without posting a lot. I am not being too successful in trying to post enough code to have it work without posting the entire code. Here is the link if you want to run it. http://www.codeskulptor.org/#user38_Kka7mh2v9u_9.py The print out looks like this: Hand contains H4 DQ. I can (and am) currently printing the hand like this: print Player's,player print Dealer's,dealer My question is can you add (self) in the __str__ so when you issue the command print player the player part is included in the __str__. -- https://mail.python.org/mailman/listinfo/python-list I think your main problem is a design issue. I won't go into details, it would be too long but here's a way to fix your problem: # Untested code class Player(object): def __init__(self, name): self.name = name self.hand = Hand() def __str__(self): return '%s%s has %s' % (self.__class__.__name__, self.name, self.hand) # A dealer is a special type of player class Dealer(Player): pass def deal(): global outcome, in_play,deck,dealer,player # your code goes here deck=Deck() deck.shuffle() print deck players = [Dealer('Robert'), Player('John')] for deal in range(2): for player in players: player.hand.add_card(deck.deal_card()) for player in players: print str(player) in_play = True With the above design, the relation between player and its hand is implemented with the Player attribute hand. It's a classic design where the container knows about the content, but the content does not know its container. There are other solutions which do not require a new class, but I have the feeling you will need the Player class in the future. Moreover The design above I gave you will be probably broken in the future when you add features to your code. The same player may be a dealer or not, it may vary over time. You will probably need a 'Table' object which handles a collection of players, with a dealer, small blind, big blind etc, amount of money in the pot etc... 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: Code review
- Original Message - From: C Smith illusiontechniq...@gmail.com I read that with 2.7 that I had to initialize class variables to immutable types. I think because I was working with the lists before they had been altered and were still empty lists. I will mess around tomorrow with the classes you suggested as I have yet to make use of decorators. Thanks. The problem you referring too is probably the default value in *function definition*. Never write class Foo(object): def __init__(self, bar=[]): self.bar = bar The empty list is evaluated at the function definition and will be shared by all instances of the class. What you can do is class Foo(object): def __init__(self, bar=None): # None is immutable self.bar = bar or [] On a completely unrelated topic: I think you are using too much of default values for you arguments. I tend to use them only for keeping something backward compatible. Otherwise, use positional arguments, remember that explicit is better than implicit. Rememer your Table class: class Table(object): def __init__(self,bigblind=20,PLAYERNUM=0,pot=0,PLAYERORDER=None, hand_done=0, left_to_act=None,cost_to_play=0,in_hand=None,last_raise=0,cards_in_play=None,round='preflop'): You do not need to to pass all attribute initializers to your init method. For instance PLAYERNUM, which should be lowercase by the way, is clearly not intended to be set at the Table creation, it is something changed when filling seats. Actually, since you've created your table this way: table1=Table(bingblind=1) It probably means that your table __init__ method should look like: def __init__(self, bigblind): self.bigblind= bigblind self.hand_one = False self.left_to_act = [] # etc... By the way, avoid using directly 1 and 0 for coding booleans, use True and False (see hand_one attribute). 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: Understanding help command description syntax - explanation needed
Original Message - From: Ivan Evstegneev webmailgro...@gmail.com To: python-list@python.org Sent: Wednesday, 5 November, 2014 12:00:16 PM Subject: Understanding help command description syntax - explanation needed So here is the question itself: If I use the help command to check the “range” command I get this info: range(stop) - range object range(start, stop[, step]) - range object With python 2.7, when I type help(range), I get Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) - list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. range([start,] stop[, step]) tells you how to call the range function, there's a start, stop and step argument. The purpose of these arguments are given by the longer description. brackets [] means that the argument is optional. Though there's nothing wrong with googling the function for help, I'm doing it all the time. Actually, the python documentation is a better place to get help on a particular function, just make sure you hit the correct version, for either python 2 or 3: https://docs.python.org/2/library/functions.html#range I'm using python's help function only when working offline. 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: generating unique variable name via loops
- Original Message - From: Fatih Güven mfthgu...@gmail.com I have a structured and repetitive data. I want to read a .txt file line by line and classified it to call easily. For example employee1 has a name, a salary, shift, age etc. and employee2 and other 101 employee have all of it. Call employee1.name or employee2.salary and assign it to a new variable, something etc. Some python 2.7 pseudo code to give you some leads employes = {} with open('file.txt') as f_: for line in f_: name, age, phone = line.split(',') employes[name] = (age, phone) print employes If your file is a csv format, it could even be easier using the csv module. 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: Code review
- Original Message - From: C Smith illusiontechniq...@gmail.com To: python-list@python.org Sent: Tuesday, 4 November, 2014 4:28:33 PM Subject: Code review I was wondering if I could get some feedback on the biggest thing I have done as an amateur Python coder. The sidepots algorithm isn't correct yet, but I haven't worked on it in a while and thought I would get some advice before diving back in. import random, os ## class Table(object): def __init__(self,bigblind=20,PLAYERNUM=0,pot=0,PLAYERORDER=None, hand_done=0,\ left_to_act=None,cost_to_play=0,in_hand=None,last_raise=0,cards_in_play=None,round='preflop'): if cards_in_play is None: cards_in_play = [] if in_hand is None: in_hand = [] if PLAYERORDER is None: PLAYERORDER = [] if left_to_act is None: left_to_act = [] [snip hundreds of code lines] - Most methods have too much code, split methods into more unitary logical functions. - For instance, add classes 'Hand' and 'Card' - not enough comments - have you written some tests? The code reached a reasonable size where tests would be very helpful (module unittest) - why do you use uppercase attributes ? like PLAYERORDER. These are not 'constants', you change them Example of (incomplete) Card and Hand implementation (python 2.7): class Card(object): Card implementation. def __init__(self, suit, rank): self._suit = suit self._rank = rank # write test card1 == card2 def __eq__(self, other): return (self.suit, self.rank) == (other.suit, other.rank) # use cards as dict keys def __hash__(self): return hash(self.suit, self.rank) # will allow python to sort a list of cards def __lt__(self, other): return int(self) int(other) def __int__(self): Return the numerical value of a card # the dictionary is incomplete return {'1':1,'2':2,'J':11,'Q':12}[self.rank] def __str__(self): return 'Card(%s of %s)' % (self.rank, self.suit) # alias in case card.rank has more meaning than int(card) @property def rank(self): return int(self) # read only access to suit @property def suit(self): return self._suit class Hand(object): Short incomplete example of Hand class def __init__(self): self._cards = [] def add(self, card): if not self.full: self._cards.append(card) if card.rank == 14: # it's an Ace # trick to get Ace considered as 1 as well self._cards.append(Card(card.suite, '1')) # generate the ordered sequence of cards, hiding the '1' cards @property def cards(self): return (card for card in sorted(self._cards) if card.rank 1) # allow to write len(hand) def __len__(self): return len(list(self.cards)) #property def full(self): return len(self) == 5 # allow to write 'for card in hand:' def __iter__(self): return iter(self.cards) def remove(self, card): # and so on... Otherwise: replace if left_to_act is None: left_to_act = [] self.left_to_act = left_to_act by self.left_to_act = left_to_act or [] replace if ranky == 9 or ranky == 5 by if ranky in [9,5] replace if foo == True by if foo replace if len(self.left_to_act) == 0 by if self.left_to_act And much more... but honestly, there's too much code :) I'll let you chew on this one. 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: Classes
- Original Message - From: Gregory Ewing greg.ew...@canterbury.ac.nz Steven D'Aprano wrote: Like all good Pythonistas[1], we hate Java and think that getter/setter methods are pointless. But come on, they're not *wrong*, What's wrong is the statement that getters and setters are necessary to allow the implementation to change without changing the interface. That's factually incorrect in regard to Python. -- Greg I'm not sure that is what the course was stating: The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class. I agree with Steven on that one, while getters/setters are not the preferred way, they are not utterly wrong. Python uses the descriptor protocol which is basically getters and setters. It's is just hidden by a strange decorator syntax. 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: When using a decorator exceptions raised reference the decorator not the function
- Original Message - From: Peter Otten __pete...@web.de To: python-list@python.org Sent: Thursday, 30 October, 2014 1:45:42 PM Subject: Re: When using a decorator exceptions raised reference the decorator not the function Néstor Boscán wrote: I'm using Python 2.7 and I'm creating a class decorator that extract information from exceptions for logging purposes. Everytime an exception is raised from the original function and I extract the origin of the exception with sys.exc_info() I get a reference to the line in the decorator where the function is called, not the line of the original function where the exception was raised. Any ideas? Please show us the code, preferably as a small self-contained example. Thank you. +1 show us your decorator. if you did something like: try: except Exception, e: # do something raise e Then replace raise e by a bare raise 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: Callback functions arguments
- Original Message - From: ast nom...@invalid.com To: python-list@python.org Sent: Monday, 27 October, 2014 9:16:26 AM Subject: Callback functions arguments Hi In this web site at example n°5 http://fsincere.free.fr/isn/python/cours_python_tkinter.php A program is using the Scale widget from tkinter module. Here is a piece of code: Valeur = StringVar() echelle = Scale(Mafenetre, from_=-100, to=100, resolution=10, \ orient=HORIZONTAL, length=300, width=20, label=Offset, \ tickinterval=20, variable=Valeur, command=maj) The maj callback function is: def maj(nouvelleValeur): print(nouvelleValeur) When the user move the scale with the mouse, the new position is supposed to be printed on the python shell. The maj function has an argument nouvelleValeur but no argument is passed through the Scale widget. So how the hell Python knows that it has to pass parameter Valeur to the maj function ? thx The Scale object is performing the call, hence it will be the Scale object that will call your maj function with a nouvelleValeur parameter. When you write command=maj, you pass the function, but you don't call it. That's the purpose of a callback. You provide a function and it get called by the object you've been giving the function to. The Scale object should be documented and should provide with the callback signature. See http://effbot.org/zone/tkinter-callbacks.htm 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: Classes and the command line
- Original Message - From: Seymore4Head Seymore4Head@Hotmail.invalid To: python-list@python.org Sent: Monday, 27 October, 2014 3:27:18 AM Subject: Classes and the command line I am trying to learn classes. I am currently using Python 2.7 at the command line. If you try to type commands at the command line and make the slightest mistake you have to start over. I was trying to copy and paste these instructions into the command prompt. http://en.wikibooks.org/wiki/Python_Programming/Classes class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print self.x There is really no way to do that without pasting line by line is there and adding deleting spaces? And if you use spaces and tabs, they are not the same. You could use Ipython http://ipython.org/, if you're familiar with the python shell you won't get lost as it's quite the same with a lot of features added. One of them is the %paste magic function, it will paste your clipboard taking care of the indentation for you. 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: (test) ? a:b
- Original Message - From: ast nom...@invalid.com To: python-list@python.org Sent: Wednesday, 22 October, 2014 10:29:43 AM Subject: (test) ? a:b Hello Is there in Python something like: j = (j = 10) ? 3 : j+1; as in C language ? thx j = 3 if j =10 else j+1 Cheers 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: (-1)**1000
- Original Message - From: ast nom...@invalid.com To: python-list@python.org Sent: Wednesday, 22 October, 2014 10:27:34 AM Subject: (-1)**1000 Hello If i am writing (-1)**1000 on a python program, will the interpreter do (-1)*(-1)*...*(-1) or something clever ? In fact i have (-1)**N with N an integer potentially big. I do some tests that suggest that Python is clever thx Python will yield the correct results. That is the most clever thing to do. If you really worried about execution speed (I assume that what your question implies), Python may not be the language you need. However, know that there are these modules numpy and scipy which are used by the scientific community which provide a python interface (it's a python module) but most of the heavy lifting is done in C (you can embed C in python code). For instance http://docs.scipy.org/doc/numpy/reference/generated/numpy.power.html Use this module if speed is what you're looking for. 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: Permissions on files installed by pip?
- Original Message - From: Adam Funk a24...@ducksburg.com To: python-list@python.org Sent: Thursday, 16 October, 2014 9:29:46 PM Subject: Permissions on files installed by pip? I've been using the python-nltk package on Ubuntu, but I need ntlk 3.0 now. I used 'sudo aptitude purge python-nltk' to get rid of my existing installation, followed instructions on the nltk website [1] starting at step 4 (since I already have python-pip python-numpy packages installed). $ sudo pip install -U I couldn't get it to work, until I realized that the permissions ownership on /usr/local/lib/python2.7/dist-packages were 'drwx--S--- root staff'. A 'chmod -R a+rX' on that directory seems to have fixed it. Is it normal for sudo pip install to set the permissions that way, or did I do something wrong? On debian wheezy: ls -al /usr/local/lib/python2.7/dist-packages drwxrwsr-x 5 root staff 4.0K Jun 30 15:16 ./ I'm not sure pip is responsible for this anyway, so my money goes on you did something wrong :) 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: virtualenv question: include just a few site packages
- Original Message - From: Gelonida N gelon...@gmail.com To: python-list@python.org Sent: Thursday, 9 October, 2014 5:55:44 PM Subject: Re: virtualenv question: include just a few site packages You could build a virtual machine, installing only your VIP modules, and create virtual environment on this virtual machine, using the system site packages. Yeah that's an option. However I guess in this case it's probably faster to write a script, that 'post-processes' the virtualenv and just deletes files / symlinks, that are not desired. Definitely not elegant, but probably OK. On the other hand a VM migfht help finding out which files to keep. if you have the package somewhere of those modules you'd want to install you can specify local packages in the pip_requirement.txt file: https://pip.readthedocs.org/en/1.1/requirements.html 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: CLI framework using python
- Original Message - From: vijna...@gmail.com Hi, I need to develop a python CLI framework. [snip] 3. There are other such commands for which i will be using python scripts. I came across pyCLI, but it doesn't have much documentation, so couldn't figure out how to move forward. Any guidance would be greatly appreciated. Regards Thanks, Vij https://pythonhosted.org/pyCLI/ The doc features a quick tour and basic usage section + the complete API, illustrated with examples. Why don't you show us some code you've written using pyCli, maybe we could 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: virtualenv question: include just a few site packages
- Original Message - From: Gelonida N gelon...@gmail.com To: python-list@python.org Sent: Thursday, 9 October, 2014 12:09:50 AM Subject: virtualenv question: include just a few site packages virtualenv has the switch --system-site-packages (including all system site pacgaes) and the switch --no-site-packages (to expclude all site packages) Does anyone know an easy way to include just a few site-packages? for example (PySide, but not PyQt) The reason I'm asking is following. Some site packages are sometimes raher huge or sometimes refuse to compile on certain hosts. as these packages are already part of the site packages I'd like to include them. You might wonder why I care whether I have more site packages than I need. As long as I don't import them, I shouldn't care about it. If I really wanted to replace a version I could use pip install -U. However sometimes I'd like to have a test environment where want to be sure, that no module can find certain other modules. so they should not be visible. at the moment I make some experiments with pyinstaller and the module pythonqtbindings. and there I'd like to be sure that no PuQt files end up in the generated code. The only idea, that I have so far is to run virutalanv with --system-side-packages and to manually remove modules I don't want or to run virtualenv without this switch and to manually add links for site packages, taht I want. both options don't really feel right for me. Is there any other way? You could build a virtual machine, installing only your VIP modules, and create virtual environment on this virtual machine, using the system site packages. 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: Python code in presentations
- Original Message - From: Wolfgang Keller felip...@gmx.net To: python-list@python.org Sent: Wednesday, 1 October, 2014 11:42:34 AM Subject: Re: Python code in presentations Right now the method I'm using is write the code in notepad++, use a plugin (NppExport) to copy paste code into powerpoint. After using it a little bit, I'm really not satisfied with this method, it's expensive and all this copy paste stuff is driving me crazy. Not to mention that the syntax highlight from notepads renders like crap in powerpoint. I wonder if some people in this list who have successfully presented python code have some tips about doing the proper way. Ned's presentations for pycons are to me one example of successful code presentation: - the layout is simple - the code and code output are clearly identified - a line of code can be highlighted while presenting LyX and Beamer. Sincerely, Wolfgang Thank you all for all your great suggestions. I think I now have all I need. 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
Python code in presentations
Hello list, I'm currently writing a presentation to help my co-workers ramp up on new features of our tool (written in python (2.7)). I have some difficulties presenting code in an efficient way (with some basic syntax highlights). I need to be catchy about the code I'm presenting otherwise the presentation will fail and I would be better saying to my co-workers RTFM, cause there is a manual. So I really need to make them realize the code I'm presenting will benefit them (they're not software engineers, python is just a tool, their expertise and focus is aimed at something else, don't blame them :) ) Right now the method I'm using is write the code in notepad++, use a plugin (NppExport) to copy paste code into powerpoint. After using it a little bit, I'm really not satisfied with this method, it's expensive and all this copy paste stuff is driving me crazy. Not to mention that the syntax highlight from notepads renders like crap in powerpoint. I wonder if some people in this list who have successfully presented python code have some tips about doing the proper way. Ned's presentations for pycons are to me one example of successful code presentation: - the layout is simple - the code and code output are clearly identified - a line of code can be highlighted while presenting http://nedbatchelder.com/text/iter.html I have access to powerpoint, or any tool under linux (I don't have access to Mac's stuff). Right now I'm so not satisfied by my current method that I'm about to make the presentation showing the code from the file directly, alt-tabing between the slides and the code. At least it's cheap. 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: Python code in presentations
- Original Message - From: Joel Goldstick joel.goldst...@gmail.com Cc: python-list@python.org Sent: Tuesday, 30 September, 2014 3:01:38 PM Subject: Re: Python code in presentations I'm a little at a loss that you are concentrating on showing code to users. Are you also showing how your tool works to solve the problems that they will need to solve with it? JM We write python code using the tools I've mentioned, these tools are nothing more than code snippets, custom classes, decorators and modules. Using them is all about writing python code. However we all have the kind of quick and dirty knowledge of python, writing python code is not our core expertise. That is why I thought showing how simple and elegant python can be could provoke some visual shock, making them think I want to do that. Possibly the wrong approach, I'll tell you that after the presentation :) . 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: Flask and Python 3
- Original Message - From: Chris Angelico ros...@gmail.com Cc: Python python-list@python.org Sent: Friday, 26 September, 2014 1:55:51 AM Subject: Re: Flask and Python 3 On Fri, Sep 26, 2014 at 4:35 AM, Juan Christian juan0christ...@gmail.com wrote: when I say video tutorial, it's implied that every video that I talked about have 1. The source-code (if programming/code related), 2. The transcripts and in some cases even 3. PDF version of the video. I've almost never seen videos that have all of that - and certainly not enough to *imply* that about the term. ChrisA -- https://mail.python.org/mailman/listinfo/python-list Though I'm never using videos to learn, they probably can benefit some people. Ask you this question : is there a major difference between videos and presentations, if not how can we justify the money spent on Pycons over the years ? 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: PyCli : Need some reference to good books or tutorials on pycli
- Original Message - From: vijna...@gmail.com To: python-list@python.org Sent: Friday, 26 September, 2014 2:54:48 PM Subject: PyCli : Need some reference to good books or tutorials on pycli Hi Folks, I need to develop a CLI (PyCli or similar)on Linux. To be more specific to develop Quagga(open source routing software) like commands using python instead of C. Need some good reference material for the same. P.S google didn't help Thank You! Vij Have you considered using ipython ? I have built a CLI on top of that and it's pretty easy and effective, and it requires almost no dev. The following code is untested but it should give you an idea of what I mean. cli.py: import IPython import yourApi # explict exposure foo = yourApi.foo bar = yourApi.bar # or you can expose all the content of yourApi api = yourApi # delete unwanted names del yourApi del IPython # start the interactive CLI IPython.frontend.terminal.embed.InteractiveShellEmbed(banner1='Hello Word', exit_msg='bbye')() Regards, 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: how to write a html to automatically display the dictionary?
- Original Message - From: luofeiyu elearn2...@gmail.com To: Joel Goldstick joel.goldst...@gmail.com, python-list@python.org Sent: Wednesday, 24 September, 2014 1:06:25 AM Subject: Re: how to write a html to automatically display the dictionary? how can i create the proper html file with Jinjia 2 or other temple? template :) I'm surprised you didn't figure it out by looking at jinja2 examples in their documentation. python 2.7 : from jinja2 import Template template = Template(''' table border=1 tr{% for k in x.keys()%}th{{k}}/th{%endfor%}/tr tr{% for k in x.values()%}td{{k}}/td{%endfor%}/tr /table''') with open('foo.html', 'w') as myFile: myFile.write(template.render(x={'f1':1,'f2':2,'f3':3})) Regards, 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: Class Inheritance from different module
class User(Inheritance from API): def __init__(self, ID): steamapi.core.APIConnection(api_key = KEY) super( Inheritance SteamUser (ID)) # creates the user using the API [...] So that in my code when I need to create a new user, I just call 'usr = User(XXX)' instead of calling 'usr = steamapi.user.SteamUser(76561197996416028)', is that possible? [snip -- 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: Class Inheritance from different module
- Original Message - From: Jean-Michel Pichavant jeanmic...@sequans.com To: Juan Christian juan0christ...@gmail.com Cc: Python python-list@python.org Sent: Monday, 22 September, 2014 1:37:41 PM Subject: Re: Class Inheritance from different module class User(Inheritance from API): def __init__(self, ID): steamapi.core.APIConnection(api_key = KEY) super( Inheritance SteamUser (ID)) # creates the user using the API [...] So that in my code when I need to create a new user, I just call 'usr = User(XXX)' instead of calling 'usr = steamapi.user.SteamUser(76561197996416028)', is that possible? [snip Sorry, sent the message by mistake. Anyway if you just want a nice way to create an instance, you may simply write import steamapi.user.SteamUser as User usr = User('whatever') However you don't create an APIConnection when creating a user, it does not make much sense, you only need one API connection per session and it will be shared by all the User objects. # Note ApiConnection is a singleton, and you only need to execute this once, in you app/script initialization for instance. api = APIConnection(api_key='dlkfnsdlfn') # query the database user1 = User('user1') user2 = User('user2') Cheers, JM NB: I assumed you were using https://github.com/smiley/steamapi NB2 : because APIConnection is a singleton, your original code probably works just fine, I'm just not a big fan of breaking to python module design -- 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: Love to get some feedback on my first python app!!!
- Original Message - From: Chris Angelico ros...@gmail.com Cc: python-list@python.org Sent: Saturday, 20 September, 2014 4:58:44 PM Subject: Re: Love to get some feedback on my first python app!!! [snip] #search API rawData = urllib.urlopen('http://ajax.googleapis.com/ajax/services/search/web?v=1.0q='+encodedQuery).read() #loads data from API into json jsonData = json.loads(rawData) #extracts the results from API searchResults = jsonData['responseData']['results'] The more normal way to write these would be in present tense, in a more imperative style: Fix some bugs, Load data, Extract results. (Although these comments are actually quite redundant - all they do is tell you what the single next line of code does.) I used to belong to the cult don't repeat yourself in the comments, being angry against people who thought I couldn't understand by myself the simplest line of code. But I changed my mind. I've read some code comments over the years and best ones (imo) where those which where actually repeating themselves. Golden rules of comments: # state what you plan to do doIt() For instance: cells = ['a', 'b' 'c'] # print the first cell print cell[1] A bug that is easily spotted thanks to the comment. It's all about implementation versus intentions. Also note that comment should be written for the future self, and most importantly, for the current others. 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: Love to get some feedback on my first python app!!!
- Original Message - From: Chris Angelico ros...@gmail.com Cc: python-list@python.org Sent: Monday, 22 September, 2014 4:50:15 PM Subject: Re: Love to get some feedback on my first python app!!! On Tue, Sep 23, 2014 at 12:32 AM, Jean-Michel Pichavant jeanmic...@sequans.com wrote: For instance: cells = ['a', 'b' 'c'] # print the first cell print cell[1] A bug that is easily spotted thanks to the comment. It's all about implementation versus intentions. Also note that comment should be written for the future self, and most importantly, for the current others. I do see your point, but there's a serious problem here of code edits. It's really easy to zip through and find all occurrences of some name and change them - and miss the one in the comment. In this particular case, I'm not actually sure where the bug is: is it in the first line (should be cell = ...) or the third (print cells[1])? Either way, the comment doesn't make it any clearer, because the plural rule in English doesn't always match naming of variables. Also, it's common in English to count from 1, but in code to count from 0; so there's another bug (and this might be the one you thought easily spotted) - it should either be cell[0] in the third line, or print the 1th cell in the second. (Plus, there's a comma omitted. That list has two elements, but I think it's meant to have three. However, I'm guessing that's a transcription error, or a construction-in-email error, and nothing to do with what you're saying.) Now, compare this similar code: cells = ['Chris Angelico', 'ros...@gmail.com', 142857] # print the email address print(cells[2]) This says *why* it's doing what it does - what the meaning of the index is. And it, too, has a clearly visible bug, because when it prints out an integer, the comment makes it obvious that it's done the wrong thing. This is, IMO, much more useful. If the code gets edited (maybe the name used to be in two fields for First Name and Last Name, and then someone realized how bad an idea that is - but forgot to update the index), the original intention is visible; if it just says print out cell #2, it's not so helpful. So basically, don't *purely* repeat yourself, but give some info that's a level behind the code. ChrisA Damn you didn't fall into my trap :D. The code I posted had many bugs but one could not be fixed without the comment. Or at least there's an obvious discrepancy between the comment and the code that should catch the reader's attention. Anyway it's seems we agree anyway because your example perfectly illustrate what I was trying to demonstrate: print(cells[2]) is very easy to understand, most of people would say 'no need of any comment'. I think it does require a comment. I find myself writing a comment every 3 or 4 line of code, at least, for what I've read, that's way too much. 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: Love to get some feedback on my first python app!!!
Original Message - From: Chris Angelico ros...@gmail.com Cc: python-list@python.org Sent: Monday, 22 September, 2014 6:04:43 PM Subject: Re: Love to get some feedback on my first python app!!! On Tue, Sep 23, 2014 at 1:52 AM, Jean-Michel Pichavant jeanmic...@sequans.com wrote: The code I posted had many bugs but one could not be fixed without the comment. Or at least there's an obvious discrepancy between the comment and the code that should catch the reader's attention. The obvious discrepancy, sadly, doesn't tell you which one is right. [snip] ChrisA You're right but that's fine and the comment's still doing its job. Either the comment is wrong, or the code is. It doesn't really matter which one, It needs to be investigated and fixed. Otherwise you could say that writing specifications is pointless since specifications can be wrong and when a problem occur you need to figure out if either the code or the specification is responsible. Like a CRC check, sometimes the payload is correct and the error is on the CRC, it's still damn useful. 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: Keeping python code and database in sync
- Original Message - From: Roy Smith r...@panix.com Yeah, schema migration is an ugly problem. There's a number of tools to help here, most of which reduce the suckitude, but don't eliminate it completely. Some things you might want to look at: * SQLAlchemy Migrate * South (django-specific) * yoyo-migrations * alembic Google for python schema migration tools and you'll probably find others. Note that South is now fully integrated in django 1.7 (It's still ugly but it has been polished by the django team). The OP may want to consider moving to such framework, they tend to provide working concepts on critical issues when it comes to webapp/database. 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: [RELEASE] Nevow 0.11.1
- Original Message - Hello, I'm pleased to announce the release of Nevow 0.11.1. Nevow is a web application construction kit written in Python and based on Twisted. It is designed to allow the programmer to express as much of the view logic as desired in Python, and includes a pure Python XML expression syntax named stan to facilitate this. However it also provides rich support for designer-edited templates, using a very small XML attribute language to provide bi-directional template manipulation capability. This release includes a number of minor new features and bug fixes. It also includes changes to modernize Nevow's packaging - installation of Nevow using `pip` is now supported. This release also marks the move of Nevow development to Github. You can read about all of the changes in this release in the NEWS file: https://github.com/twisted/nevow/blob/release-0.11.1/NEWS.txt 404 not found https://github.com/twisted/nevow/blob/nevow-0.11.1/NEWS.txt cheers, 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: pyflakes best practices?
- Original Message - We've recently started using pyflakes. The results seem to be similar to most tools of this genre. It found a few real problems. It generated a lot of noise about things which weren't really wrong, but were easy to fix (mostly, unused imports), and a few plain old false positives which have no easy fix (in the sense of, things I can change which will make pyflakes STFU). So, what's the best practice here? How do people deal with the false positives? Is there some way to annotate the source code to tell pyflakes to ignore something? -- https://mail.python.org/mailman/listinfo/python-list For the easy things to fix, fix them (yes, remove the unused imports). That is the best practice. pyflakes is integrated with my vim editor, it's working fine, but I used someone else script so there's possibly some tuning going on, I can't help you with that. However as someone stated before, pylint is I think a preferred solution, it's highly configurable and this is what we're using for the real deal (the code base is checked with pylint). With pylint, you can disable any checker you find annoying, you can add commented directives in the code to locally disable a checker in a block or in a line and you can write plugins to extend the pylint understanding of your code. 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: YADTR (Yet Another DateTime Rant)
- Original Message - One of my roles on this newsgroup is to periodically whine about stupidities in the Python datetime module. This is one of those times. I have some code which computes how long ago the sun set. Being a nice pythonista, I'm using a timedelta to represent this value. It would be difficult to imagine a less useful default way to print a timedelta: previous sunset: -1 day, 22:25:26.295993 The idea of str() is that it's supposed to return a human-friendly representation of a value. Humans do not say things like, The sun set 1 day ago plus 22 hours and 25 minutes. I can think of a less useful default way: previous sunset: 1 sunset ago This is how humans have been saying things for thousands of years before inventing the clock. Beside that, I think datetime has all the formatters required to do pretty much anything. Note : I don't see what's wrong in your example, however I have the feeling the term stupiditie is a little bit strong ;) 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: How do we pass default argument value to create thread object?
- Original Message - Hi, I am using Thread class to create threads. CODE thread = threading.Thread(target=Fun, args=[arg1, arg2, arg3=val]) thread.start() /CODE This code is throwing compilation error(Ipython). In [19]: import threading In [20]: def Fun(agr1, arg2, arg3=None): : pass : In [21]: thread = threading.Thread(target=Fun, args=[arg1, arg2, arg3=val ]) File ipython console, line 1 thread = threading.Thread(target=Fun, args=[arg1, arg2, arg3=val]) ^ SyntaxError: invalid syntax How do we pass the value to default arguments while creating thread object? Regards, ~Piyush Facebook Twitter Hi, try something like thread = threading.Thread(target=Fun, args=(val1, val2), kwargs={arg3:val3}) This will call Fun(val1, val2, arg3=val3) Browse the python tutorial for details on arguments and keyword arguments. Cheers, 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: Need help in writing some code so i can re-use it in every module or class
- Original Message - Hello Experts, I have requirement, like i want to use below command in python script. command --username username --password password Command line arguments now my requirement is i want to write some class so i can re-use command --username username --password password part via importing as module or class .. and re-use that in other module or classes .. so i dont have to write that in every module or classes .. Now why i wan to do this is ... currently command we are using is going to change in near future to command1, so i dont have go to every module and change that command if i have written single module or class and re-use it in other ? Hope i am clear enough to describe my issue? any suggestions ? Regards, DJ Hi, Have a look at http://docs.python.org/2/library/argparse.html Then create a module, for instance myParser, that defines the common paser, and in each of your scripts import that module and use the parser. *Untested code* myParser.py import argparse parser = argparse.ArgumentParser(description='Process some integers.') #then define the parser then in a script: script.py import myParser if __name__ == '__main__': args = myParser.parser.parse_args() # and so on... Cheers, 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: Functions help
- Original Message - On Feb 23, 2014, at 1:44 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Sorry, I don't really understand your question. Could you show an example of what you are doing? Do you mean add 5 or *5? Add *5 doesn't really mean anything to me. Sorry I forgot to add the code that I had to give an example of what I was talking about. I’ll put it below, sorry that it’s so long. A Here's an example of how your star() function could be rewritten. Note that it does not exactly do what it does in your example regarding the start and end position of the turtle. So use it for inspiration only ;) from turtle import * from math import sin, sqrt, radians def star(width): R = (width)/(2*sin(radians(72))) A = (2*width)/(3+sqrt(5)) # record the initial position position = getturtle().pos() heading = getturtle().heading() penup() left(36) # initial angle forward(R) pendown() for arms in range(5): left(144) forward(A) right(72) forward(A) penup() # go back to the initial position getturtle().setpos(position) getturtle().setheading(heading) showturtle() clear() star(50) -- 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: Problem with the console on the new python.org site
- Original Message - On Sun, 23 Feb 2014 10:20:15 -0800, Pierre Quentel wrote: The new home page of python.org is very nice, congratulations ! The best I can say about it is that I'm extremely underwhelmed by the design, which is far more busy and colourful than the old design (this is not a complement), and not happy that it doesn't work correctly without Javascript. Steven, you must have been the grumpy smurf in another life ;) But there is a problem with the online console provided by PythonAnywhere : with my azerty keyboard, I can't enter characters such as ) or ] - very annoying ! I have an azerty keyboard and it works just fine, your problem must be something else. 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: Mac vs. Linux for Python Development
- Original Message - Hello, I'm sure this is a common question but I can't seem to find a previous thread that addresses it. If one one exists, please point me to it. I've been developing with python recreationally for a while on Ubuntu but will soon be transitioning to full-time python development. I have the option of using a Mac or Ubuntu environment and I'd like to hear any thoughts on the pros and cons of each. Specifically, how's the support for numpy and scipy? How are the IDEs? Since I generally like working with a Mac, I'd like to hear if there are any significant downsides to python dev on OsX. Thanks I'd rather go for linux, I have the feeling that the dev community is larger, though I have no numbers to provide, so I may be wrong. One would successfully argue that most python dev are cross-platform anyway. IDEs in Linux are great, and you'll get the best of them for free. However vim / emacs are available for free on OsX as well... If you go for Linux, know that ubuntu would not be the first choice, ubuntu prefers user experience over stability. Debian for instance is a distribution largely used in the industry. 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: Using virtualenv to bypass sudoer issues
Thank you all for you insights. I'll probably go with virtualenv, I'll be able to distribute it among the team. There's still one point worrying me though: We're doing a lot a remote execution. We're using execnet http://codespeak.net/execnet/, and I'm not sure it can be compatible with virtualenv. execnet working at the python level I don't see how I can execute shell stuff before. I had a look at fabric http://docs.fabfile.org/en/1.8/, and it looks like it can handle virtual env (anyone confirm?). Has someone already successfully remotely activated a venv then execute a python scripts within that env, getting back the stdout/stderr ? I'm afraid right now that switching to venv would mean switching from execnet to fabric as well (I hate redoing stuff that works :-/ ). 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: Using virtualenv to bypass sudoer issues
Call the venv version of python and activation is handled. E.g. in a fabfile myenv/bin/python myscript.py -- Pete Forman -- https://mail.python.org/mailman/listinfo/python-list wow, the solution is so nice and simple. 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
Using virtualenv to bypass sudoer issues
Greetings, Assuming I have a debian workstation for which I don't have any sudo rights, i n order to be able to install / remove python packages, should I be using virtualenv ? Is it a suited solution ? 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: generator slides review and Python doc (+/- text bug)
- Original Message - generator slides review and Python doc I do not know what tool is used to produce such slides. When the mouse is over a a text like a title (H* ... \H* ???) the text get transformed and a colored eol is appearing. Used to get a link to the given chapter/section... Works as intended. Sphinx features the same thing, it can be disabled. JM Note : the links provided in the OP example are broken though -- 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: Pyro4 - reading files
- Original Message - Hello there. I am currently working on a project involving the use of Pyro4. I have a scenario. We have the pc named A, and a pc named B. On pc B lies a python script, that includes pyro, and a method for reading files. On pc A, we create an instance to the pyro object on pc B. And we call the method for reading files. I want to read a file that lies on pc B, from pc A using the method of the pyro object i just created. Is it possible? Thank you. Hi, Yes, read http://pythonhosted.org/Pyro4/tutorials.html If you plan to transfer large files between PCS, make sure you read http://pythonhosted.org/Pyro4/tipstricks.html before, as other solutions may be better suited. 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: interactive help on the base object
- Original Message - On 17/01/2014 01:00, Terry Reedy wrote: On 12/6/2013 8:35 PM, Terry Reedy wrote: On 12/6/2013 12:03 PM, Mark Lawrence wrote: Is it just me, or is this basically useless? help(object) Help on class object in module builtins: class object | The most base type Given that this can be interpreted as 'least desirable', it could definitely be improved. Surely a few more words, How about something like. '''The default top superclass for all Python classes. Its methods are inherited by all classes unless overriden. ''' When you have 1 or more concrete suggestions for the docstring, open a tracker issue. At Mark's invitation, I have done so. http://bugs.python.org/issue20285 Thanks, I've altered my will accordingly :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence The issue is tagged 2.7. Is object the superclass of all classes in 2.7 ? I'm asking because in 2.5, it is not (old/new style). 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: Building and accessing an array of dictionaries
- Original Message - I would like to build an array of dictionaries. Most of the dictionary example on the net are for single dictionary. dict = {'a':'a','b':'b','c':'c'} dict2 = {'a':'a','b':'b','c':'c'} dict3 = {'a':'a','b':'b','c':'c'} arr = (dict,dict2,dict3) What is the syntax to access the value of dict3-'a'? Thank you. -- https://mail.python.org/mailman/listinfo/python-list Hi, arr = (dict,dict2,dict3) builds a tuple. If you want to build a (ordered) List, which is the closest type to array (arrays don't exists in python), you may write myList = [dict, dict2, dict3] you can access 'a' by writing myList[2]['a'] Additionally: myList[0] - 1st element myList[-1] - last element myList[3:] - list of elements of myList from the the 4th element to the last Accessing a list element or a dictionary value is done through the same operator []. That can be confusing at the very beginning, you'll get used to it eventually. 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: a web UI to invoke a python script at server side
- Original Message - Hey guys, I'm working on to provide a lightweight web UI for providing an interface to invoke a python script(a sequential script which could involve some system calls) at the server side. The UI should collect some parameters for input into this python script, and conversely the output of the script needs to be returned to the web client side. I haven't done much web programming before, can you provide some hints on how this is usually implemented ? Thanks Frank -- https://mail.python.org/mailman/listinfo/python-list Hi Frank, Have a look at http://flask.pocoo.org/ This is a micro web framework. Build your hello world web app, once it's working, look at the flask tutorial, you won't use the database but it'll give you a good overview of how things are organized. Flask support python 3 but your web server may not. You may need to stick with python 2. 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: Editor for Python
- Original Message - On Jan 8, 2014, at 10:53 AM, Jean-Michel Pichavant jeanmic...@sequans.com wrote: -- IMPORTANT NOTICE: too late you have sent this to a public forum No pb with that, the python list is the intended recipient :) I tried to negotiate this with my IT guys, but it looks like it's now mandatory, something related to being in the USA stock market. Yeah, when in doubt blame the Americans. Sorry if I hurt your feelings, have a look at http://www.sarbanes-oxley-101.com/ I don't blame anyone, would I be blaming the law, that wouldn't imply the americans anyway. cheers, JM The Sarbanes-Oxley Act of 2002, sponsored by Paul Sarbanes and Michael Oxley, represents a huge change to federal securities law. It came as a result of the corporate financial scandals involving Enron, WorldCom and Global Crossing. Effective in 2006, all publicly-traded companies are required to implement and report internal accounting controls to the SEC for compliance. -- 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: Editor for Python
- Original Message - On Friday, 23 November 2001 04:13:40 UTC+5:30, MANUEL FERNANDEZ PEREZ wrote: Hello, I'm looking for an editor for Python.I' m interested it works on Windows.Can anybody help me? Thank you Manuel http://lmgtfy.com/?q=python+editor+windows Otherwise, must of the newcomers will be pleased with http://notepad-plus-plus.org/ Ideally, try to use an editor that will allow you to edit any type of code, python or anything else. JM PS : you could also have searched this archive, this subject has been already discussed... a lot. -- 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: Editor for Python
- Original Message - I've been pleased with Komodo, and certainly prefer it over Notepad++. Komodo: http://www.activestate.com/komodo-ide?gclid=COHE4eLj7rsCFQISMwodOUQAiw Komodo is an IDE and costs 385$. I certainly expect it to better than notepad++. 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: Editor for Python
-- 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. too late you have sent this to a public forum No pb with that, the python list is the intended recipient :) I tried to negotiate this with my IT guys, but it looks like it's now mandatory, something related to being in the USA stock market. I have no way to remove it, it's added by the email server. I apologise for the noise. 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: nested dictionaries and functions in data structures.
- Original Message - Hello all. I have some questions again. :-) I wish to be able to place a function within a data structure. I would like to use a dictionary because I could pass it a key and then the function could be called. I couldn't find anything on the net to show me how to do this. More then likely, not using the right search terms. For example: funct_call = { 'bhp' : 'bhp_counters (addict[key1][key2])', 'ospf' : 'ospf_counters (addict[key1][key2])'} I am sure there is a way to do this. The other issue is I cannot nest dictionaries. I have seen examples and when I apply them to the code below. They do not provide the result I want. The program does 3 actions. 1. Opens all the files in the directory. Each file begins with data_. The 6 character in the file name is the occurrence of the output. Ranging from 1 to 9. The8th character plus the remaining part of the file is the output of the command. For example: data_1_ospf.txt The commands stored in this file are related to OSPF. When I build the nested dictionary I want to have OSPF as the primary key. Nested under OSPF is the number of times the command has been captured. The file content stored as an array and is the value of the 2nd key. data structure could look like this: outputs = { 'ospf' : { '1' : lines_of_file[], '2' : lines of_file[]} } Below is the code I have used to try and achieve the above. I just don't get the nested dictionary effect I am after. Again, I am trying to use standard core which some of the examples I have seen appeared to use. I am aware of collection module. #! /usr/bin/env python # Identifying if memory leaks are occurring. # goal is to import output to Excel. # created on 28 Dec 2013 By Sean Murphy import os, sys from os.path import exists # main code begins if len(sys.argv) = 2: # storing file names into variable from command line. filenames = sys.argv[1:] else: filenames = os.listdir(os.getcwd()) #print (Error, must provide at least one file name\n) #quit() outputs = {} # empty dictionary (hash) capture = # key used for the capture version command = # key for the command output for filename in filenames: if exists(filename): fp = open(filename, r) capture = filename[6] command = filename[8:] # nested dictionary. Command and then number of captures. outputs = {command : { capture :[fp.readlines() } } fp.close() else: print (error %s doesn't exists\n % filename) quit() print (%r\n % outputs.keys()) for key in sorted(outputs): print (outputs[key].keys ()) Cheers Sean outputs keeps track of the last loop only because you're assigning a new dict on every loop. You need to update the current dict instead. try to replace outputs = {command : { capture :fp.readlines() } } with (untested code) if command not in outputs: outputs[command] = {} outputs[command][capture] = fp.readlines() 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: nested dictionaries and functions in data structures.
- Original Message - Thanks for that. It resolved the issue and it was so simple compared to everything else I saw on the net. Only outstanding thing I have to work out is how to execute functions from a dictionary. I will continue searching on the net. Sean This may help you (untested code) class Workers: @staticmethod def ospf(*args, **kwargs): print args, kwargs return 'Bar' @staticmethod def bhp(*args, **kwargs): return 'Foo' outputs = {'ospf' : {1 : {'param1' : 'foo', 'param2' : 'foo2'}} for command, value in outputs.items(): for counter, kwargs in value: func = getattr(Workers, command) # get the function func(**kwargs) # the actual call It would be possible to do it without the *args, **kwargs magic. You can write ospf and bhp with the explicit parameters, however you must make sure you pass the correct number of parameter in the call. 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: word replacing in a paragraph
- Original Message - Hey guys, I'm trying to automate a process by initially creating a standard template and then replace some text fields with variable values. [for example, DATE in the paragraph will be replaced by the current date value. it doesn't have to be a literal word of DATE, DATE in TESTDATE can also be replaced.] Is there some lightweight built-in or 3rd party libraries which are good for such kind of work ? Thanks Frank Jinja2 would be able to do it, with very few line of code. And you get all the features provided by a template engine should you need them to build more advanced templates. 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: Variables in a loop, Newby question
- Original Message - Hello, for the first time I'm trying te create a little Python program. (on a raspberri Pi) I don't understand the handling of variables in a loop with Python. Lets say i want something like this. x = 1 while x 10 var x = x x = x + 1 The results must be: var1 = 1 var2 = 2 enz. until var9 = 9 How do i program this in python? Short story, cause it's almost xmas eve :D: python 2.5: var = {} for i in range(10): var[i] = i print var[1] print var[2] print var var here is a dictionary. I suggest that you read through the python tutorial :) 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: how to develop code using a mix of an existing python-program and console-commands
- Original Message - Am 18.12.13 21:17, schrieb Jean Dubois: I have a python-program which I want to perform its task first, then switch to the python console to experiment with further commands, using what was already defined in the python-program. Excellent way to use/debug a scripting langugage. Use ipython, and then either %run myfile.py I second his suggestion. Additionally, %pdb %run myfile.py will automatically call the ipython debugger on unhandled exceptions, making post mortem debugging a walk in a park. 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: Logger module in python
Original Message - On Wednesday, December 18, 2013 8:52:11 AM UTC+5:30, smileso...@gmail.com wrote: Hi, I am a newbie in python. I am looking for a existing module which I can import in my program to log the objects to a file? I know there is a module Data::Dumper in perl which dumps the objects to file. But not sure about python. Assuming you are looking for a serialization format: If efficiency, easily-at-hand, standard are important then pickle better than json better than yaml If however readability of the output (as the word 'log' suggests) is desired its the other way round: yaml is the most readable, pickle is utterly unreadable -- https://mail.python.org/mailman/listinfo/python-list There's a (better) alternative to pickle: serpent. https://pypi.python.org/pypi/serpent I've been told it was a standard module in python 3, I'm not sure though. Basically it's pickle without the security issue and a readable text format. 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: Struggling for inspiration with lists
- Original Message - Hi I have a list of data that presents as: timestamp: value Timestamps are used solely to determine the sequence of items in the list. I want to find the longest repeated sequence of values in the list. Example, in the following list: data = { 0: d, 1: x, 2: y, 3: t, 4: d, 5: y, 77: g' 78: h, 79: x, 80: y, 206: t, 210: d, 211: x } I would pull out the sequence x-y-t-d (starting at 1 and 79) I need to keep the timestamp / data association because I need to generate output that identifies (a) the longest repeated sequence (b) how many elements in the longest repeated sequence (c) at what timestamps each occurrence started. I'm not sure of the best way, programatically, to aproach this task, which means I'm unsure whether eg a list of tuples ( time, data ) or an OrderedDict keyed on the timestamp is the best starting point. I can make a list of tuples using: d = [ (k,v) for k,v in data ] and with the list of tuples, I can do something like: d.sort( key=lambda tup: tup[0] ) max_start_a = 0 max_start_b = 0 max_len = 0 i = 0 while i len( d ): j = i + 1 while j len( d ): o = 0 while j+o len( d ) and d[i+o][1] == d[j+o][1]: o += 1 if o max_len: max_len = 0 max_start_a = i max_start_b = j j += 1 i += 1 print d[max_start_a][0], d[max_start_b][0], max_len Is there a better way to do this? -- Denis McMahon, denismfmcma...@gmail.com Hi, Depends on what you're meaning by better. If you mean quicker, it seems there is an algorithm in O(n). http://stackoverflow.com/questions/11090289/find-longest-repetitive-sequence-in-a-string You'll need a little bit of work to move from dict / to string / to dict but that shouldn't be a problem. If you didn't mean quicker, I have no idea. If your current code is working, I don't see how it would such wrong that you'd need to change it. 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: seeking a framework to automate router configurations
- Original Message - Hi Pythoners, I'm looking for a tool or framework in which I can do a slight modification to achieve the following task: Asynchronously reset a large number of cisco routers back to their original configurations and push prepared initial configurations to them I did find some similar existing work such as exscript and trigger, however I was stuck in the following two problems : 1. telneting to a non-default port number (other than 23) 2. handling of customized banner messages. can you give some hints on this ? Thanks in advance for your input. Frank -- https://mail.python.org/mailman/listinfo/python-list Hi, If you can ssh on your routers, you may want to look at fabric, a python module that do ssh stuff. You only need to figure out how to reset and reconfigure the router from the shell prompt. 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: How to import Wave files into python?
- Original Message - How exactly do I import a .wav file and run it? also is it possible to run it inside a while loop if so or it just start playing when its run? - Tom 14 -- https://mail.python.org/mailman/listinfo/python-list I think the pygame module should be able to do so. 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: [newbie] trying socket as a replacement for nc
I'm a newbie in Python programming that is very much true, and contrary to what you seem to suggest I did my homework At no point that was my intention, my apologies. If you fixed the syntax error, you should be pretty close to the solution though. 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: [newbie] trying socket as a replacement for nc
Such equipment often implements a telnet protocol. Have use try using the telnetlib module ? http://docs.python.org/2/library/telnetlib.html t = Telnet(host, port) t.write('*IDN?') print t.read_until('Whateverprompt') # you can use read_very_eager also JM Could you tell me how to install telnetlib on a linux-system (it's not available via apt-get install as I see it) kind regards, jean Please keep it on list, some other may have the same install issue or someone could have better insights on installing telnetlib. telnetlib is part of the standard modules in my Debian squeeze(python 2.5). Looking at the doc, it looks like it's available for python 3 as well. Strange that you don't have it. Did you try import telnetlib ? Note that in the code above I forgot the EOF, which is very much dependent of the equipment itself. You may have to write t.write('*IDN?\n') or t.write('IDN?\n\r') 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: [newbie] trying socket as a replacement for nc
Did you try import telnetlib ? Note that in the code above I forgot the EOF, which is very much dependent of the equipment itself. You may have to write t.write('*IDN?\n') or t.write('IDN?\n\r') JM Additionally, here's the code we're using for our signal generators, just to give you a broad idea: def getError(self): error = self._extractRsp(self._sendCmd('SYST:ERR?', 10)) if 'No error' in error: return None else: return error def _sendCmd(self, aCmd, timeout): self.send(str(aCmd) + self.SEND_LFCR) waitPattern = [self.PROMPT] try: index, _, rsp= self._telnet.expect(waitPattern, timeout) except EOFError: self._logger.error('Connection unexpectedly closed while sending/reading/ data.') raise MxgError('Connection unexpectedly closed while sending the command %s' % aCmd) if index == -1: raise MxgError('Timeout occurred while sendind the command %s' % aCmd) return rs def _extractRsp(self, rawRsp): # the returned string should be something like '\r\nresponse\r\nprompt' # or '\r\nprompt' # tries to extract the response only, removing the additional carriage returns and prompt rawRsp = rawRsp.replace(self.READ_LFCR+self.PROMPT, '') if rawRsp.startswith(self.READ_LFCR): rawRsp = rawRsp[2:] return rawRs -- 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: [newbie] trying socket as a replacement for nc
Here is the code: #!/usr/bin/env python import telnetlib host = '10.128.59.63' port = 7000 t = Telnet(host, port) t.write('*IDN?\n') print t.read_until('Whateverprompt') # you can use read_very_eager also and this is the result of executing the code(from which I deduce I have to install telnetlib, but how?) Traceback (most recent call last): File ./nctelnet.py, line 5, in module t = Telnet(host, port) NameError: name 'Telnet' is not defined kind regards, jean t = telnetlib.Telnet(host, port) 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