ANN: eGenix PyRun - One file Python Runtime 1.3.0
ANNOUNCING eGenix PyRun - One file Python Runtime Version 1.3.0 An easy-to-use single file relocatable Python run-time - available for Linux, Mac OS X and Unix platforms, with support for Python 2.5, 2.6 and 2.7 This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-PyRun-1.3.0-GA.html INTRODUCTION Our new eGenix PyRun combines a Python interpreter with an almost complete Python standard library into a single easy-to-use executable, that does not require a system wide installation and is fully relocatable. eGenix PyRun's executable only needs 11MB, but still supports most Python application and scripts - and it can be further compressed to just 3-4MB using upx. Compared to a regular Python installation of typically 100MB on disk, this makes eGenix PyRun ideal for applications and scripts that need to be distributed to many target machines, client installations or customers. It makes installing Python on a Unix based system as simple as copying a single file. We have been using the product internally in our mxODBC Connect Server since 2008 with great success and have now extracted it into a stand-alone open-source product. We provide both the source archive to build your own eGenix PyRun, as well as pre-compiled binaries for Linux, FreeBSD and Mac OS X, as 32- and 64-bit versions. The binaries can be downloaded manually, or you can let our automatic install script install-pyrun take care of the installation: ./install-pyrun dir and you're done. Please see the product page for more details: http://www.egenix.com/products/python/PyRun/ NEWS This is a new minor release of eGenix PyRun, which comes with updates to the latest Python releases and includes a number of compatibility enhancements. New Features * Upgraded eGenix PyRun to work with and use Python 2.7.5 per default. * Upgraded eGenix PyRun to use Python 2.6.8 as default Python 2.6 version. * PyRun will now create a symlink from pyrunX.X to pythonX.X and pyrunX.X to python in the bin/ dir to enhance compatibility with scripts and applications that hardwire the name of the Python interpreter to python. Other Changes - * Removed the compiler package from being compiled into PyRun. If needed, it can be installed separately. Note that the compiler package needs the parser module which is not compiled into PyRun either, but is still available as extension module. * Removed the Tkinter Python module from being compiled into PyRun. If needed, it can be installed separately. Note that the Tkinter module needs the _tkinter C module, which is not compiled into PyRun either, but is still available as extension module. * Fixed sys.argv when using interactive mode to default to ['']. * All eGenix PyRun distribution packages are now GPG signed with our release key and come with MD5 and SHA1 hashes to check for download corruption. install-pyrun Quick Installation Enhancements - Since version 1.1.0, eGenix PyRun includes a shell script called install-pyrun, which greatly simplifies installation of eGenix PyRun. It works much like the virtualenv shell script used for creating new virtual environments (except that there's nothing virtual about PyRun environments). https://downloads.egenix.com/python/install-pyrun With the script, an eGenix PyRun installation is as simple as running: ./install-pyrun targetdir We have enhanced this script somewhat since the last release: * install-pyrun now defaults to always installing the most recent setuptools and pip versions from PyPI. * install-pyrun now installs setuptools instead of distribute, after the two projects got merged and continued under the older name. * Added new option --pyrun-executable to define an alternative name for the executable, which is then also used when installing setuptools and pip, e.g. python for even better compatibility with standard Python. * install-run will now prefer curl over wget when downloading packages from PyPI. * install-pyrun local distribution options will now also work with relative paths. * install-pyrun now defaults to installing setuptools 1.1.1 and pip 1.4.1 when looking for local downloads of these tools. * The short options in install-pyrun now also have corresponding long option names. Other Changes - * Fixed SyntaxWarning in pyrunX.X: name 'pyrun_script' is assigned to before global declaration global pyrun_script Presentation at EuroPython 2012 --- Marc-André Lemburg, CEO of
ANN: eGenix PyRun - One file Python Runtime 1.3.0
ANNOUNCING eGenix PyRun - One file Python Runtime Version 1.3.0 An easy-to-use single file relocatable Python run-time - available for Linux, Mac OS X and Unix platforms, with support for Python 2.5, 2.6 and 2.7 This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-PyRun-1.3.0-GA.html INTRODUCTION Our new eGenix PyRun combines a Python interpreter with an almost complete Python standard library into a single easy-to-use executable, that does not require a system wide installation and is fully relocatable. eGenix PyRun's executable only needs 11MB, but still supports most Python application and scripts - and it can be further compressed to just 3-4MB using upx. Compared to a regular Python installation of typically 100MB on disk, this makes eGenix PyRun ideal for applications and scripts that need to be distributed to many target machines, client installations or customers. It makes installing Python on a Unix based system as simple as copying a single file. We have been using the product internally in our mxODBC Connect Server since 2008 with great success and have now extracted it into a stand-alone open-source product. We provide both the source archive to build your own eGenix PyRun, as well as pre-compiled binaries for Linux, FreeBSD and Mac OS X, as 32- and 64-bit versions. The binaries can be downloaded manually, or you can let our automatic install script install-pyrun take care of the installation: ./install-pyrun dir and you're done. Please see the product page for more details: http://www.egenix.com/products/python/PyRun/ NEWS This is a new minor release of eGenix PyRun, which comes with updates to the latest Python releases and includes a number of compatibility enhancements. New Features * Upgraded eGenix PyRun to work with and use Python 2.7.5 per default. * Upgraded eGenix PyRun to use Python 2.6.8 as default Python 2.6 version. * PyRun will now create a symlink from pyrunX.X to pythonX.X and pyrunX.X to python in the bin/ dir to enhance compatibility with scripts and applications that hardwire the name of the Python interpreter to python. Other Changes - * Removed the compiler package from being compiled into PyRun. If needed, it can be installed separately. Note that the compiler package needs the parser module which is not compiled into PyRun either, but is still available as extension module. * Removed the Tkinter Python module from being compiled into PyRun. If needed, it can be installed separately. Note that the Tkinter module needs the _tkinter C module, which is not compiled into PyRun either, but is still available as extension module. * Fixed sys.argv when using interactive mode to default to ['']. * All eGenix PyRun distribution packages are now GPG signed with our release key and come with MD5 and SHA1 hashes to check for download corruption. install-pyrun Quick Installation Enhancements - Since version 1.1.0, eGenix PyRun includes a shell script called install-pyrun, which greatly simplifies installation of eGenix PyRun. It works much like the virtualenv shell script used for creating new virtual environments (except that there's nothing virtual about PyRun environments). https://downloads.egenix.com/python/install-pyrun With the script, an eGenix PyRun installation is as simple as running: ./install-pyrun targetdir We have enhanced this script somewhat since the last release: * install-pyrun now defaults to always installing the most recent setuptools and pip versions from PyPI. * install-pyrun now installs setuptools instead of distribute, after the two projects got merged and continued under the older name. * Added new option --pyrun-executable to define an alternative name for the executable, which is then also used when installing setuptools and pip, e.g. python for even better compatibility with standard Python. * install-run will now prefer curl over wget when downloading packages from PyPI. * install-pyrun local distribution options will now also work with relative paths. * install-pyrun now defaults to installing setuptools 1.1.1 and pip 1.4.1 when looking for local downloads of these tools. * The short options in install-pyrun now also have corresponding long option names. Other Changes - * Fixed SyntaxWarning in pyrunX.X: name 'pyrun_script' is assigned to before global declaration global pyrun_script Presentation at EuroPython 2012 --- Marc-André Lemburg, CEO of
Re: How to split with \ character, and licence copyleft mirror of �
On 6 Sep 2013 07:18, Terry Reedy tjre...@udel.edu wrote: On 9/5/2013 11:33 PM, Tim Roberts wrote: random...@fastmail.us wrote: Of course, in 99% of situations where you can use a windows pathname in Python, you are free to use it with a forward slash instead of a backslash. This is actually worth repeating, because it's not well known. ALL Windows APIs handle forward and backward slashes interchangably. It is only the command interpreter that requires the backslash. and only for the path the the command, when needed, and not for the arguments of the command. Example, in a python development directory pcbuild\python_d tools/scripts/patchcheck.py Interesting. I was pretty sure that forward slashes were allowed in this situation, just that tab completion didn't work unless you used backslashes. Well, fortunately I'm not able to check that these days. -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On 09/10/13 09:09, Steven D'Aprano wrote: What design mistakes, traps or gotchas do you think Python has? My favourite gotcha is this: elt, = elts It's a nice and compact way to do both: assert len(elts) == 0 elt = elts[0] but it sure looks strange at first sight. As a bonus, it works on any iterable, not just ones that support __getitem__. burak -- https://mail.python.org/mailman/listinfo/python-list
Telnet to remote system and format output via web page
Hi I would like to create a web app using flask or cgi library along with telnetlib to telnet to specific servers and execute commands and retrieve the output. The output will then be formatted and outputted to a webpage . . Is this the best way of getting info from a remote system to be output to a web page? Is flask over kill for project like this ? Thanks, Kenroy -- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
Hello, William On 09/11/2013 06:39 AM, William Bryant wrote: user_input1 = input(prompt) I take it you are using Python 3.x . If that's not the case, take a look at raw_input(). def NOS(): if user_input1 == String or user_input1 == string or user_input1 == STRING or user_input1 == s or user_input1 == S or user_input1 == str: print(a) What if you create a list containing these, and then you check if the user_input is contained in that list. But before that, get the lower-case of it so you don't deal with String sTring string, s, S, etc... Something like this You add this to the variables you are using section string_list = ['string', 's'] When you want to check the check if user_input.lower() in string_list: {your_code_here} elif user_input1 == Number or user_input1 == number or user_input1 == NUMBER or user_input1 == N or user_input1 == N or user_input1 == int or user_input1 == num: print(a) Same goes with that But some questions: 1 - Why does the user have to specify that, why doesn't the program itself tell if it is a string or a number ? You just give it the data and it's up to him to tell. 2 - What is it you are trying to accomplish: Maybe there are shortcuts or better ways to do things. -- ~Jugurtha Hadjar, -- https://mail.python.org/mailman/listinfo/python-list
Re: print function and unwanted trailing space
On Sat, 31 Aug 2013, candide wrote: # - for i in range(5): print(i, end=' ') # - The last ' ' is unwanted print() # - Then why not define end='' instead? -W -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Tue, 10 Sep 2013, Ben Finney wrote: The sooner we replace the erroneous “text is ASCII” in the common wisdom with “text is Unicode”, the better. I'd actually argue that it's better to replace the common wisdom with text is binary data, and we should normally look at that text through Unicode eyes. A little less catchy, but more accurate ;) -W-- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
On 11/9/2013 01:39, William Bryant wrote: On Wednesday, September 11, 2013 5:11:23 PM UTC+12, John Gordon wrote: In ef8de6db-5f35-4d07-8306-bcec47b1e...@googlegroups.com William Bryant gogobe...@gmail.com writes: Hey, I am very new to python, I am 13 years old. I want to be able to make = a program the caculates the mean, meadian and mode. When i run the program,= an input field pops up and says 'Does your list contain, a number or a str= ing?' like I want it to, but when I type in something that is not one of va= lid field options: String or string or STRING or s or S or str = etc. Thanks for quoting some context. However, since you're using buggy googlegroups, please either constrain your quoting to a couple of lines, or fix its display to NOT doublespace everything. See http://wiki.python.org/moin/GoogleGroupsPython Thanks so much for putting your time into helping me!! It worked! Could you tell me if I did anything wrong this time? :) #- Variables that I am using, including the list. -# num_or_string = amount_numbers = [] List = [] prompt = Does your list contain, a number or a string? #- Functions that I am using. -# user_input1 = input(prompt) user_input1 This last line does nothing useful. You may be confused because in the debugger, a lone expression getes its value printed. But that's a debugger feature not a language one. If you want to see what got input, you'd want to use print() function. Looks like the second function is identical to the first. if I'm right, then just change the NOS2 into NOS1, and save lots of redundancy. def NOS(): if user_input1 == String or user_input1 == string or user_input1 == STRING or user_input1 == s or user_input1 == S or user_input1 == str: print(a) elif user_input1 == Number or user_input1 == number or user_input1 == NUMBER or user_input1 == N or user_input1 == N or user_input1 == int or user_input1 == num: print(a) else: global user_input2 global prompt prompt = You did not enter a valid field, :P Sorry. user_input2 = input(prompt) user_input2 NOS2() Here you're using the recursive call to NOS() to substitute for a loop. Recursion is very useful, but in this case, it hides what's really happening, and it prevents you from writing a conventional function with parameters and return value. I don't know what NOS is supposed to stand for, but it's generally useful if a function does a simply described single thing. In this case, it gets input from the user, and asks the user repeatedly till he/she gets it right. So the function should do its own input, and not expect the top-level code to already have asked once. Something like: SOMETHING = [ list of the valid inputs ] def query_user(prompt): while true: udata = input(prompt) ifudata.lower() in SOMETHING return udata print(Invalid field, sorry) And now you call this function the same way you would have called input() function: user_input1 = query_user(Does your list contain, a number or a string?) NOS() -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On 11/9/2013 07:42, Wayne Werner wrote: On Tue, 10 Sep 2013, Ben Finney wrote: The sooner we replace the erroneous “text is ASCII” in the common wisdom with “text is Unicode”, the better. I'd actually argue that it's better to replace the common wisdom with text is binary data, and we should normally look at that text through Unicode eyes. A little less catchy, but more accurate ;) -W Text is unicode, but text files are binary, and need to be decoded on read, and encoded on write. Most other external textual data is also binary, and similarly need to be converted before use -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: How can I remove the first line of a multi-line string? (SOLVED)
On 2 Sep 2013 18:13, Roy Smith r...@panix.com wrote: In article mailman.500.1378139057.19984.python-l...@python.org, Anthony Papillion papill...@gmail.com wrote: On 09/02/2013 11:12 AM, Chris “Kwpolska” Warrick wrote: On Mon, Sep 2, 2013 at 6:06 PM, Anthony Papillion papill...@gmail.com wrote: Hello Everyone, I have a multi-line string and I need to remove the very first line from it. How can I do that? I looked at StringIO but I can't seem to figure out how to properly use it to remove the first line. Basically, I want to toss the first line but keep everything else. Can anyone put me on the right path? I know it is probably easy but I'm still learning Python and don't have all the string functions down yet. Thanks, Anthony -- http://mail.python.org/mailman/listinfo/python-list Use split() and join() methods of strings, along with slicing. Like this: fullstring = foo bar baz sansfirstline = '\n'.join(fullstring.split('\n')[1:]) The last line does this: 1. fullstring.split('\n') turns it into a list of ['foo', 'bar', 'baz'] 2. the [1:] slice removes the first element, making it ['bar', 'baz'] 3. Finally, '\n'.join() turns the list into a string separated by newlines (bar baz) This, of course, worked like a charm. I really need to study the string methods. In the work I'm doing they are going to come in very handy. Thank you, Chris! Let me toss out a couple of other possibilities. Not necessarily better, but if you're learning about strings, you might as well learn some other ways to do it: s = foo bar baz print using index... i = s.index('\n') print s[i+1:] print using regex... import re print re.sub(r'^[^\n]*\n', '', s) I'll admit, the split/slice/join solution is probably the easiest to implement (and to understand when you're reading the code). But, it copies all the data twice; once when split() runs, and again when join() runs. Both the index and regex solutions should only do a single copy. For huge strings, this might matter. For a three-liner as in your example, it doesn't make any difference. Is there not a limit argument to str.split? This should be trivial. first, rest = multiline_str.split('\n', 1) -- https://mail.python.org/mailman/listinfo/python-list
Re: How can I remove the first line of a multi-line string? (SOLVED)
On 9/11/2013 8:08 AM, Fábio Santos wrote: Is there not a limit argument to str.split? This should be trivial. Yes, I posted an example using it the first day. I also showed how to use iter and next with files and avoid copying. first, rest = multiline_str.split('\n', 1) This does not work right is there is no '\n' Then someone pointed out first, dummy, rest = partition('\n') which does work with no '\n' -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
global variable across modules
Hi , I'm trying to understand using global variable across different modules.Here is what i have tried so far without much success.Please ignore any indentation issue in the below code. Filename:Test1.py Debug_Value = import Test2 def globalValmethod(): global Debug_Value Debug_Value =10 Test2.globalValTest() globalValmethod() -Execute the method Filename:Test2.py import Test1 from Test1 import * def globalValTest() print Golabal Value Debug_Value In Test2.py file I wanted to print the global value ,Debug_Value as 10.I'm not getting expected result.Please can any one point where exactly i'm doing wrong. Similarly , how can i use global variable inside a class and use the same value of global variable in different class?Is that possible?if Yes please give me some pointers on implementing. Best Regards, Chandan -- https://mail.python.org/mailman/listinfo/python-list
Re: Telnet to remote system and format output via web page
- Original Message - Hi I would like to create a web app using flask or cgi library along with telnetlib to telnet to specific servers and execute commands and retrieve the output. The output will then be formatted and outputted to a webpage . . Is this the best way of getting info from a remote system to be output to a web page? Is flask over kill for project like this ? Thanks, Kenroy -- https://mail.python.org/mailman/listinfo/python-list I never used Flask, but most of python web framework provide an easy/quick way of setting up a web application server. So I'd say Flask is just fine. What concerns me is the telnet protocol you plan to use for remote execution. Do you have any other options ? are you trying to execute on a remote unix like system ? Anyway if you must stick with telnet, I don't see anything wrong in your plan, Flask + telnetlib should do the trick. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: Telnet to remote system and format output via web page
On 09/11/2013 11:45 AM, Kenroy Bennett wrote: Hi I would like to create a web app using flask or cgi library along with telnetlib to telnet to specific servers and execute commands and retrieve the output. The output will then be formatted and outputted to a webpage . Is security an issue ? How sensitive is the information you are querying ? Must it be Telnet ? -- ~Jugurtha Hadjar, -- https://mail.python.org/mailman/listinfo/python-list
why syntax change in lambda
In py2.7 this was accepted, but not in py3.3. Is this intentional? It seems to violate the 'principle' that extraneous parentheses are usually allowed/ignored In [1]: p = lambda x: x In [2]: p = lambda (x): x File ipython-input-2-2b94675a98f1, line 1 p = lambda (x): x ^ SyntaxError: invalid syntax -- https://mail.python.org/mailman/listinfo/python-list
Re: How can I remove the first line of a multi-line string? (SOLVED)
In article mailman.244.1378901307.5461.python-l...@python.org, Fábio Santos fabiosantos...@gmail.com wrote: One suggested solution: sansfirstline = '\n'.join(fullstring.split('\n')[1:]) To which I suggested a couple of alternatives: i = s.index('\n') print s[i+1:] [...] print re.sub(r'^[^\n]*\n', '', s) I'll admit, the split/slice/join solution is probably the easiest to implement (and to understand when you're reading the code). But, it copies all the data twice; once when split() runs, and again when join() runs. Both the index and regex solutions should only do a single copy. For huge strings, this might matter. For a three-liner as in your example, it doesn't make any difference. Is there not a limit argument to str.split? This should be trivial. first, rest = multiline_str.split('\n', 1) This certainly prevents the extra splitting and re-compositing of the additional lines. One thing to watch out for is that split(s, 1) does *at most* 1 split. If the original string didn't have any newlines, you would end up with a single-item list and the unpack would fail. You can get around that with: rest = multiline_str.split('\n', 1)[-1] but that's kind of cryptic. Looking back at my solutions suggested above, s.index() fails in the same situation (throws ValueError). The regex solution works fine, once again proving that 1970's technology is still superior to all this newfangled stuff. A coworker recently introduced me to what is apparently a classic essay (http://www.team.net/mjb/hawg.html). If Unix is the Hole Hawg of operating systems, then regexes are the Hole Hawg of string processing tools. Those of us who grew up around them, appreciate their power and have learned how to use them without chopping off any fingers. And we look on with a mix of amusement and pity at the current crop of programmers who play with index(), split(), startswith(), rpartition(), etc and think they're using real tools :-) For the record, I have never used a Hole Hawg. I do, however, own a Milwaukee 1/2 drill. Which also comes with the screw-in handle for two-handed operation. I've had that get away from me a couple of times, so I figure it's about my limit. Torque is a wonderful thing until the thing you're drilling into weighs more than you do. -- https://mail.python.org/mailman/listinfo/python-list
Re: why syntax change in lambda
On 11 September 2013 14:03, Neal Becker ndbeck...@gmail.com wrote: In py2.7 this was accepted, but not in py3.3. Is this intentional? It seems to violate the 'principle' that extraneous parentheses are usually allowed/ignored In [1]: p = lambda x: x In [2]: p = lambda (x): x File ipython-input-2-2b94675a98f1, line 1 p = lambda (x): x ^ SyntaxError: invalid syntax I guess it's related to the removal of auto-unpacking of arguments. i.e. in 2.x: f = lambda (x, y), z: (x, y, z) f([1, 2], 3) (1, 2, 3) However this was removed in 3.x so f = lambda (x, y), z: (x, y, z) File stdin, line 1 f = lambda (x, y), z: (x, y, z) ^ SyntaxError: invalid syntax Removing that feature would allow a simplification of the lambda syntax that would have no need to admit any kind of brackets. Oscar -- https://mail.python.org/mailman/listinfo/python-list
Python in XKCD today
http://xkcd.com/1263/ -- https://mail.python.org/mailman/listinfo/python-list
Re: global variable across modules
On Wed, Sep 11, 2013 at 10:50 PM, chandan kumar chandan_...@yahoo.co.in wrote: In Test2.py file I wanted to print the global value ,Debug_Value as 10.I'm not getting expected result.Please can any one point where exactly i'm doing wrong. Similarly , how can i use global variable inside a class and use the same value of global variable in different class?Is that possible?if Yes please give me some pointers on implementing. Python simply doesn't have that kind of global. What you have is module-level variables [1] which you can then import. But importing is just another form of assignment: # Test1.py Debug_Value = # Test2.py from Test1 import * # is exactly equivalent to Debug_Value = It simply sets that in Test2's namespace. There's no linkage across. (By the way, I strongly recommend NOT having the circular import that you have here. It'll make a mess of you sooner or later; you actually, due to the way Python loads things, have two copies of one of your modules in memory.) When you then reassign to Debug_Value inside Test1, you disconnect it from its previous value and connect it to a new one, and the assignment in the other module isn't affected. Here's a much simpler approach: # library.py foo = 0 def bar(): global foo foo += 1 # application.py import library library.bar() print(library.foo) This has a simple linear invocation sequence: you invoke the application from the command line, and it calls on its library. No confusion, no mess; and you can reference the library's globals by qualified name. Everything's clear and everything works. ChrisA [1] They're not really variables, they're name bindings. But close enough for this discussion. -- https://mail.python.org/mailman/listinfo/python-list
Re: Telnet to remote system and format output via web page
I would use something like fabric to automatically login to hosts via ssh then parse the data myself to generate static HTML pages in a document root. Having a web app execute remote commands on a server is so wrong in many ways. Sent from my iPhone On Sep 11, 2013, at 8:56 AM, Jugurtha Hadjar jugurtha.had...@gmail.com wrote: On 09/11/2013 11:45 AM, Kenroy Bennett wrote: Hi I would like to create a web app using flask or cgi library along with telnetlib to telnet to specific servers and execute commands and retrieve the output. The output will then be formatted and outputted to a webpage . Is security an issue ? How sensitive is the information you are querying ? Must it be Telnet ? -- ~Jugurtha Hadjar, -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
better and user friendly IDE recommended?
Hey i am a programmer but new to python. Can anyone guide me in knowing which is a better IDE used to develop web related apps that connect to DB using python? -- https://mail.python.org/mailman/listinfo/python-list
Send alt key to subprocess.PIPE stdin
How do I send the command 'Alt+D' to subprocess.PIPE? My code is import subprocess rsconfig = subprocess.Popen([C:\Program Files\Photometrics\PVCam64\utilities\RSConfig\RSConfig.exe, ],stdin=subprocess.PIPE) rsconfig.stdin.write('Alt+D') Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On 2013-09-11, Burak Arslan burak.ars...@arskom.com.tr wrote: On 09/10/13 09:09, Steven D'Aprano wrote: What design mistakes, traps or gotchas do you think Python has? My favourite gotcha is this: elt, = elts It's a nice and compact way to do both: assert len(elts) == 0 elt = elts[0] I'm confused. Your rewrite looks like an assertion error or an IndexError. -- Neil Cerutti -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Thu, Sep 12, 2013 at 12:32 AM, Neil Cerutti ne...@norwich.edu wrote: On 2013-09-11, Burak Arslan burak.ars...@arskom.com.tr wrote: My favourite gotcha is this: elt, = elts It's a nice and compact way to do both: assert len(elts) == 0 elt = elts[0] I'm confused. Your rewrite looks like an assertion error or an IndexError. Presumably he meant to assert that the length is 1. If elts is a list, then yes, these are equivalent, though the expanded form is actually a bit different (since any iterable can be used). ChrisA -- https://mail.python.org/mailman/listinfo/python-list
TypeError in date_parse.py
Hello, I'm running an application using python 2.7 with django 1.5 and when posting a page I get the error TypeError I guess it is something related to timestamps? Below I paste part of the code I think is causing the problem and the stacktace I see Any help is welcome, Thanks! Paula = # Compute duration for this item. duration = None if end_timestamp and start_timestamp: start_datetime = datetime.fromtimestamp(float(start_timestamp)) end_datetime = datetime.fromtimestamp(float(end_timestamp)) duration = end_datetime - start_datetime = POST Request URL: http://127.0.0.1:8000/appraise/evaluation/7b31d05e50584d2b92b4a04d85e68ce3/ Django Version: 1.5.2 Exception Type: TypeError Exception Value: expected string or buffer Exception Location: /usr/local/lib/python2.7/dist-packages/django/utils/dateparse.py in parse_time, line 50 Python Executable: /usr/bin/python Python Version: 2.7.2 Python Path: ['../Appraise-Software/appraise', '/home/paula/.local/lib/python2.7/site-packages/setuptools-1.1.4-py2.7.egg', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/paula/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol'] -- https://mail.python.org/mailman/listinfo/python-list
Re: Dealing with Lists
ok, so i think that getting the nested list is a little more for what i need, however, i could be wrong here, i got confused with Dave's suggestion. so, i got my lists broken up in a list of lists, but how would i access each of the elements? When i implement this solution my output list (the new one, after CHOPPING) prints like this: [u'arms', [u'a', [u'super', [u'group', [u'type', [u'is', [u'here']]] so i assume the indexing here would be similar to this: 01 0 1 0 1 0 1 0 1 0 [u'arms', [u'a', [u'super', [u'group', [u'type', [u'is', [u'here']]] Basically speaking ( each generated list would be the len=2 ? so, in my understanding, if i need to call the parenet for my FIRST group(most fist created), i would go and call chopGrps[0] this would get me arms and if i need to get the second element, (which should be a i would call chopGrps[1] but instead, i get the REST of the lists stored there. so what position does a take in this nested list? and this same question would apply to the rest of the items Thanks guys! On Tuesday, September 10, 2013 10:52:20 PM UTC-5, stas poritskiy wrote: Steven, i think you got on the right track with your proposal, although i am not going after the visual represenatation that you were able to create, rather a structural one, i think this might work for me, instead of printing, i could be using my commands to make elements (instances of API objects to create my groups inside the file) but one question i might have is : once i created first instance object which in my example is : groups = intance.add_group(str(name)) how would i temporary preserve this name as a reference for the next iteration for the subroups? On Tuesday, September 10, 2013 10:13:48 PM UTC-5, Steven D'Aprano wrote: On Wed, 11 Sep 2013 02:24:44 +, Dave Angel wrote: On 10/9/2013 22:14, Steven D'Aprano wrote: On Tue, 10 Sep 2013 14:08:45 -0700, stas poritskiy wrote: Greetings to all! i ran into a little logic problem and trying to figure it out. my case is as follows: i have a list of items each item represents a Group i need to create a set of nested groups, so, for example: myGroups = [head, neck, arms, legs] What is the rule for grouping these items? Below, you suggest: head encloses neck neck encloses arms arms encloses legs which seems rather strange. But if it is *always* the case that each item encloses the next item: def print_nested_list(alist): spaces = ' '*4 for level, item in enumerate(alist): if level != 0: indent = spaces*(level-1) + ' ' print (indent + '|_'), # note comma print item which gives us this: py print_nested_list(['head', 'neck', 'arms', 'legs']) head |_ neck |_ arms |_ legs as requested. Very nice. But what I want to know is how did you know that Stan (the OP) wanted his printed output to be formatted that way? I don't. Stan's email is unclear. But he does show an example: [quote] so, for example: myGroups = [head, neck, arms, legs] i need to get them to be represented like this: (if you can imaging a folder structure) head |_ neck |_ arms |_legs and so on until i hit the last element. [end quote] so I just provided that. He said: i need to create a set of nested groups, and store each of the first elements of a par, so I can reference to them as to a parent of another group. I have no idea what that means :-) I *guess* that what Stan is actually looking for is something like a dictionary-based solution, not lists: {'head': {'neck': {'arms': {}, 'legs': { which gives: head encloses neck neck encloses arms and legs arms enclose nothing legs enclose nothing or: {'head': {'neck': {'arms': {'legs': {}
Re: Language design
On 09/11/2013 03:38 AM, Burak Arslan wrote: On 09/10/13 09:09, Steven D'Aprano wrote: What design mistakes, traps or gotchas do you think Python has? My favourite gotcha is this: elt, = elts It's a nice and compact way to do both: assert len(elts) == 0 Perhaps you meant 'assert len(elts) == 1' ? -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Dealing with Lists
ok, while writing this, i figured out where those elements are located, so each element is always at the position 0, and to get deeper i have to follow something similar to this chopGrp = [[u'arms', [u'a', [u'super', [u'group', [u'type', [u'is', [u'here']]] print chopGrp[1][1][1][1][0] (this would get me type from the list) type this is getting somewhere, now, i am confused what type of iteration loop i should make, where each element is being called by itself, so i could reference the previous element as its Parent. so if i make this manually as a pseudo code: chopGrp[0] #gets me arms print Parent is: + chopGrp[0] chopGrp[1][0] #gets me a print Child is: + chopGrp[1][0] and the next iteration should take the chopGrp[1][0] and make it a parent of chopGrp[1][1][0] any hints? On Wednesday, September 11, 2013 9:47:30 AM UTC-5, stas poritskiy wrote: ok, so i think that getting the nested list is a little more for what i need, however, i could be wrong here, i got confused with Dave's suggestion. so, i got my lists broken up in a list of lists, but how would i access each of the elements? When i implement this solution my output list (the new one, after CHOPPING) prints like this: [u'arms', [u'a', [u'super', [u'group', [u'type', [u'is', [u'here']]] so i assume the indexing here would be similar to this: 01 0 1 0 1 0 1 0 1 0 [u'arms', [u'a', [u'super', [u'group', [u'type', [u'is', [u'here']]] Basically speaking ( each generated list would be the len=2 ? so, in my understanding, if i need to call the parenet for my FIRST group(most fist created), i would go and call chopGrps[0] this would get me arms and if i need to get the second element, (which should be a i would call chopGrps[1] but instead, i get the REST of the lists stored there. so what position does a take in this nested list? and this same question would apply to the rest of the items Thanks guys! On Tuesday, September 10, 2013 10:52:20 PM UTC-5, stas poritskiy wrote: Steven, i think you got on the right track with your proposal, although i am not going after the visual represenatation that you were able to create, rather a structural one, i think this might work for me, instead of printing, i could be using my commands to make elements (instances of API objects to create my groups inside the file) but one question i might have is : once i created first instance object which in my example is : groups = intance.add_group(str(name)) how would i temporary preserve this name as a reference for the next iteration for the subroups? On Tuesday, September 10, 2013 10:13:48 PM UTC-5, Steven D'Aprano wrote: On Wed, 11 Sep 2013 02:24:44 +, Dave Angel wrote: On 10/9/2013 22:14, Steven D'Aprano wrote: On Tue, 10 Sep 2013 14:08:45 -0700, stas poritskiy wrote: Greetings to all! i ran into a little logic problem and trying to figure it out. my case is as follows: i have a list of items each item represents a Group i need to create a set of nested groups, so, for example: myGroups = [head, neck, arms, legs] What is the rule for grouping these items? Below, you suggest: head encloses neck neck encloses arms arms encloses legs which seems rather strange. But if it is *always* the case that each item encloses the next item: def print_nested_list(alist): spaces = ' '*4 for level, item in enumerate(alist): if level != 0: indent = spaces*(level-1) + ' ' print (indent + '|_'), # note comma print item which gives us this: py print_nested_list(['head', 'neck', 'arms', 'legs']) head |_ neck |_ arms
Re: Dealing with Lists
stas poritskiy wrote: By now your post consists of over 1300 lines, most of them containing nothing but quoting marks. Please be courteous to your readers and avoid that. https://wiki.python.org/moin/GoogleGroupsPython may be helpful. ok, while writing this, i figured out where those elements are located, so each element is always at the position 0, and to get deeper i have to follow something similar to this chopGrp = [[u'arms', [u'a', [u'super', [u'group', [u'type', [u'is', [u'here']]] print chopGrp[1][1][1][1][0] (this would get me type from the list) type this is getting somewhere, now, i am confused what type of iteration loop i should make, where each element is being called by itself, so i could reference the previous element as its Parent. so if i make this manually as a pseudo code: chopGrp[0] #gets me arms print Parent is: + chopGrp[0] chopGrp[1][0] #gets me a print Child is: + chopGrp[1][0] and the next iteration should take the chopGrp[1][0] and make it a parent of chopGrp[1][1][0] Again, be courteous and give actual self-contained runnable Python code. I doubt that anyone can make much of the above any hints? My impression is that much of your confusion stems from using generic lists where items in different positions have a different meaning for different posters and it is difficult to keep track of what's what. I suggest you bite the bullet and go for a class-based approach. Then, when you talk about children or parent it is clear that you find them in the Node's attribute of the same name. Proceed to express your tasks in plain English as clearly as you can, and only then try to transform them into code. To get you started here's what a simple tree might look like: $ cat tree.py from __future__ import print_function from collections import OrderedDict as Children class Node: def __init__(self, name, parent=None): self.name = name self.parent = parent self.children = Children() if parent is not None: self.parent.children[name] = self def show(self, level=0): print( * level, self.name, sep=) for child in self.children.values(): child.show(level + 1) class Tree(Node): def __init__(self): Node.__init__(self, None) def ensure(self, path): Add node with all intermediate nodes node = self for name in path: try: node = node.children[name] except KeyError: node = Node(name, node) return node def show(self, level=0): for child in self.children.values(): child.show() if __name__ == __main__: data = \ plant flower tulip plant flower lily animal mammal cat animal mammal zebra animal reptile snake animal reptile snake python animal reptile snake boa paths = [line.split() for line in data.splitlines()] tree = Tree() for path in paths: tree.ensure(path) tree.show() And here's the output of the demo: $ python tree.py plant flower tulip lily animal mammal cat zebra reptile snake python boa -- https://mail.python.org/mailman/listinfo/python-list
Re: TypeError in date_parse.py
In 09d39e02-c741-4a46-b34f-551e8...@googlegroups.com pestre...@gmail.com writes: = # Compute duration for this item. duration = None if end_timestamp and start_timestamp: start_datetime = datetime.fromtimestamp(float(start_timestamp)) end_datetime = datetime.fromtimestamp(float(end_timestamp)) duration = end_datetime - start_datetime = What is the type and value of start_timestamp and end_timestamp? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- https://mail.python.org/mailman/listinfo/python-list
Re: Python TUI that will work on DOS/Windows and Unix/Linux
Michael Torrie torr...@gmail.com wrote in message news:mailman.229.1378858009.5461.python-l...@python.org... ... A toolkit (that's old, arguably), that might help you is TVision, a port of the old Turbo Vision library that formed the foundation for Borland's old DOS IDEs back in the day (check wikipedia). And it looked quite beautiful back then, actually. There is a Python binding for it here: https://pypi.python.org/pypi/PyTVision That looks very good. For the record, I have been emailed about npyscreen and urwid. And I have found a hex editor with the kind of interface I had in mind. Here are some links for anyone else who is interested. http://www.sigala.it/sergio/tvision/images.html http://www.npcole.com/npyscreen/ http://excess.org/urwid/examples.html http://www.hexedit.com/hex-edit-shots.htm James -- https://mail.python.org/mailman/listinfo/python-list
Re: Send alt key to subprocess.PIPE stdin
On Wed, 11 Sep 2013 07:26:32 -0700, Wanderer wrote: How do I send the command 'Alt+D' to subprocess.PIPE? You don't. GUI programs don't read stdin, they receive key press events from the windowing system. -- https://mail.python.org/mailman/listinfo/python-list
Re: TypeError in date_parse.py
I think it's a float, I see in the code if request.method == POST: end_timestamp = request.POST.get('end_timestamp', None) start_timestamp = request.POST.get('start_timestamp', None) and in the debug of django QueryDict: {u'start_timestamp': [u'1378918630.398'], -- https://mail.python.org/mailman/listinfo/python-list
Re: TypeError in date_parse.py
In 3d0038fd-00ec-4560-ab0d-06528f838...@googlegroups.com pestre...@gmail.com writes: I think it's a float, I see in the code if request.method == POST: end_timestamp = request.POST.get('end_timestamp', None) start_timestamp = request.POST.get('start_timestamp', None) and in the debug of django QueryDict: {u'start_timestamp': [u'1378918630.398'], That's a list, containing a string. float() expects a single item, not a list. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- https://mail.python.org/mailman/listinfo/python-list
Re: embedding interactive python interpreter
Scott, Yes. As Mark Hammond suggested I took a look into the code/console modules. I wound up using InteractiveConsole from the code module. I'm sure my requirements are completely different from yours but I'll explain what I did anyway... I was working with a client/server architecture where I wanted the client to be able to interact with a server-side Python console. Yes, I know this is a huge security hole. It is only used as a debugging console to be able to interactively inspect the state of the remote server process from within the client application itself. This 3rd party client server application I was customizing allows me to write my own services. So I wrote a service that accepts a string (the python line) and returns two strings and a boolean (stdout, stderr, and whether or not the interpreter expects more input). That boolean basically controls whether the console should show a or a ... and comes from InteractiveConsole.push. To get stdout and stderr I monkey patched sys.stdout and sys.stderr with an instance of MyBuffer. class MyBuffer(object): def __init__(self): self.buffer = [] def write(self, data): self.buffer.append(data) def get(self): ret = ''.join(self.buffer) self.buffer = [] return ret In my subclass of InteractiveConsole I defined the following... def __init__(self, *args, **kwargs): InteractiveConsole.__init__(self, *args, **kwargs) self.mb_out = MyBuffer() self.mb_err = MyBuffer() def process(self, s): sys.stdout, sys.stderr = self.mb_out, self.mb_err more = self.push(s) sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__ return self.mb_out.get(), self.mb_err.get(), more My service (written in c++), upon initialization gets a handle to a singleton instance of this InteractiveConsole sublcass using the Python C APIs. When the service responds to a request it uses the Python C APIs to call the process method above and returns the two strings and the boolean. The client, which happens to be Java/Eclipse based, then has something that resembles a Python console in the GUI and uses that single service to interact with the remote Python console. Lots of stuff going on but it works very well. On Wed, Sep 11, 2013 at 1:42 PM, Scott ihearthondu...@gmail.com wrote: Eric, https://mail.python.org/pipermail/python-list/2011-March/600441.html Did you ever figure this out? I'm trying to embed an interactive interpreter, and I'm sure that python has an easy way to do this, but I can't seem to find it... Thanks, -C. Scott! Brown -- https://mail.python.org/mailman/listinfo/python-list
Re: Send alt key to subprocess.PIPE stdin
On 09/11/2013 07:26 AM, Wanderer wrote: How do I send the command 'Alt+D' to subprocess.PIPE? My code is import subprocess rsconfig = subprocess.Popen([C:\Program Files\Photometrics\PVCam64\utilities\RSConfig\RSConfig.exe, ],stdin=subprocess.PIPE) rsconfig.stdin.write('Alt+D') Thanks That question doesn't really make sense. A pipe provides a method to transfer a stream of bytes. You could indeed send that byte across the pipe, but it's just a byte, written by one process and read by another process. The receiving process can examine the byte stream, and do whatever it wants in response. By calling it a _command_, you seem to expect some particular behavior out of the receiving process. Please tell us *what* that might be, and we'll see what we can do to help out. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Can I trust downloading Python?
On Saturday, September 7, 2013 9:17:46 PM UTC-4, Aaron Martin wrote: Hi, I am thinking about getting a software but it requires python, so that brought up a few questions. Is it safe do download python, and does it come with spam or advertisements? If it doesn't then should I get the latest version? I mostly want to know if it is safe to download, because most of the time downloading free stuff off the internet comes with spam and all that, so I want to know if I can trust downloading it. Hope others find this article helpful and relevant: http://www.eweek.com/developer/open-source-python-code-sets-new-standard-for-quality-study.html/?kc=EWKNLEAU09102013BESTOF2dni=77668545rni=22939981 A development testing company (Coverity) reports that the core Python platform has a very low number of source code defects and its developers effect repairs to known flaws very readily, as compared to other open-source projects. I can't attest to the validity of the claim (one way or the other), but it is something worth noting -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On 09/11/13 17:52, Ethan Furman wrote: On 09/11/2013 03:38 AM, Burak Arslan wrote: On 09/10/13 09:09, Steven D'Aprano wrote: What design mistakes, traps or gotchas do you think Python has? My favourite gotcha is this: elt, = elts It's a nice and compact way to do both: assert len(elts) == 0 Perhaps you meant 'assert len(elts) == 1' ? yes :) -- https://mail.python.org/mailman/listinfo/python-list
Oportunidade: Desenvolvedor Python
Arpex Capital seleciona para uma de suas empresas: Desenvolvedor Python Objetivo geral da Posição: Desenvolver software estável e de primeira linha, que será incorporado à plataforma de WiFi mais moderna atualmente. Pré-requisitos: - Conhecimento em Python - MongoDB - Cloud computing, BigData - Pensamento lógico e analítico - Capacidade de absorver tecnologias novas de forma constante Deveres: - Escrever software sólido em Python Formação: Irrelevante (não cobramos) Local de Trabalho: São Paulo/SP A empresa oferece remuneração compatível com o mercado + Benefícios. Os interessados deverão enviar o CV para kgar...@arpexcapital.com.br , mencionando no assunto Desenvolvedor Python. -- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
@Dave Angel What is .lower() ? -- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
@Jugurtha Hadjar What does user_input.lower() mean/do? -- https://mail.python.org/mailman/listinfo/python-list
Re: Send alt key to subprocess.PIPE stdin
On Wednesday, September 11, 2013 1:43:09 PM UTC-4, Gary Herron wrote: On 09/11/2013 07:26 AM, Wanderer wrote: How do I send the command 'Alt+D' to subprocess.PIPE? My code is import subprocess rsconfig = subprocess.Popen([C:\Program Files\Photometrics\PVCam64\utilities\RSConfig\RSConfig.exe, ],stdin=subprocess.PIPE) rsconfig.stdin.write('Alt+D') Thanks That question doesn't really make sense. A pipe provides a method to transfer a stream of bytes. You could indeed send that byte across the pipe, but it's just a byte, written by one process and read by another process. The receiving process can examine the byte stream, and do whatever it wants in response. By calling it a _command_, you seem to expect some particular behavior out of the receiving process. Please tell us *what* that might be, and we'll see what we can do to help out. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 I found Sendkeys works. import subprocess import time import SendKeys rsconfig = subprocess.Popen([C:\Program Files\Photometrics\PVCam64\utilities\RSConfig\RSConfig.exe, ]) time.sleep(2) SendKeys.SendKeys('%D\n', with_newlines=True) Basically there is a dialog with a Done button and 'Alt D' selects the Done button. The subprocess program runs some interface code which sets up an ini file that the rest of the program needs. But then I run into another problem with Windows permissions. The program needs to edit this ini file located in the C:\Windows directory. Windows won't let you without administrator permissions. So then I run into login issues, etc. I kind of gave up and this program has to be run outside my main program. It's annoying since it's just this stupid little text ini file, but I can't convince Windows it doesn't matter if gets edited because it's in a system directory. -- https://mail.python.org/mailman/listinfo/python-list
Re: better and user friendly IDE recommended?
On Wed, 2013-09-11 at 07:14 -0700, mnish1...@gmail.com wrote: Hey i am a programmer but new to python. Can anyone guide me in knowing which is a better IDE used to develop web related apps that connect to DB using python? geany; it's awesome. http://www.geany.org/ -- Adam Tauno Williams mailto:awill...@whitemice.org GPG D95ED383 Systems Administrator, Python Developer, LPI / NCLA -- https://mail.python.org/mailman/listinfo/python-list
Re: global variable across modules
On 11/9/2013 08:50, chandan kumar wrote: Hi , I'm trying to understand using global variable across different modules. Python doesn't have such a thing, unless you consider builtins. Here is what i have tried so far without much success.Please ignore any indentation issue in the below code. Which one is the script, and which one an imported module? You have bugs ether wayl, but different ones. I have to assume something, so I'll assume Test2.py is your script. Filename:Test1.py Debug_Value = import Test2 Nasty business. Any time you have recursive imports, you can expect trouble. But importing the script is doubly bad. You'll be importing a second copy of the script, pretending it's a module, and you'll be RUNNING it before this Test1 module. Maybe that doesn't matter, since the script does nothing useful. But once you fix the other problems, this one will be a big problem. def globalValmethod(): global Debug_Value Debug_Value =10 Test2.globalValTest() globalValmethod() -Execute the method Filename:Test2.py import Test1 from Test1 import * Bad practice. I wish the above syntax were not in the language. def globalValTest() print Golabal Value Debug_Value You omitted any top-level code, so this function won't be called anyway. In Test2.py file I wanted to print the global value ,Debug_Value as 10.I'm not getting expected result.Please can any one point where exactly i'm doing wrong. After you fix the above, you'll still have the problem that you apparently don't understand that these variables are names referring to objects. If you have two names bound to the same object, and you rebind one of them (inside globalValmethod()), the other remains bound to the original object. After you rename your files so I can tell which one is intended as the script, and which as the module, then clean up the other problems, and remove one of the imports. Then if you're still confused, ask again. Similarly , how can i use global variable inside a class and use the same value of global variable in different class?Is that possible?if Yes please give me some pointers on implementing. There are no global variables inside a class. There are class attributes which are sort-of global, and it's legal to use the global statement inside a method, as with any other function. But the main question is probably, why are you so hung up on globals? If it's changeable, it usually should NOT be global. Good uses for globals are things like math.pi or command-line options. The first is always the same, and the second is initialized before anyone will use it, and never changed afterwards. incidentally, class names, module names, and top-level function names are also global, and these are normally not changeable. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Send alt key to subprocess.PIPE stdin
On 11/9/2013 10:26, Wanderer wrote: How do I send the command 'Alt+D' to subprocess.PIPE? That's not a command, it's a keystroke combination. And without knowing what RSConfig.exe is looking to get its keystrokes, it might not even be possible to feed it any keystrokes via the pipe. if the program does indeed use stdin, there's no portable encoding for Alt-D. But if your program only runs on one particular platform, you might be able to find docs for that platform that explain it. My code is import subprocess rsconfig = subprocess.Popen([C:\Program Files\Photometrics\PVCam64\utilities\RSConfig\RSConfig.exe, ],stdin=subprocess.PIPE) That string will only work by accident. You need to make it a raw string, or use forward slashes, or double them. As it happens, with this PARTICULAR set of directories, you won't get into trouble with Python 2.7.3 -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
In f7db6733-0f7a-4b18-bdcd-8d53e3644...@googlegroups.com William Bryant gogobe...@gmail.com writes: @Jugurtha Hadjar What does user_input.lower() mean/do? String objects have a number of built-in functions, lower() being one of them. It returns a copy of the string with all uppercase letters converted to lowercase. Example: x = Hello There y = x.lower() print y hello there -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
On 11/9/2013 15:31, William Bryant wrote: @Dave Angel What is .lower() ? It is a method on the str class. You could teach yourself. At the interpreter prompt, type help(test response.lower) Or on the web: http://docs.python.org/2/library/stdtypes.html#str.lower There are lots of other interesting methods in the str class, listed on that section of that page. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
RE: Help please, why doesn't it show the next input?
William Bryant wrote: Sent: Wednesday, September 11, 2013 2:32 PM To: python-list@python.org Subject: Re: Help please, why doesn't it show the next input? @Dave Angel What is .lower() ? Thanks for bottom posting and trimming, but you should leave some content quoted for context. Otherwise people will not what you are referring to. You can find answers to questions like this in the API. http://docs.python.org/2/library/stdtypes.html#str.lower I would recommend taking time to get familiar with the Athena interpreter. It can also answer questions like this (but with less detail than the web API). You can use dir() to find the attributes on any object. help() will give you docstring for the attribute/class. 'A'.lower() 'a' help(''.lower) Help on built-in function lower: lower(...) S.lower() - string Return a copy of the string S converted to lowercase. help(dir) Help on built-in function dir in module __builtin__: dir(...) dir([object]) - list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes. dir('') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem_\ _', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__\ ', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclass\ hook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expan\ dtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lo\ wer', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'starts\ with', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] If you want to see all the relevant information you can use help() on the class [e.g. help(str)]. I think help(class) will not show functions that start with _ unless they are python magic dunder functions (e.g. __str__). ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
On 9/11/2013 3:31 PM, William Bryant wrote: What is .lower() ? The Python docs have a pretty good index that includes 'lower() (str method)'. Learn to use it. If you know that .lower is a str method, help(str.lower) at interactive prompt prints a page. Learn to use help(ob) also. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Chardet, file, ... and the Flexible String Representation
09.09.13 22:27, random...@fastmail.us написав(ла): On Mon, Sep 9, 2013, at 15:03, Ian Kelly wrote: Do you mean that it breaks when overwriting Python string object buffers, or when overwriting arbitrary C strings either received from C code or created with create_unicode_buffer? If the former, I think that is to be expected since ctypes ultimately can't know what is the actual type of the pointer it was handed -- much as in C, that's up to the programmer to get right. I also think it's very bad practice to be overwriting those anyway, since Python strings are supposed to be immutable. If the latter, that sounds like a bug in ctypes to me. I was talking about writing to the buffer object from python, i.e. with slice assignment. s = 'Test \U0001' len(s) 6 buf = create_unicode_buffer(32) buf[:6] = s TypeError: one character unicode string expected buf[:7] = s ValueError: Can only assign sequence of same size buf[:7] = 'Test \ud800\udc00' buf[:7] 'Test \U0001' # len = 6 Assigning with .value works, however, which may be a viable workaround for most situations. The one character unicode string expected message is a bit cryptic. Please report a bug on http://bugs.python.org/. -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
* Imports are fiendishly complex, hidden below deceptively simple syntax. It's a reasonable expectation that one can import a module from a source code file given its path on the filesystem, but this turns out to be much more complicated than in many other languages. Why is this so difficult? Add a Graph class to the collections module (networkx is quite good) and simply check for circular imports. The remaining difficulty I encounter is because the user hasn't defined their PYTHONPATH variable. -- MarkJ Tacoma, Washington -- https://mail.python.org/mailman/listinfo/python-list
Python GUI?
There are a few known GUI toolkits out there, and the main ones from what I can tell are: Tkinter -- Simple to use, but limited PyQT -- You have a GUI designer, so I'm not going to count that PyGTK -- Gnome officially back this I think wxPython -- Very nice, very professional, approved by Python creator, but alas hard to get started with So, what are your personal preferences and why? Why use X over Y? I, personally, really like wxPython, but I also really like Tkinter. I've messed with PyGTK, but I'd choose wxPython over it. Have you got anything to say on what one I should be using(excluding PyQT because it has a DD designer :( )? Is Tkinter really dead? Should I stick with wxPython? It's might be similar to the What language to use argument, or the What background to code on argument(I prefer darker backgrounds xD Please don't argue about this though!), in the sense that there is *no* answer, just preference. Also, with wxPython, it has kind of a flow layout like JFrame, whereas it will adjust it's layout to look like a native Mac App, Windows app or Linux App, correct? It'll look almost identical, right? Not that it matters, I'm just curious! :D Thanks! -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
Hello all, Thanks for this thread. Here are my two cents... On 10.09.2013 08:09, Steven D'Aprano wrote: What design mistakes, traps or gotchas do you think Python has? Gotchas are not necessarily a bad thing, there may be good reasons for it, but they're surprising. 1. Occasionally, one encounters a strange idiom. Syntactically legal and consistent, though: +4++4 8 -4+-4 -8 -4-+4 -8 2. Reduce removed from standard library. That is a big fail, in my opinion. 3. The default return value of methods is None instead of self. If it was self, it would be possible to chain method calls (which is called a cascade in smalltalk). lst = [] lst.append(1).append(2).append(3) ## FAIL Traceback (most recent call last): ... AttributeError: 'NoneType' object has no attribute 'append' Instead, this works: class Coll(list): ... ... def add(self, e): ... self.append(e) ... return self ... lst = Coll() lst.add(1).add(2).add(3) ## OK [1, 2, 3] A very practical use case is, that the return value of None makes all of these methods unusable for reduce. from functools import reduce ... many = [{1: 'a'}, {2: 'b'}, {3: 'c'}] ... reduce(lambda d, other : d.update(other), many, {}) ## FAIL Traceback (most recent call last): ... AttributeError: 'NoneType' object has no attribute 'update' Again, one would have to define an update function with an explicit return value. many = [{1: 'a'}, {2: 'b'}, {3: 'c'}] ... def fn(d, other): ... d.update(other) ... return d ... reduce(fn, many, {}) ## OK {1: 'a', 2: 'b', 3: 'c'} 4. As has been mentioned already, some built-in functions do magic stuff behind the scenes: () == [] False But: bool(().__eq__([])) True Because: ().__eq__([]) NotImplemented which yields True when cast to boolean. Greets, Markus -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
1) It tried to make Object the parent of every class. No one's close enough to God to make that work. 2) It didn't make dicts inherit from sets when they were added to Python. 3) It used the set literal for dict, so that there's no obvious way to do it. This didn't get changed in Py3k. 4?) It allowed [reference] variables to be used as dict keys. This creates a parsing difficulty for me, mentally. Keys should be direct, hashable values, not hidden in a variable name. A few of the top of the head Mark On Mon, Sep 9, 2013 at 11:09 PM, Steven D'Aprano st...@pearwood.info wrote: Some time ago, Tom Christiansen wrote about the Seven Deadly Sins of Perl: http://www.perl.com/doc/FMTEYEWTK/versus/perl.html What design mistakes, traps or gotchas do you think Python has? Gotchas are not necessarily a bad thing, there may be good reasons for it, but they're surprising. To get started, here are a couple of mine: - Python is so dynamic, that there is hardly anything at all that can be optimized at compile time. - The behaviour of mutable default variables is a gotcha. - Operators that call dunder methods like __add__ don't use the same method resolution rules as regular methods, they bypass the instance and go straight to the type, at least for new-style classes. -- Steven -- https://mail.python.org/mailman/listinfo/python-list -- MarkJ Tacoma, Washington -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On 09/11/2013 01:41 PM, Markus Rother wrote: 4. As has been mentioned already, some built-in functions do magic stuff behind the scenes: That's why they're called magic methods. ;) () == [] False But: bool(().__eq__([])) True This is not a trap, this is simply the wrong way to do it. The magic methods (aka dunder methods) are there for Python to call, not you (except under special circumstances, such as when writing your own dunder methods). -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: global variable across modules
Chris, Interesting. # Test1.py Debug_Value = # Test2.py from Test1 import * # is exactly equivalent to Debug_Value = I take it then that assigning to Debug_Value in Test2.py will not change the value of Debug_Value in Test1.py. That being the case it would be wrong to assume that the following are identical import sys and from sys import * (the latter being a convenience to avoid having to write sys. before every variable). Thus assigning to sys.stdout would change the standard out destination in every module importing sys whereas from sys import * stdout = foo.dst would only change stdout in the current module and sys.stdout would remain unchanged. Is my understanding here correct? As to global usage I do find it useful to have a file called something like 'preferences.py' and put in there constants to be used throughout the application. But I use these strictly read only. It is good in that system wide constants are defined in one place only. Also if the constants are put inside a class, possibly with getter methods, instantiated as a singleton then initially the values can be typed directly into the preferences file. Later the constructor could be changed to read the constants from an initialisation file of your own format (e.g. .ini or JSON). Thus users without python experience might find it easier to change them without having to look at any python code. On the other hand I appreciate simple constant assignments should be easy enough to change without needing to know any Python. Also remember that accessing any form of global that is shared between multiple threads is a recipe for disaster unless appropriate locks are used. A significant advantage of not using globals (except for system wide constants) is that is makes testing of individual modules easier. The less coupling there is between modules the easier it is to understand and test. Regards all, John-- https://mail.python.org/mailman/listinfo/python-list
Re: global variable across modules
On 11/9/2013 17:49, John Pote wrote: Chris, Interesting. # Test1.py Debug_Value = # Test2.py from Test1 import * # is exactly equivalent to Debug_Value = I take it then that assigning to Debug_Value in Test2.py will not change the value of Debug_Value in Test1.py. That's correct. But it would be clearer to say that binding a new object to Debug_Value in Test2.py after Test1.py has already done its import does not change the binding that Test1.py has for Debug_Value. Note that if the object was mutable (which string is not), then it would be possible to change the object. In that case, both names would refer to the new value of the object. That being the case it would be wrong to assume that the following are identical import sys and from sys import * (the latter being a convenience to avoid having to write sys. before every variable). Right, they're not even close. Thus assigning to sys.stdout would change the standard out destination in every module importing sys whereas from sys import * stdout = foo.dst would only change stdout in the current module and sys.stdout would remain unchanged. Is my understanding here correct? Yes. But notice that when you do print() in any module, it indirectly refers to sys.stdout, even if you have changed your own module's stdout. htmlheadmeta http-equiv=Content-Type content=text/html charset=us-ascii/headbody style=word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; Chris,divInteresting.nbsp;brdivblockquote type=citebr# Test1.pybrDebug_Value = brbr# Test2.pybrfrom Test1 import *br# is exactly equivalent tobrDebug_Value = brbr/blockquote/divI take it then that assigning tonbsp;Debug_Value in Test2.py will not change the value ofnbsp;Debug_Value in Test1.py./divdivbr/divdivThat being the case it would be wrong to assume that the following are identical/divdivbr/divdivimport sys/divdivbr/divdivand/divdivbr/divdivfrom sys import */divdivbr/divdiv(the latter being a convenience nbsp;to avoid having to write sys. before every variable)./divdivbr/divdivThus assigning to sys.stdout would change the standard out destination in every module importing sys whereas/di vdivbr/divdivfrom sys import */divdivstdout = foo.dst/divdivbr/divdivwould only change stdout in the current module and sys.stdout would remain unchanged./divdivbr/divdivIs my understanding here correct?/divdivbr/divdivAs to global usage I do find it useful to have a file called something like 'preferences.py' and put in there constants to be used throughout the application. But I use these strictly read only. It is good in that system wide constants are defined in one place only. Also if the constants are put inside a class, possibly with getter methods, instantiated as a singleton then initially the values can be typed directly into the preferences file. Later the constructor could be changed to read the constants from an initialisation file of your own format (e.g. .ini or JSON). Thus users without python experience might find it easier to change them without having to look at any python code. On the other hand I appreciate simple consta nt assignments should be easy enough to change without needing to know any Python./divdivbr/divdivAlso remember that accessing any form of global that is shared between multiple threads is a recipe for disaster unless appropriate locks are used. A significant advantage of inot/i using globals (except for system wide constants) is that is makes testing of individual modules easier. The less coupling there is between modules the easier it is to understand and test./divdivbr/divdivRegards all,/divdivJohn/div/body/html Try fixing your email program to use text, not html. This time it's just wasted space in each copy of the message (where space is money). But next time it might lead to indentation problems and other miscommunication. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
RE: Language design
Mark Janssen wrote: 1) It tried to make Object the parent of every class. No one's close enough to God to make that work. 2) It didn't make dicts inherit from sets when they were added to Python. 3) It used the set literal for dict, so that there's no obvious way to do it. This didn't get changed in Py3k. 4?) It allowed [reference] variables to be used as dict keys. This creates a parsing difficulty for me, mentally. Keys should be direct, hashable values, not hidden in a variable name. What do you mean by 4? Do you mean that keys should only be hardcoded? I am going to assume you meant something different, as that sounds like a terrible idea to me... A few of the top of the head Mark This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
Wayne Werner wa...@waynewerner.com writes: On Tue, 10 Sep 2013, Ben Finney wrote: The sooner we replace the erroneous “text is ASCII” in the common wisdom with “text is Unicode”, the better. I'd actually argue that it's better to replace the common wisdom with text is binary data, and we should normally look at that text through Unicode eyes. A little less catchy, but more accurate ;) No, that's inaccurate. A sequence of bytes is binary data. Unicode is not binary data. There are encodings which map Unicode to a sequence of bytes, but text is not binary data. -- \ “For fast acting relief, try slowing down.” —Jane Wagner, via | `\ Lily Tomlin | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Please omit false legalese footers (was: Language design)
Prasad, Ramit ramit.pra...@jpmorgan.com.dmarc.invalid writes: This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. No, your message was not confidential. You sent it to a public mailing list, presumably by choice. So please omit such false and pointless legal rubbish from your messages here. -- \“I'd take the awe of understanding over the awe of ignorance | `\ any day.” —Douglas Adams | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Thu, Sep 12, 2013 at 6:41 AM, Markus Rother pyt...@markusrother.de wrote: 3. The default return value of methods is None instead of self. If it was self, it would be possible to chain method calls (which is called a cascade in smalltalk). lst = [] lst.append(1).append(2).append(3) ## FAIL Traceback (most recent call last): ... AttributeError: 'NoneType' object has no attribute 'append' That's a policy decision: a method (or function) will *EITHER* return a value, *OR* mutate its primary argument (in the case of a method, that's self). It reduces the chances of code like this: foo = [1, 4, 2, 8, 5, 7] largest_digit = foo.sort()[-1] one_seventh = ''.join(map(str,foo)) If you used sorted(foo) instead of foo.sort(), this wouldn't crash out, and it'd do what you expect. Having foo.sort() return self would mean this wouldn't crash, but would potentially do something surprising. But while I understand the reasoning behind it, I don't entirely agree. There are times when I use Pike's sort() function [1], which does return its mutated argument, something like this: foo = sort(blah_blah_blah()) Why should that be split into two statements? Or alternatively, why should an extra copy of the list be created (if you use Python's sorted() here)? But for the new programmer, this is a convenient safety-net, and if list.sort() worked the other way, it'd be just as much a gotcha (I ask for a sorted list, and it also changed the original?!??). ChrisA [1] http://pike.lysator.liu.se/generated/manual/modref/ex/predef_3A_3A/sort.html -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
Mark Janssen dreamingforw...@gmail.com writes: * Imports are fiendishly complex, hidden below deceptively simple syntax. It's a reasonable expectation that one can import a module from a source code file given its path on the filesystem, but this turns out to be much more complicated than in many other languages. Why is this so difficult? I don't know, you'll have to ask the people who designed it that way. Add a Graph class to the collections module (networkx is quite good) and simply check for circular imports. Er? That doesn't address the task of importing a module from a source code file given its path on the filesystem. Other languages have the equivalent of ‘include /path/to/file.py’, but Python doesn't. That's the misdesign I'm describing. -- \ “Just because nobody complains doesn't mean all parachutes are | `\ perfect.” —Benny Hill | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: better and user friendly IDE recommended?
mnish1...@gmail.com writes: Hey i am a programmer but new to python. Welcome! Congratulations on finding Python. Can anyone guide me in knowing which is a better IDE used to develop web related apps that connect to DB using python? The question of IDEs is a common one, and is a matter of aesthetics as much as functionality. Many of use use general-purpose development environments, which will repay learning in much broader range of tasks than only Python programming. Here is a Wiki page on the topic, with discussions and reviews URL:https://wiki.python.org/moin/IntegratedDevelopmentEnvironments. My main advice: Avoid non-free (that is, proprietary) software for your development tools. Learning a set of development tools is a significant investment, and you should not tie that investment to a single vendor; if they lose interest for whatever reason, your investment is stranded. Free software is essential to ensure your tools can continue beyond the copyright holders of today. -- \ “Corporation, n. An ingenious device for obtaining individual | `\ profit without individual responsibility.” —Ambrose Bierce, | _o__) _The Devil's Dictionary_, 1906 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Wed, 11 Sep 2013 14:30:54 -0700, Mark Janssen wrote: 1) It tried to make Object the parent of every class. Tried, and succeeded. No one's close enough to God to make that work. Non-sequitor. One doesn't need to be close to a deity to have a single root of the object hierarchy. 2) It didn't make dicts inherit from sets when they were added to Python. Why would you want dicts to inherit from sets? 3) It used the set literal for dict, so that there's no obvious way to do it. This didn't get changed in Py3k. No, it uses the dict literal for dicts. And the obvious way to form an empty set is by calling set(), the same as str(), int(), list(), float(), tuple(), dict(), ... 4?) It allowed [reference] variables to be used as dict keys. This creates a parsing difficulty for me, mentally. Keys should be direct, hashable values, not hidden in a variable name. I don't even understand what you are talking about here. [reference] variables? What does that mean? Dict keys are direct, hashable values, and I have no idea what you mean by hidden in a variable name. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Wed, 11 Sep 2013 22:41:50 +0200, Markus Rother wrote: 2. Reduce removed from standard library. That is a big fail, in my opinion. And Guido's Time Machine strikes again! py from functools import reduce py reduce built-in function reduce [...] 4. As has been mentioned already, some built-in functions do magic stuff behind the scenes: () == [] False But: bool(().__eq__([])) True Because: ().__eq__([]) NotImplemented which yields True when cast to boolean. I don't see that this is a gotcha, let alone a design mistake. There's no reason to be calling __eq__ directly instead of == but if you do, you're responsible for handling the operator protocol yourself. Namely, if the operator special method returns NotImplemented, you're supposed to reverse the operands and try again. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On 9/11/2013 7:19 PM, Ben Finney wrote: Er? That doesn't address the task of importing a module from a source code file given its path on the filesystem. Other languages have the equivalent of ‘include /path/to/file.py’, Some includes are equivalent to with open(/path/to/file.py) as f: exec(f.read()) but Python doesn't. which Python does have. Python also has __import__(/path/to/file.py), which is used by import when the module does not exist. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: why syntax change in lambda
On Wed, 11 Sep 2013 09:03:49 -0400, Neal Becker wrote: In py2.7 this was accepted, but not in py3.3. Is this intentional? It seems to violate the 'principle' that extraneous parentheses are usually allowed/ignored In [1]: p = lambda x: x In [2]: p = lambda (x): x File ipython-input-2-2b94675a98f1, line 1 p = lambda (x): x ^ SyntaxError: invalid syntax It is not specific to lambda, it has to do with the removal of argument unpacking in function argument lists: # allowed in Python 2, not in Python 3 def f(a, b, (c, d), e): pass In Python 3, the parser appears to disallow any extra parentheses inside the parameter list, even if strictly speaking they don't do anything: py def f(a, b, (c), d, e): File stdin, line 1 def f(a, b, (c), d, e): ^ SyntaxError: invalid syntax -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: global variable across modules
Sorry about the html - did not realise. Thanks for your comments. John On 11 Sep 2013, at 22:49, John Pote johnhp...@o2.co.uk wrote: Chris, Interesting. # Test1.py Debug_Value = # Test2.py from Test1 import * # is exactly equivalent to Debug_Value = I take it then that assigning to Debug_Value in Test2.py will not change the value of Debug_Value in Test1.py. That being the case it would be wrong to assume that the following are identical import sys and from sys import * (the latter being a convenience to avoid having to write sys. before every variable). Thus assigning to sys.stdout would change the standard out destination in every module importing sys whereas from sys import * stdout = foo.dst would only change stdout in the current module and sys.stdout would remain unchanged. Is my understanding here correct? As to global usage I do find it useful to have a file called something like 'preferences.py' and put in there constants to be used throughout the application. But I use these strictly read only. It is good in that system wide constants are defined in one place only. Also if the constants are put inside a class, possibly with getter methods, instantiated as a singleton then initially the values can be typed directly into the preferences file. Later the constructor could be changed to read the constants from an initialisation file of your own format (e.g. .ini or JSON). Thus users without python experience might find it easier to change them without having to look at any python code. On the other hand I appreciate simple constant assignments should be easy enough to change without needing to know any Python. Also remember that accessing any form of global that is shared between multiple threads is a recipe for disaster unless appropriate locks are used. A significant advantage of not using globals (except for system wide constants) is that is makes testing of individual modules easier. The less coupling there is between modules the easier it is to understand and test. Regards all, John -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Tue, 10 Sep 2013, Ben Finney wrote: The sooner we replace the erroneous “text is ASCII” in the common wisdom with “text is Unicode”, the better. I'd actually argue that it's better to replace the common wisdom with text is binary data, and we should normally look at that text through Unicode eyes. A little less catchy, but more accurate ;) No, that's inaccurate. A sequence of bytes is binary data. Unicode is not binary data. Well now, this is an area that is not actually well-defined. I would say 16-bit Unicode is binary data if you're encoding in base 65,536, just as 8-bit ascii is binary data if you're encoding in base-256. Which is to say: there is no intervening data to suggest a TYPE. -- MarkJ Tacoma, Washington -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Thu, Sep 12, 2013 at 10:25 AM, Mark Janssen dreamingforw...@gmail.com wrote: On Tue, 10 Sep 2013, Ben Finney wrote: The sooner we replace the erroneous “text is ASCII” in the common wisdom with “text is Unicode”, the better. I'd actually argue that it's better to replace the common wisdom with text is binary data, and we should normally look at that text through Unicode eyes. A little less catchy, but more accurate ;) No, that's inaccurate. A sequence of bytes is binary data. Unicode is not binary data. Well now, this is an area that is not actually well-defined. I would say 16-bit Unicode is binary data if you're encoding in base 65,536, just as 8-bit ascii is binary data if you're encoding in base-256. Which is to say: there is no intervening data to suggest a TYPE. Unicode is not 16-bit any more than ASCII is 8-bit. And you used the word encod[e], which is the standard way to turn Unicode into bytes anyway. No, a Unicode string is a series of codepoints - it's most similar to a list of ints than to a stream of bytes. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
Why is this so difficult? Add a Graph class to the collections module (networkx is quite good) and simply check for circular imports. Er? That doesn't address the task of importing a module from a source code file given its path on the filesystem. That's true, I guess was hooked on Python's abstraction mechanism for making the file system invisible. But I like the idea of programming *relative* path addressing, so you can create a sort of name space for your modules. So instead of import /path/to/file.py which makes a system dependency (i.e. *yours*), you could have import TestPackage.collections.bag (using periods for file path separators in keeping with the Pythonic Way). -- MarkJ Tacoma, Washington -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
Unicode is not 16-bit any more than ASCII is 8-bit. And you used the word encod[e], which is the standard way to turn Unicode into bytes anyway. No, a Unicode string is a series of codepoints - it's most similar to a list of ints than to a stream of bytes. Okay, now you're in blah, blah land. --mark -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Thu, Sep 12, 2013 at 10:37 AM, Mark Janssen dreamingforw...@gmail.com wrote: Unicode is not 16-bit any more than ASCII is 8-bit. And you used the word encod[e], which is the standard way to turn Unicode into bytes anyway. No, a Unicode string is a series of codepoints - it's most similar to a list of ints than to a stream of bytes. Okay, now you're in blah, blah land. Eh? Apart from the grammatical oddity (artifact of editing - should be more similar not most similar), I don't see anything wrong in what I said there. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
1) It tried to make Object the parent of every class. Tried, and succeeded. Really? Are you saying you (and the community at-large) always derive from Object as your base class? No one's close enough to God to make that work. Non-sequitor. One doesn't need to be close to a deity to have a single root of the object hierarchy. But wait is it the base (at the bottom of the hierarchy) or is it the parent at the top? You see, you, like everyone else has been using these terms loosely, confusing yourself. 2) It didn't make dicts inherit from sets when they were added to Python. Why would you want dicts to inherit from sets? A dict is-a set of {key:object, key:object} pairs bound together with a colon :. By inheriting from sets you get a lot of useful functionality for free. That you don't know how you could use that functionality is a failure of your imagination, not of the general idea. 3) It used the set literal for dict, so that there's no obvious way to do it. This didn't get changed in Py3k. No, it uses the dict literal for dicts. Right. The dict literal should be {:} -- the one obvious way to do it. Pay me later. And the obvious way to form an empty set is by calling set(), the same as str(), int(), list(), float(), tuple(), dict(), ... Blah, blah. Let me know when you got everyone migrated over to Python.v3. 4?) It allowed [reference] variables to be used as dict keys. This creates a parsing difficulty for me, mentally. Keys should be direct, hashable values, not hidden in a variable name. I don't even understand what you are talking about here. [reference] variables? What does that mean? It's a just a tricky point, that I will wait to comment on. --mark -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Wed, Sep 11, 2013 at 5:37 PM, Mark Janssen dreamingforw...@gmail.com wrote: Unicode is not 16-bit any more than ASCII is 8-bit. And you used the word encod[e], which is the standard way to turn Unicode into bytes anyway. No, a Unicode string is a series of codepoints - it's most similar to a list of ints than to a stream of bytes. Okay, now you're in blah, blah land. --mark -- There's no such thing as 16-bit Unicode. Unicode is a sequence of characters, not a sequence of bytes. It's an abstract thing. To work with it on a computer, you need to use a byte encoding because computers don't deal with with abstract things. UTF-16 is one encoding method that can map any character defined in Unicode to a sequence of bytes. UTF-16 isn't Unicode, it's just a function that maps a byte string to a character string. Python's unicode class is a character string- as far as the user is concerned, it's made up of those abstract character things and not bytes at all. -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
Mark Janssen dreamingforw...@gmail.com writes: Unicode is not 16-bit any more than ASCII is 8-bit. And you used the word encod[e], which is the standard way to turn Unicode into bytes anyway. No, a Unicode string is a series of codepoints - it's most similar to a list of ints than to a stream of bytes. Okay, now you're in blah, blah land. Text is (in the third millennium) Unicode. Unicode text is not binary data and never will be. Unicode text can be *encoded* to binary data, and that data can be *decoded* back to Unicode text. The two are never the same thing. You're demonstrating my point: the pernicious “text is binary data” falsehood needs to be eradicated from everything today's programmers learn. We need the simple facts about the basic difference between text and bytes to be learned by every programmer as early as can feasible. -- \ 德不孤、必有鄰。 (The virtuous are not abandoned, | `\ they shall surely have neighbours.) | _o__) —孔夫子 Confucius, 551 BCE – 479 BCE | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On 9/11/2013 8:49 PM, Mark Janssen wrote: 1) It tried to make Object the parent of every class. Tried, and succeeded. Really? Are you saying you (and the community at-large) always derive from Object as your base class? The name is 'object', and yes, everyone does it because it is automatic. (I am including indirect inheritance, and excluding weird metaclass games.) class C(): pass dir(C) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] Just *where* do you think all those methods come from. C.__bases__ (class 'object',) But wait is it the base (at the bottom of the hierarchy) or is it the parent at the top? This sort of quibbling should be beneath you. A dict is-a set of {key:object, key:object} pairs bound together with a colon :. Yes... but there is a very important additional condition: each key appears only once. Humans are primates, but that is not a sufficient characterization. By inheriting from sets you get a lot of useful functionality for free. Actually, you get a lot of un-useful functionality for free. Because of the extra condition, the rule for adding a key:object pair to a dict is different from the rule for adding a key:object pair to a set of such pairs. The set-union of two dicts is not necessarily a dict. To put is another way, dicts as set subclasses would violate the Liskov Substitution Principle. 'Homogenous' sets (of strings, numbers) would be proper subclasses of set. Right. The dict literal should be {:} and the set literal 'should' be {}, and would be if Python were redesigned from scratch. Is your imagination so stunted that you actually think we did not discuss that when designing Python 3? We did, but Guido rejected switching because he thought it would cause too much pain and discourage adoption of Python 3 even more than the other code-breaking changes that were made. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Thu, Sep 12, 2013 at 10:49 AM, Mark Janssen dreamingforw...@gmail.com wrote: 1) It tried to make Object the parent of every class. Tried, and succeeded. Really? Are you saying you (and the community at-large) always derive from Object as your base class? Uhh, yep? It kinda happens automatically for me: Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32 class Foo: pass Foo.__bases__ (class 'object',) Yeah, I think I'm always deriving from object. Also, if ever I write code that has to run also on 2.x, I'll do that explicitly, to be sure it works the same way. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Python in XKCD today
On 09/11/2013 02:09 PM, Roy Smith wrote: http://xkcd.com/1263/ Nice one! -- ~Jugurtha Hadjar, -- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
On 09/11/2013 08:33 PM, William Bryant wrote: @Jugurtha Hadjar What does user_input.lower() mean/do? Hello, As did other people point out, it returns the lower case of a string. It's not user_input.lower(), it's any_string.lower() For example: Try this on your python prompt mystring = ThIs Is ThE wAy SoMe StUpId PeOpLe WrItE i DoN't KnOw WhY! mystring.lower() -- ~Jugurtha Hadjar, -- https://mail.python.org/mailman/listinfo/python-list
Re: Help please, why doesn't it show the next input?
On 09/12/2013 02:08 AM, Jugurtha Hadjar wrote: Try this on your python prompt mystring = ThIs Is ThE wAy SoMe StUpId PeOpLe WrItE i DoN't KnOw WhY! mystring.lower() This should return: You shouldn't treat people of stupid, but I feel your pain, or let's be more realistic: this is the way some stupid people write i don't know why! -- ~Jugurtha Hadjar, -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Thu, 12 Sep 2013 10:31:26 +1000, Chris Angelico wrote: On Thu, Sep 12, 2013 at 10:25 AM, Mark Janssen dreamingforw...@gmail.com wrote: Well now, this is an area that is not actually well-defined. I would say 16-bit Unicode is binary data if you're encoding in base 65,536, just as 8-bit ascii is binary data if you're encoding in base-256. Which is to say: there is no intervening data to suggest a TYPE. Unicode is not 16-bit any more than ASCII is 8-bit. And you used the word encod[e], which is the standard way to turn Unicode into bytes anyway. No, a Unicode string is a series of codepoints - it's most similar to a list of ints than to a stream of bytes. And not necessarily ints, for that matter. Let's be clear: the most obvious, simple, hardware-efficient way to implement a Unicode string holding arbitrary characters is as an array of 32-bit signed integers restricted to the range 0x0 - 0x10. That gives you a one-to-one mapping of int - code point. But it's not the only way. One could implement Unicode strings using any similar one-to-one mapping. Taking a leaf out of the lambda calculus, I might implement each code point like this: NULL pointer = Code point 0 ^NULL = Code point 1 ^^NULL = Code point 2 ^^^NULL = Code point 3 and so on, where ^ means pointer to. Obviously this is mathematically neat, but practically impractical. Code point U+10 would require a chain of 1114111 pointer-to-pointer-to- pointer before the NULL. But it would work. Or alternatively, I might choose to use floats, mapping (say) 0.25 = U+0376. Or whatever. What we can say, though, is that to represent the full Unicode charset requires 21 bits per code-point, although you can get away with fewer bits if you have some out-of-band mechanism for recognising restricted subsets of the charset. (E.g. you could use just 7 bits if you only handled the characters in ASCII, or just 3 bits if you only cared about decimal digits.) In practice, computers tend to be much faster when working with multiples of 8 bits, so we use 32 bits instead of 21. In that sense, Unicode is a 32 bit character set. But Unicode is absolutely not a 16 bit character set. And of course you can use *more* bits than 21, or 32. If you had a computer where the native word-size was (say) 50 bits, it would make sense to use 50 bits per character. As for the question of binary data versus text, well, that's a thorny one, because really *everything* in a computer is binary data, since it's stored using bits. But we can choose to *interpret* some binary data as text, just as we interpret some binary data as pictures, sound files, video, Powerpoint presentations, and so forth. A reasonable way of defining a text file might be: If you decode the bytes making up an alleged text file into code-points, using the correct encoding (which needs to be known a priori, or stored out of band somehow), then provided that none of the code-points have Unicode General Category Cc, Cf, Cs, Co or Cn (control, format, surrogate, private-use, non-character/reserved), you can claim that it is at least plausible that the file contains text. Whether that text is meaningful is another story. You might wish to allow Cf and possibly even Co (format and private-use), depending on the application. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
In article 523127e2$0$29988$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: just 3 bits if you only cared about decimal digits. That's a neat trick. -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Thu, Sep 12, 2013 at 12:43 PM, Roy Smith r...@panix.com wrote: In article 523127e2$0$29988$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: just 3 bits if you only cared about decimal digits. That's a neat trick. It is! It's one of the fancy things we can do in the Land Downunder. By the time we've dodged spiders, snakes, and Drop Bears, squeezing ten options into three bits is easy! Of course, we always keep a fourth bit lying around for when the tourists come through. 33% extra profit when we sell them the unnecessary spare bit. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Parsing an html line and pulling out only numbers that meet a certain criteria
I am using line.rfind to parse a particular line of html code. For example, this is the line of html code I am parsing: strong class=temp79spandeg;/span/strongspan class=lowspanLo/span 56spandeg;/span/span and this is the code I use to split the line to (in this case) pull out the '79'. position0 = line.rfind('{}'.format(date1.strftime(%a))) if position0 0 : self.high0 = lines[line_number + 4].split('span')[0].split('')[-1] Now I need to only pull out that number if it is =94 and =37. If it does not meet this criteria, I don't want anything to happen. Any ideas? Thank you in advance! -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On 11 September 2013 11:38, Burak Arslan burak.ars...@arskom.com.tr wrote: On 09/10/13 09:09, Steven D'Aprano wrote: What design mistakes, traps or gotchas do you think Python has? My favourite gotcha is this: elt, = elts It's a nice and compact way to do both: assert len(elts) == 0 elt = elts[0] but it sure looks strange at first sight. As a bonus, it works on any iterable, not just ones that support __getitem__. I very much enjoy the [elt] = elts spelling, although I don't get how this is a gotcha. It's just a semi-obscure usage of unpacking. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python GUI?
On 09/11/2013 02:55 PM, eamonn...@gmail.com wrote: PyQT -- You have a GUI designer, so I'm not going to count that What do you mean? Gtk has a GUI designer too. what of it? I, personally, really like wxPython, but I also really like Tkinter. I've messed with PyGTK, but I'd choose wxPython over it. Not me. wxWidgets' event model is way too MFC-esque for me. Does it still use event numbers that you define? Shudder. Gtk and Qt's method of signals and slots is by far the most powerful and flexible. Have you got anything to say on what one I should be using(excluding PyQT because it has a DD designer :( )? Is Tkinter really dead? Should I stick with wxPython? I still don't understand why you are excluding Qt. All modern toolkits are heading towards imperative GUI design. With Gtk I use Glade and GtkBuilder. My GUI is in a nice XML file that gets loaded and manipulated by my python class. It's extremely clean. And in the case of compiled programming, you don't have to recompile just to tweak something like a layout. At the moment if someone were to come in from scratch and ask what GUI toolkit to use, I would answer Qt with PySide. It's the most cross-platform of all the toolkits, and it's one of the most mature. Gtk is also good, but Windows and Mac support is always lagging behind X11, and it's not as good at fitting into the native look and feel. Also, with wxPython, it has kind of a flow layout like JFrame, whereas it will adjust it's layout to look like a native Mac App, Windows app or Linux App, correct? It'll look almost identical, right? Not that it matters, I'm just curious! :D Possibly. I know Qt and Gtk both can flip the button orders, etc to look more native. And all good toolkits give you layout managers so you never have to resort to fixed layouts. Qt's layout system is very different than Gtk's, but once you get the feel of it (use the Qt Designer program!), it makes a lot of sense. -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Wed, 11 Sep 2013 22:43:20 -0400, Roy Smith wrote: In article 523127e2$0$29988$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: just 3 bits if you only cared about decimal digits. That's a neat trick. Well obviously it's compressed. :-) Sorry for the typo, I meant 4. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
By the way, please keep attributions for those you are quoting. It is rude otherwise. On Wed, 11 Sep 2013 17:49:09 -0700, Mark Janssen wrote: 1) It tried to make Object the parent of every class. Tried, and succeeded. Really? Are you saying you (and the community at-large) always derive from Object as your base class? Not directly, that would be silly. But if you derive from int, or dict, or ValueError, or any other type, you're indirectly deriving from object since they derive from object. In Python 3, *everything* derives from object. In Python 2, the situation is slightly different in that there are still legacy (old style or classic) classes, but that's an old version of Python. It's not quite obsolete as yet, but in another five years or so it will be. The important thing is, as of *right now*, there are Python versions where object is the base class of every class. No one's close enough to God to make that work. Non-sequitor. One doesn't need to be close to a deity to have a single root of the object hierarchy. But wait is it the base (at the bottom of the hierarchy) or is it the parent at the top? You see, you, like everyone else has been using these terms loosely, confusing yourself. Depends on whether I'm standing on my head or not. Or more importantly, it depends on whether I visualise my hierarchy going top-down or bottom-up. Both are relevant, and both end up with the *exact same hierarchy* with only the direction reversed. 2) It didn't make dicts inherit from sets when they were added to Python. Why would you want dicts to inherit from sets? A dict is-a set of {key:object, key:object} pairs bound together with a colon :. It certainly is not. py {'x': []} # Lists can be in dicts. {'x': []} py set([[]]) # But not in sets. Traceback (most recent call last): File stdin, line 1, in module TypeError: unhashable type: 'list' By inheriting from sets you get a lot of useful functionality for free. That you don't know how you could use that functionality is a failure of your imagination, not of the general idea. No you don't. You get a bunch of ill-defined methods that don't make sense on dicts. For example: what is the intersection of these two dicts? {'a': 1, 'b': 3} {'a': 3, 'b': 5} I can see SIX possibilities: {} {'a': 1, 'b': 3} {'a': 3, 'b': 5} {'a': 3} {'b': 3} raise an exception 3) It used the set literal for dict, so that there's no obvious way to do it. This didn't get changed in Py3k. No, it uses the dict literal for dicts. Right. The dict literal should be {:} -- the one obvious way to do it. I don't agree it is obvious. It is as obvious as (,) being the empty tuple or [,] being the empty list. Pay me later. And the obvious way to form an empty set is by calling set(), the same as str(), int(), list(), float(), tuple(), dict(), ... Blah, blah. Let me know when you got everyone migrated over to Python.v3. What does this have to do with Python 3? It works fine in Python 2. 4?) It allowed [reference] variables to be used as dict keys. This creates a parsing difficulty for me, mentally. Keys should be direct, hashable values, not hidden in a variable name. I don't even understand what you are talking about here. [reference] variables? What does that mean? It's a just a tricky point, that I will wait to comment on. I'm looking forward to an explanation, as I'm intrigued. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Parsing an html line and pulling out only numbers that meet a certain criteria
In d9a020cc-89eb-4cb4-b884-abe156f18...@googlegroups.com Cory Mottice cmott...@gmail.com writes: I am using line.rfind to parse a particular line of html code. For example, this is the line of html code I am parsing: strong class=temp79spandeg;/span/strongspan class=lowspanLo/span 56spandeg;/span/span and this is the code I use to split the line to (in this case) pull out the '79'. position0 = line.rfind('{}'.format(date1.strftime(%a))) if position0 0 : self.high0 = lines[line_number + 4].split('span')[0].split('')[-1] Now I need to only pull out that number if it is =94 and =37. If it does not meet this criteria, I don't want anything to happen. Any ideas? Thank you in advance! If you have the string value in a variable, you can call int() to convert it to an integer, like so: x = 57 # string value y = int(x) # integer value But what do you mean by you don't want anything to happen? Obviously you have to do the work of grabbing the correct part of the line and parsing it to an integer value; you can't magically undo that work if the value isn't in the desired range. Do you mean that you don't want to assign it to self.high0? That's easy; assign it to a temporary variable first, and only assign it to self.high0 if it falls in the desired range. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, The Gashlycrumb Tinies -- https://mail.python.org/mailman/listinfo/python-list
[issue18962] Add special case for single iterator in heapq.merge function
Roundup Robot added the comment: New changeset 0e70bf1f32a3 by Raymond Hettinger in branch 'default': Issue #18962: Optimize the single iterator case for heapq.merge() http://hg.python.org/cpython/rev/0e70bf1f32a3 -- nosy: +python-dev ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18962 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18962] Add special case for single iterator in heapq.merge function
Changes by Raymond Hettinger raymond.hettin...@gmail.com: -- resolution: - fixed status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18962 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19002] ``dir`` function does not work correctly with classes.
New submission from David Halter: I recently stumbled over the ``dir`` function not working correctly with classes. This means that ``dir(object)`` won't list ``object.__bases__`` or ``object.__subclasses`` (and many other useful methods). I think that we should change that. The C function ``type_dir`` (in ``Objects/typeobject.c``) has a documentation entry which states: We deliberately don't suck up its __class__, as methods belonging to the metaclass would probably be more confusing than helpful. I think that that's not true. The current behaviour of ``dir`` is way more confusing, since ``dir`` is typically the tool how we find out about magic methods. I wrote about it in more details here: http://jedidjah.ch/code/2013/9/8/wrong_dir_function/ -- components: Interpreter Core messages: 197471 nosy: davidhalter priority: normal severity: normal status: open title: ``dir`` function does not work correctly with classes. type: behavior versions: Python 2.6, Python 2.7, Python 3.1, Python 3.2, Python 3.3, Python 3.4, Python 3.5 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19002 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18962] Add special case for single iterator in heapq.merge function
Wouter Bolsterlee added the comment: Thanks for the quick response. Btw, do I understand correctly code cleanups are not welcome, even when touching the code anyway? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18962 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18962] Add special case for single iterator in heapq.merge function
Wouter Bolsterlee added the comment: (In case you missed it: my latest comment included a cleaned up version of an earlier patch.) -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18962 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue17797] Visual C++ 11.0 reports fileno(stdin) == 0 for non-console program
Daniel added the comment: Here are some solutions which might help you until MS fixed the bug. 1) Even if the subsystem is Windows one solution is to call AllocConsole() before Py_Initialize() to create a console. 2) Second Solution: If you don't want to open a console and your application has its own output window you could redirect stdout/stderr/stdin with freopen to a temp file first. (e.g: freopen(file.txt,w,stdout);) Call freopen for all std handles before you call Py_Initialize(). You can keep the redirection to the file or after Py_Initialize() succeeded you change the redirection now in Python by redirect sys.stdout to the place you want. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue17797 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue18987] distutils.utils.get_platform() for 32-bit Python on a 64-bit machine
Sam Ferencik added the comment: Unfortunately, I don't have a patch. Some thoughts: To discover a 32-bit interpreter running on a 64-bit system, we could use platform.architecture(), which returns platform.architecture() ('32bit', 'ELF') What then, though? How do you turn '32bit' to 'linux-i386'? The naive solution would be to hard-code this as an exception: - if 32-on-64, use 'i386' - otherwise, use os.uname()[4], i.e. 'i386' or 'x86_64' I suspect that's ultra naive, though. The get_platform() code deals with a number of Unix-like systems (Solaris, AIX, ...). Even if we accepted this solution only for Linux, leaving the other OSs broken, is 'i386' always the right answer, or would 'i586' or similar be appropriate in some cases? We could also take inspiration from Mac OS (_osx_support.get_platform_osx()), which basically ignores os.uname()[4] completely and constructs the return value from a set of hard-coded values ('i386' being one of them). What do you think? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue18987 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19002] ``dir`` function does not work correctly with classes.
Changes by Ethan Furman et...@stoneleaf.us: -- nosy: +ethan.furman ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19002 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue19002] ``dir`` function does not work correctly with classes.
Changes by Ethan Furman et...@stoneleaf.us: -- versions: -Python 2.6, Python 2.7, Python 3.1, Python 3.5 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue19002 ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com