Re: OOP noob question: Mixin properties
Hi Steven!!! Thanks so much for the pro help, I really do appreciate it. :) On Thu, Dec 13, 2012 at 4:53 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Indentation is important. Please don't remove it. I've added it back in below: Yikes! Sorry about that. I won't do that again in the future. :( Thanks for adding the indentation back. :) The use of @property here doesn't give you any benefit (except, maybe, if you are paid by the line of code). Better to just expose the cache attribute directly, and likewise for the others. If, in the future, you need to turn them into computed properties, you can easily do so. But for now: Ah, great to know! Thank you for the clarification, I needed that. class JSONResponseMixin(object): def __init__(self): self.cache = False self.cache_timeout = 86400 self.cache_key = None and you're done. Beautiful! That's nice. Very simple and clean (I had a feeling my @decorator version was getting a bit wordy). Simply doing this: class JSONResponseMixin(object): cache = False cache_timeout = 86400 # 24 hours. cache_key = None ...works just as good! Not to mention, it's less verbose. In my code above, the cache attributes are defined on a per-instance basis. Each instance will have its own set of three cache* attributes. In the version directly above, there is a single set of cache* attributes shared by all JSONResponseMixin instances. Thank you for pointing this out! I had not realized that this was the case. I'm still kinda new to OOP in Python and Python in general (I'm learning it through Django). Will this make any practical difference? Probably not. Most importantly, if you write: instance = Api() # class includes JSONResponseMixin instance.cache = True then the assignment to an attribute will create a non-shared per-instance attribute which overrides the class-level shared attribute. This is almost certainly the behaviour that you want. So this is a good example of using class attributes to implement shared default state. Whoa, that's cool! There is one common place where the use of shared class attributes can lead to surprising results: if the class attribute is a mutable object such as a list or a dict, it may not behave the way you expect. That is because only *assignment* creates a new per-instance attribute: instance.attribute = spam spam spam # overrides the class attribute while modifying the attribute in place does not: instance.shared_list.append(spam spam spam) # every instance of the class will now see the change Exactly the type of details I was hoping to learn. Thank you so much for taking the time to explain things in such detail and easy to understand way. I really appreciate it. :) Apart from that Gotcha, the use of shared class attributes to implement default behaviour is perfectly acceptable. Awesome! That's good to know. I actually prefer a functional response, up to the point where I'm passing so many arguments to functions that I can't keep track of what's what. Then I refactor into a class. Ah, well that's good to know. There's a part of me that wants to revert back to passing arguments to self.render_to_response(...); after all, there's only 3 of them. On the flip side, if I hadn't explored other options, I wouldn't have learned anything new. Thanks a billion Steven! I owe you one. Have a great holiday. Cheers, Micky -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP noob question: Mixin properties
On Wed, Dec 12, 2012 at 7:49 PM, Micky Hulse mickyhulse.li...@gmail.com wrote: I hope you don't mind that this question involves Django... I'm just looking to improve my core Python skills (so, generic Python examples would be cool). Just experimenting: https://gist.github.com/4279705 I think that will help me achieve my desired end result. I'm open to feedback. Cheers! M -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP noob question: Mixin properties
On Thu, 13 Dec 2012 16:20:51 -0800, Micky Hulse wrote: Learning things here... In my mixin class (a version I wrote for Django) I had this (indentation removed for better list readability): Indentation is important. Please don't remove it. I've added it back in below: class JSONResponseMixin(object): def __init__(self): self._cache = False self._cache_timeout = 86400 self._cache_key = None @property def cache(self): return self._cache @cache.setter def cache(self, value): self._cache = value @cache.deleter def cache(self): del self._cache [...] The use of @property here doesn't give you any benefit (except, maybe, if you are paid by the line of code). Better to just expose the cache attribute directly, and likewise for the others. If, in the future, you need to turn them into computed properties, you can easily do so. But for now: class JSONResponseMixin(object): def __init__(self): self.cache = False self.cache_timeout = 86400 self.cache_key = None and you're done. [...] ...which works! But, then I looked here: https://github.com/django/django/blob/master/django/views/generic/ edit.py#L198 Simply doing this: class JSONResponseMixin(object): cache = False cache_timeout = 86400 # 24 hours. cache_key = None ...works just as good! Not to mention, it's less verbose. Yes. But keep in mind that there is a slight difference between what you have here and what I suggested above. In my code above, the cache attributes are defined on a per-instance basis. Each instance will have its own set of three cache* attributes. In the version directly above, there is a single set of cache* attributes shared by all JSONResponseMixin instances. Will this make any practical difference? Probably not. Most importantly, if you write: instance = Api() # class includes JSONResponseMixin instance.cache = True then the assignment to an attribute will create a non-shared per-instance attribute which overrides the class-level shared attribute. This is almost certainly the behaviour that you want. So this is a good example of using class attributes to implement shared default state. There is one common place where the use of shared class attributes can lead to surprising results: if the class attribute is a mutable object such as a list or a dict, it may not behave the way you expect. That is because only *assignment* creates a new per-instance attribute: instance.attribute = spam spam spam # overrides the class attribute while modifying the attribute in place does not: instance.shared_list.append(spam spam spam) # every instance of the class will now see the change Apart from that Gotcha, the use of shared class attributes to implement default behaviour is perfectly acceptable. I guess I wanted to run my ideas by the Python gurus just to make sure I was not doing crazy stuff here... Seems fine to me. The above seems better than taking the more functional approach: return self.render_to_response(data, cache, cache_timeout, cache_key) Then again, maybe the more functional approach is better for its simplicity? I actually prefer a functional response, up to the point where I'm passing so many arguments to functions that I can't keep track of what's what. Then I refactor into a class. Hopefully I'm not boring ya'll to death. :D No worries :-) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
OOP noob question: Mixin properties
Dear Python Santa gurus, ;D I have this Django mixin: https://github.com/registerguard/django-ad-manager/blob/8628bfe70f6ca68cb7b0373cee7da52613c7531a/ad_manager/mixins.py ...which is used to override render_to_response() so I can output a JSON response (the above code is pretty much straight from the Django docs: https://docs.djangoproject.com/en/1.3/topics/class-based-views/#more-than-just-html). The JSONResponseMixin() gets added to my view class like so: class Api(JSONResponseMixin, BaseDetailView): # ... Within my the mixins.py file, at the top of the file, I've added these constants: CACHE_TIMEOUT = 86400 # 24 hours. CACHE_NAME = 'ad_manager_api' Question(s): I'd like to convert those constants to properties and make my JSONResponseMixin() class more generic and portable. Django aside, could someone provide OOP Python examples of how I could instantiate a mixin Class and set/override its properties before passing data to said mixin? I hope you don't mind that this question involves Django... I'm just looking to improve my core Python skills (so, generic Python examples would be cool). Many thanks in advance! Cheers, Micky -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Noob Question.
Am 05.12.2012 21:24, schrieb Owatch: Thanks a TON for your answer thought, this is exactly what I really hoped for. The problem for me is that I don't actually know anything about writing a function that opens a network socket, and connects to that plugin und asks it for the information you require. That plugin should have some documentation which should tell you something about how to connect to it and how to request information. When you know that you can turn to the python documentation and find out how to do this in python. That's all really beyond me, all I can do is what I did so far, which is make it ask for your temperature value, and then test it to see if its an integer Then (I added this for testing) It asks for any temperature value. And if it exceeds the given limit, it rings an alarm. Until it freezes and becomes unresponsive :D If you have specific problems with code you have written, try to build up a minimal working example that shows the problem plus any error messages/exceptions/stack traces you get back. We might be able to help you with your code. I don't know how to make it 'query' or grab values constantly, if you don't mind my potentially incorrect terminology. This is typically done with some kind of loop, e.g. run = True while run: #do something repeatedly and do run = False if you want to stop pass Greetings Alexander -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Noob Question.
Re On Monday, December 3, 2012 4:19:51 PM UTC+2, Alexander Blinne wrote: Hello, by having a quick look at their website i found a plugin for CoreTemp which acts as a server and can be asked for status information of the cpu. Now your task is really simple: write a little function or class that opens a network socket, connects to that plugin und asks it for the information you require. You just need to find out what network protocol this plugin uses to communicate. If it is no standard protocol for which a higher level module is present (xmlrpc or something), see http://docs.python.org/3/library/socket.html for low level sockets. Greetings Really sorry for the late reply, but I've got a lot going on lately. Thanks a TON for your answer thought, this is exactly what I really hoped for. The problem for me is that I don't actually know anything about writing a function that opens a network socket, and connects to that plugin und asks it for the information you require. That's all really beyond me, all I can do is what I did so far, which is make it ask for your temperature value, and then test it to see if its an integer Then (I added this for testing) It asks for any temperature value. And if it exceeds the given limit, it rings an alarm. Until it freezes and becomes unresponsive :D I don't know how to make it 'query' or grab values constantly, if you don't mind my potentially incorrect terminology. If you know how to do this, or could explain it really step by step to me, I would be ever so thankful. Or even if you know of somewhere which I could ask this. Thanks!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Noob Question.
On Sunday, December 2, 2012 11:44:05 PM UTC+2, Steven D'Aprano wrote: On Sun, 02 Dec 2012 12:33:58 -0800, Owatch wrote: Sorry, but I was redirected here via a thread on another forum concerning where to find help for Python. (Python-forums.org not working for me) I wanted to ask if there was any way I could write a simple Python Temperature program. Where essentially it somehow (Now sure how, I'm a noob remember) read temps off of windows (Providing windows records cpu temps) from their program and then rang an alarm if temperatures exceeded a certain value. I can write the part about the alarm going off. But I have no idea how to have it stream or update values it would grab from that program (whatever it might be). Could you please help, or tell me if its possible. Thanks, Owatch. Yes, it's possible, but if you have no idea which program you want to read temperature data from, what makes you think we would have any better idea? This is a Python forum, not a Windows programs that give temperature data forum. I recommend you start by doing some research into how to read the temperature data, including the name of the program. Once you have that, come back to us for help in using Python. -- Steven Sorry if I didn't specify what program. I was thinking of using Core Temp 1.0. Their website is here: http://www.alcpu.com/CoreTemp/ Or using CPUz. If I've got to choose than I'll take Core Temp 1.0 Is this enough information? If you need to know anything else just say so! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Noob Question.
Hello, by having a quick look at their website i found a plugin for CoreTemp which acts as a server and can be asked for status information of the cpu. Now your task is really simple: write a little function or class that opens a network socket, connects to that plugin und asks it for the information you require. You just need to find out what network protocol this plugin uses to communicate. If it is no standard protocol for which a higher level module is present (xmlrpc or something), see http://docs.python.org/3/library/socket.html for low level sockets. Greetings -- http://mail.python.org/mailman/listinfo/python-list
Python Noob Question.
Sorry, but I was redirected here via a thread on another forum concerning where to find help for Python. (Python-forums.org not working for me) I wanted to ask if there was any way I could write a simple Python Temperature program. Where essentially it somehow (Now sure how, I'm a noob remember) read temps off of windows (Providing windows records cpu temps) from their program and then rang an alarm if temperatures exceeded a certain value. I can write the part about the alarm going off. But I have no idea how to have it stream or update values it would grab from that program (whatever it might be). Could you please help, or tell me if its possible. Thanks, Owatch. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Noob Question.
On Sun, 02 Dec 2012 12:33:58 -0800, Owatch wrote: Sorry, but I was redirected here via a thread on another forum concerning where to find help for Python. (Python-forums.org not working for me) I wanted to ask if there was any way I could write a simple Python Temperature program. Where essentially it somehow (Now sure how, I'm a noob remember) read temps off of windows (Providing windows records cpu temps) from their program and then rang an alarm if temperatures exceeded a certain value. I can write the part about the alarm going off. But I have no idea how to have it stream or update values it would grab from that program (whatever it might be). Could you please help, or tell me if its possible. Thanks, Owatch. Yes, it's possible, but if you have no idea which program you want to read temperature data from, what makes you think we would have any better idea? This is a Python forum, not a Windows programs that give temperature data forum. I recommend you start by doing some research into how to read the temperature data, including the name of the program. Once you have that, come back to us for help in using Python. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Issue with Scrapping Data from a webpage- Noob Question
Hi Fellow Pythoners, I'm trying to collect table data from an authenticated webpage (Tool) to which I have access. I will have the required data after 'click'ing a submit button on the tool homepage. When I inspect the submit button i see form action=/Tool/index.do method=POST Thus the tool's homepage is of the form www.example.com/Tool and on clicking the submit button the data I need will be at www.example.com/Tool/index.do The problem that I'm running into is in my below code is giving me the source of homepage(www.example.com/Tool) and not the of the submitted page( www.example.com/Tool/index.do) url=www.example.com/Tool/index.do request = urllib2.Request(url, data, {'Authorization': Basic + base64.b64encode(%s:%s % (username, password))}) Response_Page=urllib2.urlopen(request).read() Is there a way I can access the source of the submitted page? PS: Sorry for laying out very tiny details on what I'm trying to do, I just wanted to explain myself clearly :) Thanks in advance for your time on this one. Have you checked beautifulsoup? Best, anonhung -- Viktor Orban Prime minister of Hungary http://spreadingviktororban.weebly.com -- http://mail.python.org/mailman/listinfo/python-list
Issue with Scrapping Data from a webpage- Noob Question
Hi Fellow Pythoners, I'm trying to collect table data from an authenticated webpage (Tool) to which I have access. I will have the required data after 'click'ing a submit button on the tool homepage. When I inspect the submit button i see form action=/Tool/index.do method=POST Thus the tool's homepage is of the form www.example.com/Tool and on clicking the submit button the data I need will be at www.example.com/Tool/index.do The problem that I'm running into is in my below code is giving me the source of homepage(www.example.com/Tool) and not the of the submitted page( www.example.com/Tool/index.do) url=www.example.com/Tool/index.do request = urllib2.Request(url, data, {'Authorization': Basic + base64.b64encode(%s:%s % (username, password))}) Response_Page=urllib2.urlopen(request).read() Is there a way I can access the source of the submitted page? PS: Sorry for laying out very tiny details on what I'm trying to do, I just wanted to explain myself clearly :) Thanks in advance for your time on this one. Warm Regards, Abhi -- http://mail.python.org/mailman/listinfo/python-list
Noob Question
Hi All, I'm new to Python, and trying to get python 3.2 installed on Centos 5.6. When I run 'make test', I receive several errors. The readme states that you can generally ignore messages about skipped tests, but as you can see below, some of the tests failed and a number were 'unexpected skips', so I'm not sure if I can go ahead with the install or need to perform further troubleshooting. The output of 'make test' is shown below: 313 tests OK. 5 tests failed: test_argparse test_distutils test_httpservers test_import test_zipfile 31 tests skipped: test_bz2 test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_curses test_dbm_gnu test_dbm_ndbm test_gdb test_gzip test_kqueue test_ossaudiodev test_readline test_smtpnet test_socketserver test_sqlite test_ssl test_startfile test_tcl test_timeout test_tk test_ttk_guionly test_ttk_textonly test_urllib2net test_urllibnet test_winreg test_winsound test_xmlrpc_net test_zipfile64 test_zlib 11 skips unexpected on linux2: test_bz2 test_dbm_gnu test_dbm_ndbm test_gzip test_readline test_ssl test_tcl test_tk test_ttk_guionly test_ttk_textonly test_zlib sys:1: ResourceWarning: unclosed file _io.TextIOWrapper name='/dev/null' mode='a' encoding='UTF-8' make: *** [test] Error 1 Any help would be appreciated. Apologies if this post is to the wrong group. If so, please advise the appropriate group. Thanks in advance, Rob -- http://mail.python.org/mailman/listinfo/python-list
3.2 test failures on Centos 5.6 (was Re: Noob Question)
On 4/19/2011 10:55 AM, Rob McGillivray wrote: I'm new to Python, and trying to get python 3.2 installed on Centos 5.6. When I run 'make test', I receive several errors. Welcome to Python. Newbie lesson 1: write an informative subject line that will catch the attention of people who can answer. (I just happened to open this because it is a slow day so far ;-).) Example: 3.2 test failures on Centos 5.6 If you do not get any better answer than I can provide, I suggest reposting with that subject (my changed line will not be visible to some who have threads collapsed). Lesson 2: provide all relevant info needed to answer. You did pretty good, except: What are you trying to install? A public binary built by someone else for Centos? Or one *you* compiled? If the latter, did you use the official 3.2 source from the site or the latest 3.2.x source from the hg repository? (If either, I suggest trying the other.) The readme states that you can generally ignore messages about skipped tests, but as you can see below, some of the tests failed and a number were 'unexpected skips', so I'm not sure if I can go ahead with the install or need to perform further troubleshooting. I have never built Python or used it on *nix, but I will give some informed guesses ;-). The output of 'make test' is shown below: 5 tests failed: test_argparse test_distutils test_httpservers test_import test_zipfile You need to run each of these in verbose mode to see who severe the failure is. Test_import would be of most concern to me. 11 skips unexpected on linux2: test_bz2 test_dbm_gnu test_dbm_ndbm test_gzip test_readline test_ssl test_tcl test_tk test_ttk_guionly test_ttk_textonly test_zlib These look like things with 3rd party dependencies. tcl/tk/ttk tests depend on finding tcl/tk installed. If you do not want to use the modules, no problem. If you do, sys:1: ResourceWarning: unclosed file_io.TextIOWrapper name='/dev/null' mode='a' encoding='UTF-8' make: *** [test] Error 1 This is a bug either in some test or in the Python shutdown procedure, at least after running the tests. There were other things like this fixed near the end of 3.2 development and it may be fixed now. Any help would be appreciated. Apologies if this post is to the wrong group. If so, please advise the appropriate group. Right place to start. If there are Centos specific issues, you might want to look for a Centos list. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
RE: 3.2 test failures on Centos 5.6 (was Re: Noob Question)
Hi Terry, Much appreciate the pointers! :-) I am trying to install from an RPM downloaded from python.org. I'm pretty new to Linux etc (very pleased to be finally getting into the wide world of OSS), so I'm double-challenged on a number of fronts right now. I will run the failed tests in verbose mode as you recommended and then re-post my findings. Again, appreciate the friendly welcome. :-) Regards, Rob -Original Message- From: python-list-bounces+rob=mymcgillivray@python.org [mailto:python-list-bounces+rob=mymcgillivray@python.org] On Behalf Of Terry Reedy Sent: Tuesday, April 19, 2011 12:59 PM To: python-list@python.org Subject: 3.2 test failures on Centos 5.6 (was Re: Noob Question) On 4/19/2011 10:55 AM, Rob McGillivray wrote: I'm new to Python, and trying to get python 3.2 installed on Centos 5.6. When I run 'make test', I receive several errors. Welcome to Python. Newbie lesson 1: write an informative subject line that will catch the attention of people who can answer. (I just happened to open this because it is a slow day so far ;-).) Example: 3.2 test failures on Centos 5.6 If you do not get any better answer than I can provide, I suggest reposting with that subject (my changed line will not be visible to some who have threads collapsed). Lesson 2: provide all relevant info needed to answer. You did pretty good, except: What are you trying to install? A public binary built by someone else for Centos? Or one *you* compiled? If the latter, did you use the official 3.2 source from the site or the latest 3.2.x source from the hg repository? (If either, I suggest trying the other.) The readme states that you can generally ignore messages about skipped tests, but as you can see below, some of the tests failed and a number were 'unexpected skips', so I'm not sure if I can go ahead with the install or need to perform further troubleshooting. I have never built Python or used it on *nix, but I will give some informed guesses ;-). The output of 'make test' is shown below: 5 tests failed: test_argparse test_distutils test_httpservers test_import test_zipfile You need to run each of these in verbose mode to see who severe the failure is. Test_import would be of most concern to me. 11 skips unexpected on linux2: test_bz2 test_dbm_gnu test_dbm_ndbm test_gzip test_readline test_ssl test_tcl test_tk test_ttk_guionly test_ttk_textonly test_zlib These look like things with 3rd party dependencies. tcl/tk/ttk tests depend on finding tcl/tk installed. If you do not want to use the modules, no problem. If you do, sys:1: ResourceWarning: unclosed file_io.TextIOWrapper name='/dev/null' mode='a' encoding='UTF-8' make: *** [test] Error 1 This is a bug either in some test or in the Python shutdown procedure, at least after running the tests. There were other things like this fixed near the end of 3.2 development and it may be fixed now. Any help would be appreciated. Apologies if this post is to the wrong group. If so, please advise the appropriate group. Right place to start. If there are Centos specific issues, you might want to look for a Centos list. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: 3.2 test failures on Centos 5.6 (was Re: Noob Question)
On 4/19/2011 1:33 PM, Rob McGillivray wrote: I am trying to install from an RPM downloaded from python.org. That puzzles me. For *nix, I do not see .rpm, just tarballs, on http://python.org/download/releases/3.2/ -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob Question
On Tue, Apr 19, 2011 at 7:55 AM, Rob McGillivray r...@motornostixusa.com wrote: Hi All, I'm new to Python, and trying to get python 3.2 installed on Centos 5.6. When I run 'make test', I receive several errors. The readme states that you can generally ignore messages about skipped tests, but as you can see below, some of the tests failed and a number were 'unexpected skips', so I'm not sure if I can go ahead with the install or need to perform further troubleshooting. I'm guessing you need to install development versions of the various libraries on which these modules depend. If they aren't detected during configure, they probably won't be built. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob Question
Yes, Dan is right, it looked for the sources, and you have only binaries on your system. Look in your distribution repositories for the *-devel or alike for the 5 that failed and try again. 2011/4/19 Dan Stromberg drsali...@gmail.com On Tue, Apr 19, 2011 at 7:55 AM, Rob McGillivray r...@motornostixusa.com wrote: Hi All, I'm new to Python, and trying to get python 3.2 installed on Centos 5.6. When I run 'make test', I receive several errors. The readme states that you can generally ignore messages about skipped tests, but as you can see below, some of the tests failed and a number were 'unexpected skips', so I'm not sure if I can go ahead with the install or need to perform further troubleshooting. I'm guessing you need to install development versions of the various libraries on which these modules depend. If they aren't detected during configure, they probably won't be built. -- http://mail.python.org/mailman/listinfo/python-list -- Felipe Bastos Nunes -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question on 2 vs 3 Python releases
Franck Ditter fra...@ditter.org writes: Pardon my noobness (?) but why is there a 2.x and 3.x development teams working concurrently in Python ? Well, Python 2.7 is the last major 2.x release, only bugfixes are done for it, like the 2.7.1 release. Actual developement is in the 3.x branch now. Which one should I choose to start with, to cope with the future ? I started with a good book covering both. The basics are mostly the same anyways. -- http://mail.python.org/mailman/listinfo/python-list
Noob question on 2 vs 3 Python releases
Pardon my noobness (?) but why is there a 2.x and 3.x development teams working concurrently in Python ? I hardly saw that in other languages. Which one should I choose to start with, to cope with the future ? Isn't 3.x supposed to extend 2.y ? This situation is very strange... Thanks for your explanations... franck -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question on 2 vs 3 Python releases
On Sun, Nov 14, 2010 at 1:03 AM, Franck Ditter fra...@ditter.org wrote: Pardon my noobness (?) but why is there a 2.x and 3.x development teams working concurrently in Python ? I hardly saw that in other languages. You haven't heard of the infamous Perl 6? Which one should I choose to start with, to cope with the future ? Read http://wiki.python.org/moin/Python2orPython3 Isn't 3.x supposed to extend 2.y ? Not just extend. It also makes some *backwards-incompatible* removals and revisions, hence the different major version number. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question on 2 vs 3 Python releases
On Sun, Nov 14, 2010 at 1:03 AM, Franck Ditter fra...@ditter.org wrote: Pardon my noobness (?) but why is there a 2.x and 3.x development teams working concurrently in Python ? I hardly saw that in other languages. Which one should I choose to start with, to cope with the future ? Isn't 3.x supposed to extend 2.y ? This situation is very strange... Thanks for your explanations... franck -- http://mail.python.org/mailman/listinfo/python-list Actually, has there ever been a language with a substantial userbase that didn't ever have two (or more) versions at the same time? C has, C++ has, FORTRAN has, perl has, java has... I believe user migrations are just kind of part of being a computer language. That's a significant part of why code doesn't maintain itself. -- http://mail.python.org/mailman/listinfo/python-list
Noob question
Hello? I'm currently installed Ubuntu 8.10. I'm not a Linux person, so I don't know a lot about it. The reason I installed Ubuntu is just for EMAN (http://blake.bcm.tmc.edu/eman/). EMAN 1.8 software requires Python 2.4 not 2.5 which comes with Ubuntu 8.10. I installed Python 2.4 by typing sudo apt-get install python2.4 Still EMAN doesn't work for me. Do I have to downgrade 2.5 to 2.4 or install lower version of Ubuntu? -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question
nanoe...@gmail.com a écrit : Hello? Hi. Ok, first, this is mostly OT here - your question should have gone to either the project's maintainer or any Ubuntu forum / mailing-list/whatever. OT I'm currently installed Ubuntu 8.10. I'm not a Linux person, so I don't know a lot about it. The reason I installed Ubuntu is just for EMAN (http://blake.bcm.tmc.edu/eman/). EMAN 1.8 software requires Python From the doc, it doesn't *require* Python at all: Some others are optional, like boost.python, Python if you need run Pyhton program in EMAN or want to program in Python with EMAN, you can turn this option off by switching ENABLE_PYTHON to off http://blake.bcm.tmc.edu/emanwiki/EMAN_COMPILE_UNIX 2.4 not 2.5 which comes with Ubuntu 8.10. I installed Python 2.4 by typing sudo apt-get install python2.4 You'll probably need python2.4-dev too. Still EMAN doesn't work for me. Did you try to recompile it (eventually providing the path to your python2.4 install) ? Do I have to downgrade 2.5 to 2.4 Not sure this is an option - IIRC, Ubuntu 8.10 depends on Python 2.5. or install lower version of Ubuntu? This would at best be a short/medium-term workaround. OT -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
[following up late] In article 2b3c916e-6908-4b12-933f-8f7bfa86c...@i20g2000prf.googlegroups.com, Russ P. russ.paie...@gmail.com wrote: Fair enough, but for code that is not intended for general public usage (i.e., most code) so-called camelCase is every bit as good if not better than using underscores to divide variable names. It saves a few characters, and in my opinion it's significantly easier to read. Identifiers divided by underscores always appear to me at first glance to be multiple words, and I find that very annoying. So unless you think the standard library will someday include code for air traffic management, I'll stick with camelCase, and I'll thank you for not making an issue of it. You are missing the point: suppose you write a useful library in your air traffic management application, maybe one that does a good job of handling user input. If you have done a proper job of abstracting it from your application as a whole, you could easily publicize it, but it will never get into the standard library unless it meets current PEP8 guidelines. Why fuss about trying to figure out which parts of your application might in the future be published? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Sat, 17 Jan 2009 06:09:29 -0800, Aahz wrote: You are missing the point: suppose you write a useful library in your air traffic management application, maybe one that does a good job of handling user input. If you have done a proper job of abstracting it from your application as a whole, you could easily publicize it, but it will never get into the standard library unless it meets current PEP8 guidelines. Why fuss about trying to figure out which parts of your application might in the future be published? You know, it is quite possible that some people may not care whether or not their code ends up in the standard library. Holding out the possibility of inclusion in the std lib may not be quite the encouragement you expect :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
2009/1/3 Russ P. russ.paie...@gmail.com: So unless you think the standard library will someday include code for air traffic management, I'll stick with camelCase, and I'll thank you for not making an issue of it. Another late comment, sorry, but as an air traffic management safety consultant, I'm quite interested about where in ATM you plan to use Python code, and how you will be meeting the applicable safety standards in the relevant administration. -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
Anyone have something to say about the userio stuff? (If you're going to post something about my coding style, I invite you to do something infinitely more useful: write crapToPep8.py {or is it crap_to_pep8?} to satisfy your sick fetish for consistency.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
Gabriel Genellina gagsl-...@yahoo.com.ar writes: En Mon, 05 Jan 2009 02:03:26 -0200, Roy Smith r...@panix.com escribió: The other day, I came upon this gem. It's a bit of perl embedded in a Makefile; this makes it even more gnarly because all the $'s get doubled to hide them from make: define absmondir $(shell perl -e ' \ sub absmon { my $$a = $$_[0]; \ if ( $$^O =~ m/cygwin|MSWin32/i ) { $$prefix = `/bin/mount -p|awk NR==2{print \\\$$1}`; chomp($$prefix); \ $$a = ($$_[1]||$(PWD)) . /$$a \ unless ( $$a =~ m !^(:?$$prefix|/|[A-Za-z]:)! ); \ } else { $$a = ($$_[1]||$(PWD)) . /$$a unless ( $$a =~ m !^/! ); } \ return unslash(undot(undotdot($$a))); }; \ sub unslash ($$) { $$_[0] =~ s://+:/:g; $$_[0] =~ s:/$$::; return($$_[0]); }; \ sub undot ($$) { $$_[0]=~s:/\./:/:g; return ($$_[0]); }; \ sub undotdot ($$) { my $$in = $$_[0]; \ return ( $$in =~ s:/[^/.][^/]*/\.\.::g )?undotdot($$in):$$in; }; \ print absmon($(1),$(2)); \ ' ) endef Barf-o-rama. I know what it's supposed to do, and I still can't figure it out. Ouch! Me too, when I come to some piece of Perl code I've written some years ago, I invariably think what's all this noise?. Never happens with other languages I've used in the past. I still occassion upon the chance to write some Perl, and even as a full-time developer who works with Python for a living, I relish every opportunity. The funny thing is that I've never had the problem of writing code like this in Perl. The example is a very poor use-case and doesn't reflect on the useful/useless-ness of the language itself but more on the choices of the implementor. Perl is a very useful language overall and when used properly, very powerful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
En Mon, 05 Jan 2009 02:03:26 -0200, Roy Smith r...@panix.com escribió: The other day, I came upon this gem. It's a bit of perl embedded in a Makefile; this makes it even more gnarly because all the $'s get doubled to hide them from make: define absmondir $(shell perl -e ' \ sub absmon { my $$a = $$_[0]; \ if ( $$^O =~ m/cygwin|MSWin32/i ) { $$prefix = `/bin/mount -p|awk NR==2{print \\\$$1}`; chomp($$prefix); \ $$a = ($$_[1]||$(PWD)) . /$$a \ unless ( $$a =~ m !^(:?$$prefix|/|[A-Za-z]:)! ); \ } else { $$a = ($$_[1]||$(PWD)) . /$$a unless ( $$a =~ m !^/! ); } \ return unslash(undot(undotdot($$a))); }; \ sub unslash ($$) { $$_[0] =~ s://+:/:g; $$_[0] =~ s:/$$::; return($$_[0]); }; \ sub undot ($$) { $$_[0]=~s:/\./:/:g; return ($$_[0]); }; \ sub undotdot ($$) { my $$in = $$_[0]; \ return ( $$in =~ s:/[^/.][^/]*/\.\.::g )?undotdot($$in):$$in; }; \ print absmon($(1),$(2)); \ ' ) endef Barf-o-rama. I know what it's supposed to do, and I still can't figure it out. Ouch! Me too, when I come to some piece of Perl code I've written some years ago, I invariably think what's all this noise?. Never happens with other languages I've used in the past. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
My gmail did that. FYI, it wasn't intentional. А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я Paula Poundstone - I don't have a bank account because I don't know my mother's maiden name. On Sun, Jan 4, 2009 at 1:41 AM, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: On Sat, 03 Jan 2009 16:19:58 +0100, Bruno Desthuilliers wrote: But indeed, you obviously cannot add strings with numerics nor concatenate numerics with strings. This would make no sense. The OP comes from a Perl background, which AFAIK allows you to concat numbers to strings and add strings to numbers. That's probably the (mis) feature he was hoping Python had. -- Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Jan 3, 6:41 pm, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: The OP comes from a Perl background, which AFAIK allows you to concat numbers to strings and add strings to numbers. That's probably the (mis) feature he was hoping Python had. That's correct -- and that's been one of the more difficult parts of my transition. Learned C++ in college, spent a few years doing Perl, and now all of a sudden type matters again. It's a very different philosophy, but I'm determined to stick with it until I have an Aha! moment and find something I can do more easily than I can with Perl. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
In article cc87ebf5-5ce1-4fb5-bb2d-cd4bc2426...@q36g2000vbn.googlegroups.com, sprad jsp...@gmail.com wrote: On Jan 3, 6:41 pm, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: The OP comes from a Perl background, which AFAIK allows you to concat numbers to strings and add strings to numbers. That's probably the (mis) feature he was hoping Python had. That's correct -- and that's been one of the more difficult parts of my transition. Learned C++ in college, spent a few years doing Perl, and now all of a sudden type matters again. It's a very different philosophy, but I'm determined to stick with it until I have an Aha! moment and find something I can do more easily than I can with Perl. The Aha! moment comes 6 months from now, when you discover that you can understand the Python code you wrote 6 months ago, but the Perl code you wrote at the same time has become gibberish, even to you. The other day, I came upon this gem. It's a bit of perl embedded in a Makefile; this makes it even more gnarly because all the $'s get doubled to hide them from make: define absmondir $(shell perl -e ' \ sub absmon { my $$a = $$_[0]; \ if ( $$^O =~ m/cygwin|MSWin32/i ) { $$prefix = `/bin/mount -p|awk NR==2{print \\\$$1}`; chomp($$prefix); \ $$a = ($$_[1]||$(PWD)) . /$$a \ unless ( $$a =~ m !^(:?$$prefix|/|[A-Za-z]:)! ); \ } else { $$a = ($$_[1]||$(PWD)) . /$$a unless ( $$a =~ m !^/! ); } \ return unslash(undot(undotdot($$a))); }; \ sub unslash ($$) { $$_[0] =~ s://+:/:g; $$_[0] =~ s:/$$::; return($$_[0]); }; \ sub undot ($$) { $$_[0]=~s:/\./:/:g; return ($$_[0]); }; \ sub undotdot ($$) { my $$in = $$_[0]; \ return ( $$in =~ s:/[^/.][^/]*/\.\.::g )?undotdot($$in):$$in; }; \ print absmon($(1),$(2)); \ ' ) endef Barf-o-rama. I know what it's supposed to do, and I still can't figure it out. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Mon, Jan 5, 2009 at 1:47 PM, sprad jsp...@gmail.com wrote: On Jan 3, 6:41 pm, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: The OP comes from a Perl background, which AFAIK allows you to concat numbers to strings and add strings to numbers. That's probably the (mis) feature he was hoping Python had. I guess perl must have coercing for it's built-in types ? :) *shrugs* To be honest, doing such operations doesn't make much sense to me ... It's difficult to correctly understand what the following expression should evaluate to: a = 2 b = 3 c = foo a + b + c Traceback (most recent call last): File stdin, line 1, in module TypeError: unsupported operand type(s) for +: 'int' and 'str' %d %d %s % (a, b, c) '2 3 foo' That's correct -- and that's been one of the more difficult parts of my transition. Learned C++ in college, spent a few years doing Perl, and now all of a sudden type matters again. It's a very different philosophy, but I'm determined to stick with it until I have an Aha! moment and find something I can do more easily than I can with Perl. As mentioned string formatting is your friend :) cheers James -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
sprad a écrit : I've done a good bit of Perl, but I'm new to Python. I find myself doing a lot of typecasting (or whatever this thing I'm about to show you is called), Actually, it's just plain object instanciation. and I'm wondering if it's normal, or if I'm missing an important idiom. For example: bet = raw_input(Enter your bet) if int(bet) == 0: # respond to a zero bet raw_input() returns a string. If you want an int and the string is supposed to contain a legitimate string representation of an integer, then yes, passing the string to the int object constructor is the right thing to do. I'd just write it a bit diffently: bet = int(raw_input(Enter your bet)) if bet == 0: # code here or even better: def read_int(prompt, err=Sorry, '%s' is not a valid integer): while True: answer = raw_input(prompt) try: return int(answer) except ValueError: print err % answer bet = read_int(Enter your bet) if bet == 0: # code here Or later, I'll have an integer, and I end up doing something like this: print You still have $ + str(money) + remaining May suggest learning about string formatting ? print You still have $%s remaining % money But indeed, you obviously cannot add strings with numerics nor concatenate numerics with strings. This would make no sense. All the time, I'm going int(this) and str(that). Am I supposed to? Depends on the context. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Jan 2, 10:50 pm, Ben Finney bignose+hates-s...@benfinney.id.au wrote: s0s...@gmail.com writes: On Jan 2, 7:20 pm, Ben Finney bignose+hates-s...@benfinney.id.au wrote: They don't need to be creative; they merely need to conform with the naming scheme as laid out in the PEP. If it's something to be included in the standard library, I agree (just for consistency, not because using_underscores is better). But for user code, I prefer mixedCase. That seems superficially like an easy distinction. Indeed, PEP 8 explicitly is meant to apply only to code intended for inclusion in the Python standard library. But consider: Python libraries generally don't get into the standard library until they've had a history of widespread public use as an external library. This helps ensure many of the harder-to-find wrinkles get discovered through wide exposure and ironed out before becoming standard. Code bases, especially library interfaces, that get a lot of use across wide communities are naturally going to have a whole lot of other people's code directly using those interfaces. Interfaces that are so widely used garner a high resistance to change, especially for something as non-functional as a naming convention. Choosing the naming convention for one's code is much easier to do when its usage base is smaller than when that base is larger. Therefore the easiest time to choose when to code in conformance to PEP 8 is right at the start. The best conclusion I can come to from this? Unless you explicitly *never* intend sharing your code with *anyone*, it's best to code all your Python code in accordance with PEP 8 anyway. You then don't have to make the decision about whether this is the time to follow PEP 8 or not; just do it by default, and you avoid the needless pain on those occasions, often unforeseeable at the start, where your code later ends up widely used. -- \ “One of the most important things you learn from the internet | `\ is that there is no ‘them’ out there. It's just an awful lot of | _o__) ‘us’.” —Douglas Adams | Ben Finney Fair enough, but for code that is not intended for general public usage (i.e., most code) so-called camelCase is every bit as good if not better than using underscores to divide variable names. It saves a few characters, and in my opinion it's significantly easier to read. Identifiers divided by underscores always appear to me at first glance to be multiple words, and I find that very annoying. So unless you think the standard library will someday include code for air traffic management, I'll stick with camelCase, and I'll thank you for not making an issue of it. As far as I am concerned, this is one of the most important bits of advice in PEP 8: A Foolish Consistency is the Hobgoblin of Little Minds -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
for each his own. Any more word on userio? On Sat, Jan 3, 2009 at 6:14 PM, Russ P. russ.paie...@gmail.com wrote: On Jan 2, 10:50 pm, Ben Finney bignose+hates-s...@benfinney.id.aubignose%2bhates-s...@benfinney.id.au wrote: s0s...@gmail.com writes: On Jan 2, 7:20 pm, Ben Finney bignose+hates-s...@benfinney.id.aubignose%2bhates-s...@benfinney.id.au wrote: They don't need to be creative; they merely need to conform with the naming scheme as laid out in the PEP. If it's something to be included in the standard library, I agree (just for consistency, not because using_underscores is better). But for user code, I prefer mixedCase. That seems superficially like an easy distinction. Indeed, PEP 8 explicitly is meant to apply only to code intended for inclusion in the Python standard library. But consider: Python libraries generally don't get into the standard library until they've had a history of widespread public use as an external library. This helps ensure many of the harder-to-find wrinkles get discovered through wide exposure and ironed out before becoming standard. Code bases, especially library interfaces, that get a lot of use across wide communities are naturally going to have a whole lot of other people's code directly using those interfaces. Interfaces that are so widely used garner a high resistance to change, especially for something as non-functional as a naming convention. Choosing the naming convention for one's code is much easier to do when its usage base is smaller than when that base is larger. Therefore the easiest time to choose when to code in conformance to PEP 8 is right at the start. The best conclusion I can come to from this? Unless you explicitly *never* intend sharing your code with *anyone*, it's best to code all your Python code in accordance with PEP 8 anyway. You then don't have to make the decision about whether this is the time to follow PEP 8 or not; just do it by default, and you avoid the needless pain on those occasions, often unforeseeable at the start, where your code later ends up widely used. -- \ One of the most important things you learn from the internet | `\ is that there is no 'them' out there. It's just an awful lot of | _o__)'us'. —Douglas Adams | Ben Finney Fair enough, but for code that is not intended for general public usage (i.e., most code) so-called camelCase is every bit as good if not better than using underscores to divide variable names. It saves a few characters, and in my opinion it's significantly easier to read. Identifiers divided by underscores always appear to me at first glance to be multiple words, and I find that very annoying. So unless you think the standard library will someday include code for air traffic management, I'll stick with camelCase, and I'll thank you for not making an issue of it. As far as I am concerned, this is one of the most important bits of advice in PEP 8: A Foolish Consistency is the Hobgoblin of Little Minds -- http://mail.python.org/mailman/listinfo/python-list -- А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
Any more word on userio? None yet, I'm afraid. Should've started a different thread for it - but it's stuck here (in obscurity) forever xd. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Sat, 03 Jan 2009 20:35:25 +, alex goretoy wrote: for each his own. Please don't top-post. Please don't quote the ENTIRE body of text (PLUS doubling it by including a completely useless HTML version) just to add a trivial comment. Trim the text you are replying to. Any more word on userio? I doubt many people care about it. Why don't you write it, put it up on the Cheeseshop, and see if anyone uses it? Just because you think it is useful doesn't mean others do, but if they do, then great. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Sat, 03 Jan 2009 16:19:58 +0100, Bruno Desthuilliers wrote: But indeed, you obviously cannot add strings with numerics nor concatenate numerics with strings. This would make no sense. The OP comes from a Perl background, which AFAIK allows you to concat numbers to strings and add strings to numbers. That's probably the (mis) feature he was hoping Python had. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Noob question: Is all this typecasting normal?
I've done a good bit of Perl, but I'm new to Python. I find myself doing a lot of typecasting (or whatever this thing I'm about to show you is called), and I'm wondering if it's normal, or if I'm missing an important idiom. For example: bet = raw_input(Enter your bet) if int(bet) == 0: # respond to a zero bet Or later, I'll have an integer, and I end up doing something like this: print You still have $ + str(money) + remaining All the time, I'm going int(this) and str(that). Am I supposed to? -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Fri, Jan 2, 2009 at 4:15 PM, sprad jsp...@gmail.com wrote: I've done a good bit of Perl, but I'm new to Python. I find myself doing a lot of typecasting (or whatever this thing I'm about to show you is called), and I'm wondering if it's normal, or if I'm missing an important idiom. For example: bet = raw_input(Enter your bet) if int(bet) == 0: # respond to a zero bet Or later, I'll have an integer, and I end up doing something like this: print You still have $ + str(money) + remaining All the time, I'm going int(this) and str(that). Am I supposed to? The cast to the int is needed. The cast to a string isn't. Use string formatting instead. As an added bonus, you can ensure that you always show 2 digits past the decimal. money = 2.1 print You still have $%0.2f remaining % money You still have $2.10 remaining -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
sprad schrieb: I've done a good bit of Perl, but I'm new to Python. I find myself doing a lot of typecasting (or whatever this thing I'm about to show you is called), and I'm wondering if it's normal, or if I'm missing an important idiom. It is normal, although below you make things needlessly complicated. Python is strongly typed, which is a good thing. It refuses to guess you mean when you multiply a string with a number. Or how a number is to be formatted when printed. For example: bet = raw_input(Enter your bet) if int(bet) == 0: # respond to a zero bet You might better do bet = int(raw_input(Enter your bet)) because then you don't need to later on convert bet again and again. But *one* conversion you need. Or later, I'll have an integer, and I end up doing something like this: print You still have $ + str(money) + remaining This is more concisely with much better control over the output-format (think e.g. digits of a fraction) using string-interpolation. See http://docs.python.org/library/stdtypes.html#string-formatting-operations for an overview. In your case, a simple print You still have $%i remaining % bet does the trick. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
You can use the built-in string formatting options and operations. 2.5: http://www.python.org/doc/2.5.2/lib/typesseq-strings.html 2.6: http://docs.python.org/library/string.html In essence, you can do: print You still have $%i remaining %(money) On Jan 2, 2:15 pm, sprad jsp...@gmail.com wrote: I've done a good bit of Perl, but I'm new to Python. I find myself doing a lot of typecasting (or whatever this thing I'm about to show you is called), and I'm wondering if it's normal, or if I'm missing an important idiom. For example: bet = raw_input(Enter your bet) if int(bet) == 0: # respond to a zero bet Or later, I'll have an integer, and I end up doing something like this: print You still have $ + str(money) + remaining All the time, I'm going int(this) and str(that). Am I supposed to? -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
You might better do bet = int(raw_input(Enter your bet)) because then you don't need to later on convert bet again and again. This is all fine until you give it to an end-user. This is what I picture: $ ./script.py Enter your bet: $10 .. or perhaps ten, all, or a jillion other tainted inputs. Python will try to cast these strings, but will slap you with a ValueError instead (an error of some sort, at least). There needs to be a user_io or sanitize module in the standard library to take care of this stuff. Like: import userio logic = userio.userio() number = logic.getNumeric(blah: ) # will offer the user a re-do in case of bad input number = logic.forceGetNumeric(Enter your bet!: ) # even if input is tainted, will return some number text = logic.getText(blargh: ) # return all text text = logic.setValidText([A-Za-z]) text = logic.forceGetText(blargh: ) # return some text, strips invalid chars ... but there isn't, as far as I know. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Fri, 2 Jan 2009 14:36:04 -0800 (PST) vk vmi...@gmail.com wrote: There needs to be a user_io or sanitize module in the standard library to take care of this stuff. [snip example] Great idea! +1 ... but there isn't, as far as I know. Well, get to it, then. ;) /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
There needs to be a user_io or sanitize module in the standard library to take care of this stuff. [snip] +1 You are sooo right. You know, it is easy to forget about such things after you learn a language, i have written my own input logic, but i remember my __init__ days with python now and the learning curve. Every new user will makes much use of raw_input()[or input 3.0] and has to climb this same little hill every time, you and i do it as second nature. A small module like you describe would be a great addition to the standard library, and heck, i would even use it :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
vk vmi...@gmail.com writes: There needs to be a user_io or sanitize module in the standard library to take care of this stuff. Like: import userio logic = userio.userio() number = logic.getNumeric(blah: ) # will offer the user a re-do in case of bad input number = logic.forceGetNumeric(Enter your bet!: ) # even if input is tainted, will return some number text = logic.getText(blargh: ) # return all text text = logic.setValidText([A-Za-z]) text = logic.forceGetText(blargh: ) # return some text, strips invalid chars ... but there isn't, as far as I know. If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) -- \ “The face of a child can say it all, especially the mouth part | `\of the face.” —Jack Handey | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. atm, I've got a chem final to study for. I'll probably post something resembling useful code tomorrow morning. until then, int(input()) away! -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Fri, 2 Jan 2009 16:16:10 -0800 (PST) vk vmi...@gmail.com wrote: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. FYI: The names themselves aren't he problem at all. They just should be all_lowercase_with_underscores if they're functions or variables. CamelCase (with initial capital!) is reserved for classnames only. /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Jan 2, 6:26 pm, Andreas Waldenburger geekm...@usenot.de wrote: On Fri, 2 Jan 2009 16:16:10 -0800 (PST) vk vmi...@gmail.com wrote: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. FYI: The names themselves aren't he problem at all. They just should be all_lowercase_with_underscores if they're functions or variables. CamelCase (with initial capital!) is reserved for classnames only. /W -- My real email address is constructed by swapping the domain with the recipient (local part). FYI camelCase with __init__ capital is called title case try this: 'hello world.title() -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Fri, 2 Jan 2009 16:44:11 -0800 (PST) r rt8...@gmail.com wrote: On Jan 2, 6:26 pm, Andreas Waldenburger geekm...@usenot.de wrote: On Fri, 2 Jan 2009 16:16:10 -0800 (PST) vk vmi...@gmail.com wrote: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. FYI: The names themselves aren't he problem at all. They just should be all_lowercase_with_underscores if they're functions or variables. CamelCase (with initial capital!) is reserved for classnames only. /W -- My real email address is constructed by swapping the domain with the recipient (local part). FYI camelCase with __init__ capital is called title case try this: OK, since we're smartassing anyway: CamelCase refers specifically to compound words or phrases that are conjoined, that is, written without spaces between the words, where words are separated by writing their respective first letters in capitals. Title case however refers to normal phrases where (space separated) words are capitalized, and no inner capitals occur (unless of course actual CamelCase words are used in the phrase). You even assumed that distinction in your example: 'hello world.title() /W -- My real email address is constructed by swapping the domain with the recipient (local part). -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Jan 3, 11:16 am, vk vmi...@gmail.com wrote: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. atm, I've got a chem final to study for. I'll probably post something resembling useful code tomorrow morning. until then, int(input()) away! Building on the earlier example (entering the amount of money for a bet), consider the following possibilities: 10 $10 USD 10.00 USD 10,00 # many European locales 1 # moving to the high rollers table 10,000 10.000 # European 10T # T - thousand dates: 1/12/35 # 1 December or 12 January? What year? 2035? Perhaps not, if the prompt was 'Enter pensioner's date of birth - '. etc etc ... IOW consider not biting off more than you can chew. Also consider that raw_input is not sufficiently frequently used in real-world applications to warrant a data validation library to be built on top of it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
vk vmi...@gmail.com writes: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. They don't need to be creative; they merely need to conform with the naming scheme as laid out in the PEP. -- \ “One of the most important things you learn from the internet | `\ is that there is no ‘them’ out there. It's just an awful lot of | _o__)‘us’.” —Douglas Adams | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
Ben Finney wrote: vk vmi...@gmail.com writes: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. They don't need to be creative; they merely need to conform with the naming scheme as laid out in the PEP. They don't *need* to do that. It's just a good habit to get into if you plan to write code that gets read and possibly modified by other people. If you write a function called doSomething the PSU won't %...@#%:,,.. carrier lost -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Jan 2, 7:20 pm, Ben Finney bignose+hates-s...@benfinney.id.au wrote: vk vmi...@gmail.com writes: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. They don't need to be creative; they merely need to conform with the naming scheme as laid out in the PEP. If it's something to be included in the standard library, I agree (just for consistency, not because using_underscores is better). But for user code, I prefer mixedCase. +1 for mixedCase! Sebastian -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Jan 2, 6:57 pm, Andreas Waldenburger geekm...@usenot.de wrote: [snip] You even assumed that distinction in your example: 'hello world.title() [snip] sorry, here is TitleCase.py_b2 py 'hello world'.title().replace(' ', '') -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Fri, 02 Jan 2009 21:02:19 -0500, Steve Holden wrote: Ben Finney wrote: vk vmi...@gmail.com writes: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. They don't need to be creative; they merely need to conform with the naming scheme as laid out in the PEP. They don't *need* to do that. They do if you want it accepted into the standard library, which was the hope. Not *my* hope, you understand, but that of the person who suggested it :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
On Jan 2, 6:15 pm, s0s...@gmail.com wrote: On Jan 2, 7:20 pm, Ben Finney bignose+hates-s...@benfinney.id.au wrote: vk vmi...@gmail.com writes: If there were, I would expect it to conform with PEP 8 (get those ugly camelCase names outta there :-) haha, please forgive me. I'll try and think of some more creative names. They don't need to be creative; they merely need to conform with the naming scheme as laid out in the PEP. If it's something to be included in the standard library, I agree (just for consistency, not because using_underscores is better). But for user code, I prefer mixedCase. +1 for mixedCase! Sebastian I agree. I find underscores in variable names to be both ugly and harder to read. At first glance, the underscores are easy to miss. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
etc etc ... IOW consider not biting off more than you can chew. It's possible that I am, but where's the fun without the risk? Good thinking in your post though! I will add get_date at some point, and I've modified get_numeric already. All-right, the moment you've all been waiting for: - http://docs.google.com/View?docid=dgsp7w2t_2gwf447g8 - Provides: 1) user_io.user_io -- get_text(msg) -- filter_get(msg, valid_chars) -- get_numeric(msg) -- bully_numeric(msg) 2) user_io.progress_bar -- ping() -- stop() Read the doc-strings for details. I know it isn't perfect, so just yell at me on this thread if you don't like something and I'll try to fix it. Actually, I'd rather you fix it yourself and THEN yell at me to update the module. have fun! -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
s0s...@gmail.com writes: On Jan 2, 7:20 pm, Ben Finney bignose+hates-s...@benfinney.id.au wrote: They don't need to be creative; they merely need to conform with the naming scheme as laid out in the PEP. If it's something to be included in the standard library, I agree (just for consistency, not because using_underscores is better). But for user code, I prefer mixedCase. That seems superficially like an easy distinction. Indeed, PEP 8 explicitly is meant to apply only to code intended for inclusion in the Python standard library. But consider: Python libraries generally don't get into the standard library until they've had a history of widespread public use as an external library. This helps ensure many of the harder-to-find wrinkles get discovered through wide exposure and ironed out before becoming standard. Code bases, especially library interfaces, that get a lot of use across wide communities are naturally going to have a whole lot of other people's code directly using those interfaces. Interfaces that are so widely used garner a high resistance to change, especially for something as non-functional as a naming convention. Choosing the naming convention for one's code is much easier to do when its usage base is smaller than when that base is larger. Therefore the easiest time to choose when to code in conformance to PEP 8 is right at the start. The best conclusion I can come to from this? Unless you explicitly *never* intend sharing your code with *anyone*, it's best to code all your Python code in accordance with PEP 8 anyway. You then don't have to make the decision about whether this is the time to follow PEP 8 or not; just do it by default, and you avoid the needless pain on those occasions, often unforeseeable at the start, where your code later ends up widely used. -- \ “One of the most important things you learn from the internet | `\ is that there is no ‘them’ out there. It's just an awful lot of | _o__)‘us’.” —Douglas Adams | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question: Is all this typecasting normal?
Unless you explicitly *never* intend sharing your code with *anyone*, it's best to code all your Python code in accordance with PEP 8 anyway. Well said. Let's bury the puppy already. Anyone have something to say about the userio stuff? -- http://mail.python.org/mailman/listinfo/python-list
noob question : library versus normal python files
hello friends, i have a python library(rdflib) that i am using in some project using Google App Engine. I have developed everything using this on my local machine and things work fine. But in my final deployment, i have to use it in source code form rather than in library form. If i remove the library and start using the source code, thing are just not working even if i append the dir of source to the python path. any ideas on how to use the source code for a python library rather than using the library itself ? i tried googling any good tutorial for python libraries but couldn't find one. can someone share a link or something similar ? thanks ravinder thakur -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question : library versus normal python files
On 6 juin, 19:36, रवींदर ठाकुर (ravinder thakur) [EMAIL PROTECTED] wrote: hello friends, i have a python library(rdflib) that i am using in some project using Google App Engine. I have developed everything using this on my local machine and things work fine. But in my final deployment, i have to use it in source code form rather than in library form. What do you mean library form ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question
On Jan 7, 12:09 am, GHZ [EMAIL PROTECTED] wrote: Had the same issue. What you want is: reload() Thanks :) -- http://mail.python.org/mailman/listinfo/python-list
Noob question
Tinkering with Python I find myself often writing scripts and then experimenting with the interactive interpreter, which is really a cool way to learn a language. However, when, after loading a module with import module or from module import * and using it, I make a change to the module file, the changes are not effective after re-importing that same module, and I have to exit the interpreter and restart all over. Isn't there some way to avoid this annoying process? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob question
Had the same issue. What you want is: reload() -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question How do I run a Python script.
CarlP a écrit : How do I run a Python script. usually, it's: $ python /path/to/somescript.py arg1 argN on a command line prompt. I have one that gmail loader needs to run on my email box. Here's the script http://www.marklyon.org/gmail/cleanmbox.py I can't seem to find what I need to run it. I installed python, run the interpreter and the script , but all it will do is say invalid syntax. Am I right if I guess you did something like : [EMAIL PROTECTED] ~ $ python Python 2.4.3 (#1, Mar 12 2007, 23:32:01) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type help, copyright, credits or license for more information. cleanmbox.py testmbox File stdin, line 1 cleanmbox.py testmbox ^ SyntaxError: invalid syntax ?-) FWIW, I ran the script (the correct way) on a copy of a mozilla mbox dir, and it seemed to work. -- http://mail.python.org/mailman/listinfo/python-list
noob question How do I run a Python script.
How do I run a Python script. I have one that gmail loader needs to run on my email box. Here's the script http://www.marklyon.org/gmail/cleanmbox.py I can't seem to find what I need to run it. I installed python, run the interpreter and the script , but all it will do is say invalid syntax. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question How do I run a Python script.
On Jun 28, 12:17 pm, CarlP [EMAIL PROTECTED] wrote: How do I run a Python script. I have one that gmail loader needs to run on my email box. Here's the script http://www.marklyon.org/gmail/cleanmbox.py I can't seem to find what I need to run it. I installed python, run the interpreter and the script , but all it will do is say invalid syntax. Thanks Please post the traceback too. That will aid in helping you. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question How do I run a Python script.
I installed python, run the interpreter and the script... Are you trying to run the script from the interpreter? You _can_ run scripts from the interpreter, but it isn't as simple as typing the name of the script. To me, that is what it sounds like you are trying to do. I don't know what environment you are using, but at the command line (terminal) you should just type the following to run the script: python cleanmbox.py Actually, if you are using *nix use chmod +x chanmbox.py to tell the os it is executable, and then just run cleanbox.py. If you are using windows, then you don't even have to do that, just double click on it. -Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob Question: Force input to be int?
On 23 Sty, 10:59, [EMAIL PROTECTED] wrote: Hello everyone! I have a piece of code that looks like this: if len(BuildList) 0: print The script found %d game directories: % len(BuildList) print num = 0 for i in BuildList: print str(num) ++ i num = num + 1 print print Select a build number from 0 to + str(len(BuildList) - 1) buildNum = int(raw_input('Select build # ')) while buildNum (len(BuildList) -1) or buildNum = -1: print print Error: Invalid build number! print Select a build number from 0 to + str(len(BuildList) - 1) print buildNum = int(raw_input('Select build: ')) The problem is with the while buildNum-loop. If the user enters a non-numeric value in the buildNum input, the scripts throws an exception. I need to constrict the user to ONLY use integers in the input box. How can I solve this issue? Also if you would like to try mentioned approach 'Look before you leap', this code should be quite clear: buildNumber = ('foo', 'bar') n = len(buildNumber) loop = True while loop: input = raw_input('select a build number from 0 to %d: ' % (n-1)) if input.isdigit(): ch = int(input) loop = not ch in range(n) # if ch is NOT in range of [0, n), then it is ok to loop if loop: print 'Error! Invalid build number' print 'Choice: %d' % ch In fact I don't know if it applies to python, but in conventional languages it is a bad habit to use exceptions for every simple test as it takes time to jump around code. So, correct me please. -- http://mail.python.org/mailman/listinfo/python-list
Noob Question: Force input to be int?
Hello everyone! I have a piece of code that looks like this: if len(BuildList) 0: print The script found %d game directories: % len(BuildList) print num = 0 for i in BuildList: print str(num) ++ i num = num + 1 print print Select a build number from 0 to + str(len(BuildList) - 1) buildNum = int(raw_input('Select build # ')) while buildNum (len(BuildList) -1) or buildNum = -1: print print Error: Invalid build number! print Select a build number from 0 to + str(len(BuildList) - 1) print buildNum = int(raw_input('Select build: ')) The problem is with the while buildNum-loop. If the user enters a non-numeric value in the buildNum input, the scripts throws an exception. I need to constrict the user to ONLY use integers in the input box. How can I solve this issue? -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob Question: Force input to be int?
I have a piece of code that looks like this: if len(BuildList) 0: print The script found %d game directories: % len(BuildList) print num = 0 for i in BuildList: print str(num) ++ i num = num + 1 print print Select a build number from 0 to + str(len(BuildList) - 1) buildNum = int(raw_input('Select build # ')) while buildNum (len(BuildList) -1) or buildNum = -1: print print Error: Invalid build number! print Select a build number from 0 to + str(len(BuildList) - 1) print buildNum = int(raw_input('Select build: ')) The problem is with the while buildNum-loop. If the user enters a non-numeric value in the buildNum input, the scripts throws an exception. I need to constrict the user to ONLY use integers in the input box. How can I solve this issue? How about this: while True: try: x = int( raw_input( 'Enter an integer: ' ) ) break except: pass print 'Okay, now I have this integer: %d' % x HTH, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob Question: Force input to be int?
[EMAIL PROTECTED] writes: print Select a build number from 0 to + str(len(BuildList) - 1) buildNum = int(raw_input('Select build # ')) while buildNum (len(BuildList) -1) or buildNum = -1: print print Error: Invalid build number! print Select a build number from 0 to + str(len(BuildList) - 1) print buildNum = int(raw_input('Select build: ')) The problem is with the while buildNum-loop. If the user enters a non-numeric value in the buildNum input, the scripts throws an exception. I need to constrict the user to ONLY use integers in the input box. How can I solve this issue? You can either validate the input string before trying to convert it (look before you leap) or attempt conversion and handle the exception if you get one (it's easier to ask forgiveness than permission). The second pattern is generally preferable since it means you don't duplicate input validation logic all over your program. The below is untested but is a partial rewrite of your code above, intended to illustrate a few normal Python practices (I hope I haven't introduced bugs) besides the input checking: # just loop til you get a valid number, reading the number at the # top of the loop. No need to read it in multiple places. while True: # you don't have to convert int to str for use in a print statement. # the print statement takes care of the conversion automatically. print Select a build number from 0 to, len(BuildList) - 1 buildNumStr = raw_input('Select build # ') # attempt conversion to int, which might fail; and catch the # exception if it fails try: buildNum = int(buildNumStr) except ValueError: buildNum = -1# just treat this as an invalid value # you can say a x b instead of (a x) and (x b) if 0 = buildNum len(BuildList): break # you've got a valid number, so exit the loop # print error message and go back to top of loop print print Error: Invalid build number! -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob Question: Force input to be int?
Ah, thank you for the respone! I have not gotten around to test it yet, but I hope it will work! :) -Daniel 2007-01-23 10:59:37 [EMAIL PROTECTED] wrote in message [EMAIL PROTECTED] Hello everyone! I have a piece of code that looks like this: if len(BuildList) 0: print The script found %d game directories: % len(BuildList) print num = 0 for i in BuildList: print str(num) ++ i num = num + 1 print print Select a build number from 0 to + str(len(BuildList) - 1) buildNum = int(raw_input('Select build # ')) while buildNum (len(BuildList) -1) or buildNum = -1: print print Error: Invalid build number! print Select a build number from 0 to + str(len(BuildList) - 1) print buildNum = int(raw_input('Select build: ')) The problem is with the while buildNum-loop. If the user enters a non-numeric value in the buildNum input, the scripts throws an exception. I need to constrict the user to ONLY use integers in the input box. How can I solve this issue? -- http://mail.python.org/mailman/listinfo/python-list
noob question
where is a good open-source project website? thank-you (sorry for being so annoying)(if I'm annoying)(if not then I'm not sorry) -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question
xandeer wrote: where is a good open-source project website? thank-you (sorry for being so annoying)(if I'm annoying)(if not then I'm not sorry) sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question
http://code.google.com/hosting/ xandeer wrote: where is a good open-source project website? thank-you (sorry for being so annoying)(if I'm annoying)(if not then I'm not sorry) -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Jason Nordwick wrote: *mouth agape* Wow. That really sucks. I make extensive use of reduce. It seems to run more than twice as fast as a for loop. t = Timer('bino.reduceadd(bino.bits)', 'import bino') s = Timer('bino.loopadd(bino.bits)', 'import bino') t.timeit(10) 1.2373670396656564 s.timeit(10) 2.6450051612705039 t.timeit(100) 11.312374896809501 s.timeit(100) 25.817132345032689 where bits = map(lambda x:randint(0,1), xrange(100)) def reduceadd(v): return reduce(add, v) def loopadd(v): sum = 0 for x in v: sum = add(sum, x) return sum (Yes, I know there are better ways to sum up a list, but I just wanted to test the performance of the loop against reduce. In most of my reduce usages, the function passed to reduce is much more complex.) [...] Assuming Guido van Rossum is right and reduce() is only useful for arithmetic expressions (could you show an example where you use it else?), you could take advantage of more built-ins. To spoiler the result of this, the loop-variant is slightly (in this test: 2ms) faster. The results on my amd64 3k+ were: Reduce: 0.5686828074520.56633643382 For-loop: 0.56633643382 #!/usr/bin/env python # # from random import randint from timeit import Timer from operator import add def bits(): return [randint(0,1) for x in xrange(1000)] # use def list comprehension since lambda/map will be removed in Python 3.0, too print bits()[0:5] print bits()[0:5] # it's working. def reducefunc(x): return reduce(add,x) def loopfunc(x): y = 0 for i in x: y += i return y x = bits() print reducefunc(x) print loopfunc(x) # both give proper output print sum(Timer(reducefunc(bits()), from __main__ import bits, reducefunc).repeat(20,100))/20 print sum(Timer(loopfunc(bits()), from __main__ import bits, loopfunc).repeat(20,100))/20 -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
I use reduce to also do indexing, hashing with upsert semantics of lists of key-value pairs, transitioning through a state table, etc... Somebody else pointed out to me how odd it is of Python to be ditching reduce when Guido van Rossum was hired by Google, and Google is literally built on map and reduce (http://en.wikipedia.org/wiki/Mapreduce). Here is a code fragment I pulled from what I am currently working on (with a little modification to make things simple): First build a tree: def byn(a,n): return [[a[i] for i in x] for x in zip(*[range(y,len(a),n) for y in range(n)])] ... def whilep(pred,f,x): ... while pred(x): x = f(x) ... return x ... t = whilep(lambda x:1len(x), lambda x:byn(x,2), map(chr,range(97,97+16))) t ['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]], [[['i', 'j'], ['k', 'l']], [['m', 'n'], ['o', 'p'] Now if I had the list [0,1,0,0,1] and needed to find what letter it encodes: t[0][1][0][0][1] 'j' But sometimes, I want to be able to index branches or the leaves are at different depths, so I essentially have a list of indexes to follow: def indexDepth(a,i): return reduce(lambda x,y: x[y], i, a) ... indexDepth(t,[0,1,0,0,1]) 'j' Also, I completely understand your timings, but you are not timing reduce against a hand coded loop, but instead the operator '+' against the function add, as the function symbol lookup and call seem to have a heavy price. Reduce was one of the nice ways to eliminate some of those lookups. -j [EMAIL PROTECTED] wrote: Jason Nordwick wrote: *mouth agape* Wow. That really sucks. I make extensive use of reduce. It seems to run more than twice as fast as a for loop. t = Timer('bino.reduceadd(bino.bits)', 'import bino') s = Timer('bino.loopadd(bino.bits)', 'import bino') t.timeit(10) 1.2373670396656564 s.timeit(10) 2.6450051612705039 t.timeit(100) 11.312374896809501 s.timeit(100) 25.817132345032689 where bits = map(lambda x:randint(0,1), xrange(100)) def reduceadd(v): return reduce(add, v) def loopadd(v): sum = 0 for x in v: sum = add(sum, x) return sum (Yes, I know there are better ways to sum up a list, but I just wanted to test the performance of the loop against reduce. In most of my reduce usages, the function passed to reduce is much more complex.) [...] Assuming Guido van Rossum is right and reduce() is only useful for arithmetic expressions (could you show an example where you use it else?), you could take advantage of more built-ins. To spoiler the result of this, the loop-variant is slightly (in this test: 2ms) faster. The results on my amd64 3k+ were: Reduce: 0.5686828074520.56633643382 For-loop: 0.56633643382 #!/usr/bin/env python # # from random import randint from timeit import Timer from operator import add def bits(): return [randint(0,1) for x in xrange(1000)] # use def list comprehension since lambda/map will be removed in Python 3.0, too print bits()[0:5] print bits()[0:5] # it's working. def reducefunc(x): return reduce(add,x) def loopfunc(x): y = 0 for i in x: y += i return y x = bits() print reducefunc(x) print loopfunc(x) # both give proper output print sum(Timer(reducefunc(bits()), from __main__ import bits, reducefunc).repeat(20,100))/20 print sum(Timer(loopfunc(bits()), from __main__ import bits, loopfunc).repeat(20,100))/20 -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Jason Nordwick wrote: I use reduce to also do indexing, hashing with upsert semantics of lists of key-value pairs, transitioning through a state table, etc... Somebody else pointed out to me how odd it is of Python to be ditching reduce when Guido van Rossum was hired by Google, and Google is literally built on map and reduce (http://en.wikipedia.org/wiki/Mapreduce). That seems a bit literal. Just because they use a tool called MapReduce that doesn't imply that thay chose to implement it with the Python map() and reduce() functions. It's a distributed application, in case you hadn't noticed ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
That isn't what I meant. If there was a a point (and I'm not really sure that I'm even trying to make one), the point was that Google makes heavy use of reduce-like functionality, essentially implementing a distributed reduce across a cluster. From what I hear, they use a lot of Python and hired van Rossum for a reason. It just seems odd (don't read anything into this than mere cocked eyebrows) that the language designer that they hired and obviously have a lot of trust in would decide that reduce was essentially pointless. Google's distributed reduce seems to point in opposite way. However, if reduce could be rolled into the list comprehension syntax, that would be even better. Or take it that extra step and roll a grouping functionality in there too, then you would have map, reduce, group, and filter all in one construct. You could call it select (joins are merely indexes into other structures). -j Steve Holden wrote: Jason Nordwick wrote: I use reduce to also do indexing, hashing with upsert semantics of lists of key-value pairs, transitioning through a state table, etc... Somebody else pointed out to me how odd it is of Python to be ditching reduce when Guido van Rossum was hired by Google, and Google is literally built on map and reduce (http://en.wikipedia.org/wiki/Mapreduce). That seems a bit literal. Just because they use a tool called MapReduce that doesn't imply that thay chose to implement it with the Python map() and reduce() functions. It's a distributed application, in case you hadn't noticed ... regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Jason Nordwick schrieb: Or without filter: from operator import add def pr(x): print x def cross(x,y): return reduce(add, [[a+b for b in y] for a in x]) x=map(pr, reduce(cross, [map(str,range(1,6))]*5)) [...] reduce(add, list) is the same as sum(list) and is only half as fast as sum: from timeit import Timer sum(Timer(sum(range(500))).repeat(200, 1000))/200 0.055693786500798058 sum(Timer(reduce(add, range(500)), from operator import add).repeat(200, 1000))/200 0.10820861031220445 Also note that reduce will be removed in Python 3000. -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Stargaming: Also note that reduce will be removed in Python 3000. Then let's use it until it lasts! :-) bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
mike_wilson1333 wrote: I would like to generate every unique combination of numbers 1-5 in a 5 digit number and follow each combo with a newline. So i'm looking at generating combinations such as: (12345) , (12235), (4) and so on. What would be the best way to do this? So, basically i'm looking for a list of all combinations of 1-5 in a 5 digit unique number. Also, when I send the list to print there can't be any duplicates of the combos. Thanks, Mike Hi Mike mod5 = ['1','2','3','4','5'] X = [ ''.join([a,b,c,d,e]) for a in mod5 for b in mod5 for c in mod5 for d in mod5 for e in mod5 ] assert len(X) == 5**5 assert len(set(X)) == 5**5#no duplicates Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Gerard Flanagan: mod5 = ['1','2','3','4','5'] X = [ ''.join([a,b,c,d,e]) for a in mod5 for b in mod5 for c in mod5 for d in mod5 for e in mod5 ] A modified version of your one is the faster so far: v = 12345 r = [a+b+c+d+e for a in v for b in v for c in v for d in v for e in v] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Somehow my other response to the list got lost. I'm still learning Python, but this seems much better than my first attempt: def pr(x): print x def cross(x,y): return [a+b for a in x for b in y] x=map(pr, reduce(cross, [map(str,range(1,6))]*5)) -j Stargaming wrote: Jason Nordwick schrieb: Or without filter: from operator import add def pr(x): print x def cross(x,y): return reduce(add, [[a+b for b in y] for a in x]) x=map(pr, reduce(cross, [map(str,range(1,6))]*5)) [...] reduce(add, list) is the same as sum(list) and is only half as fast as sum: from timeit import Timer sum(Timer(sum(range(500))).repeat(200, 1000))/200 0.055693786500798058 sum(Timer(reduce(add, range(500)), from operator import add).repeat(200, 1000))/200 0.10820861031220445 Also note that reduce will be removed in Python 3000. -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Stargaming wrote: Also note that reduce will be removed in Python 3000. What will replace it? -j -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Jason Nordwick: Stargaming wrote: Also note that reduce will be removed in Python 3000. What will replace it? Nothing, I presume. You will have to write a function to find another way to solve problems. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
*mouth agape* Wow. That really sucks. I make extensive use of reduce. It seems to run more than twice as fast as a for loop. t = Timer('bino.reduceadd(bino.bits)', 'import bino') s = Timer('bino.loopadd(bino.bits)', 'import bino') t.timeit(10) 1.2373670396656564 s.timeit(10) 2.6450051612705039 t.timeit(100) 11.312374896809501 s.timeit(100) 25.817132345032689 where bits = map(lambda x:randint(0,1), xrange(100)) def reduceadd(v): return reduce(add, v) def loopadd(v): sum = 0 for x in v: sum = add(sum, x) return sum (Yes, I know there are better ways to sum up a list, but I just wanted to test the performance of the loop against reduce. In most of my reduce usages, the function passed to reduce is much more complex.) -j [EMAIL PROTECTED] wrote: Jason Nordwick: Stargaming wrote: Also note that reduce will be removed in Python 3000. What will replace it? Nothing, I presume. You will have to write a function to find another way to solve problems. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
mike_wilson1333 wrote: I would like to generate every unique combination of numbers 1-5 in a 5 digit number and follow each combo with a newline. So i'm looking at generating combinations such as: (12345) , (12235), (4) and so on. What would be the best way to do this? So, basically i'm looking for a list of all combinations of 1-5 in a 5 digit unique number. Also, when I send the list to print there can't be any duplicates of the combos. Thanks, Mike This is one of those questions that reminded me that I don't know Python. I launched my Python interpreter, and forgot how to even print a string. Duh! Oh well... -- -- There are several things that I will never be: * I will never be attracted to females. * I will never enjoy the company of others. Exactly how these realities bode for my enemy, is not of my concern. -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Jason Nordwick wrote: benchmark here [EMAIL PROTECTED] wrote: Jason Nordwick: Stargaming wrote: Also note that reduce will be removed in Python 3000. What will replace it? Nothing, I presume. You will have to write a function to find another way to solve problems. Bye, bearophile Well, *perhaps* there will be a new function product() -- and there we go having replaced every arithmetical use of reduce() because Guido cannot read them. Nice. Read on: The fate of reduce() in Python 3000 http://www.artima.com/weblogs/viewpost.jsp?thread=98196 -- found on PEP 3100 -- Miscellaneous Python 3.0 Plans http://www.python.org/dev/peps/pep-3100/#id63 Regards, Stargaming -- -- http://mail.python.org/mailman/listinfo/python-list
yet another noob question
I would like to generate every unique combination of numbers 1-5 in a 5 digit number and follow each combo with a newline. So i'm looking at generating combinations such as: (12345) , (12235), (4) and so on. What would be the best way to do this? So, basically i'm looking for a list of all combinations of 1-5 in a 5 digit unique number. Also, when I send the list to print there can't be any duplicates of the combos. Thanks, Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
mike_wilson1333 schrieb: I would like to generate every unique combination of numbers 1-5 in a 5 digit number and follow each combo with a newline. So i'm looking at generating combinations such as: (12345) , (12235), (4) and so on. What would be the best way to do this? So, basically i'm looking for a list of all combinations of 1-5 in a 5 digit unique number. Also, when I send the list to print there can't be any duplicates of the combos. Thanks, Mike Generally, it is range(1, 5) Sincerely, Stargaming -- -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
mike_wilson1333 wrote: I would like to generate every unique combination of numbers 1-5 in a 5 digit number and follow each combo with a newline. So i'm looking at generating combinations such as: (12345) , (12235), (4) and so on. What would be the best way to do this? So, basically i'm looking for a list of all combinations of 1-5 in a 5 digit unique number. Also, when I send the list to print there can't be any duplicates of the combos. Thanks, Mike Hi Mike, this is one of those Somebody must have had this problem before me kind of situations. Google on python combination and you should be well rewarded. :-) Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
mike_wilson1333: I would like to generate every unique combination of numbers 1-5 in a 5 digit number [...] What would be the best way to do this? Ask the Java newsgroup to design a clever algorithm and post it here for pythonification. Ask for the pseudocode, not the Java code. -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Stargaming: Generally, it is range(1, 5) Minus all numbers whose decimal string representation matches [0-9]*[06-9][0-9]* Briljant! -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Stargaming schrieb: mike_wilson1333 schrieb: I would like to generate every unique combination of numbers 1-5 in a 5 digit number and follow each combo with a newline. So i'm looking at generating combinations such as: (12345) , (12235), (4) and so on. What would be the best way to do this? So, basically i'm looking for a list of all combinations of 1-5 in a 5 digit unique number. Also, when I send the list to print there can't be any duplicates of the combos. Thanks, Mike Generally, it is range(1, 5) Sincerely, Stargaming Whoops, I'm sorry. I think I was a little bit too enthusiastic and wow look 'print range' is fun!. You could do a list comprehension over the range thingy. -- http://mail.python.org/mailman/listinfo/python-list
Re: yet another noob question
Stargaming wrote: Stargaming schrieb: mike_wilson1333 schrieb: I would like to generate every unique combination of numbers 1-5 in a 5 digit number and follow each combo with a newline. So i'm looking at generating combinations such as: (12345) , (12235), (4) and so on. What would be the best way to do this? So, basically i'm looking for a list of all combinations of 1-5 in a 5 digit unique number. Also, when I send the list to print there can't be any duplicates of the combos. Thanks, Mike Generally, it is range(1, 5) Sincerely, Stargaming Whoops, I'm sorry. I think I was a little bit too enthusiastic and wow look 'print range' is fun!. You could do a list comprehension over the range thingy. def stoopid_way(start, end): for n in xrange(start, end + 1): # Make a string. s = '%d' % n # Exclude 0's. if '0' in s: continue # Exclude 6-9's. try: int(s, 6) except ValueError: continue yield s Use it like so: # Get all the strings as a list.. data = list(stoopid_way(1, 5)) # ..or print the strings one-by-one.. for s in stoopid_way(1, 5): print s # ..or print one big string, joined by newlines. print '\n'.join(stoopid_way(1, 5)) I originally meant this as a joke and was going to say not to use it. But on my old, slow computer it only takes about a second or two. If that's fast enough for you then it won't do any harm to use it. (Just don't mention my name ;-) ) Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list