7 ms·
Python Facts
- rhdoenges 15y ago> How can addition be more easier than this? print eval('+'.join(map(str, [1, 1]))) Seriously?
- mapleoin 15y agoIt would be nice if all these "facts" could be downloadable under a CC license.
- ronreiter 15y agogood idea. will do
- ralph 15y ago"View All" only give me the titles, I still need to look at each individually. It's a bit like a FAQ that doesn't put multiple Qs and As on the same page; a pain. Part of the benefit would be scrolling through at speed, no comments interspersed, learning quickly, skipping already-known at a glance. Could be N per page to handle when total number is large as long as N >= 20. I'm looking at View All thinking some look interesting but I haven't the time to click round it all.
- veyron 15y agoIs this approach (sending the commands to a backend) preferable to a javascript-based repl (using something like emscripten)?
- ronreiter 15y agoyes, but it's jailed pretty good and it's not a lot of CPU power to execute, so it's OK.
- RyanMcGreal 15y agoIt allows `eval()` to run. Please see this: http://diveintopython3.ep.io/advanced-iterators.html#eval http://diveintopython3.ep.io/advanced-iterators.html#eval
- nanotone 15y agoIt looks like you're using GAE. Not having much experience with it, I'm wondering if GAE provides the CPU jailing, or did you have to write some voodoo yourself? I ask because it's trivially easy to send a statement containing a single bytecode that takes a really long time to execute, at least in CPython: >>> print 999 * 0 # => 0, so not a bandwidth issue If I send this to your backend in a bunch of tabs (I didn't) could that be a DoS? Also, are you thinking of putting the backend code on github? EDIT: HN swallowed my exponentiation. That should read "print nine to the nine to the nine, times zero". Without the times zero, that's a huge number.
- d0mine 15y ago>>> print 9**9**9*0 # => 0 Text after a blank line that is indented by two or more spaces is reproduced verbatim. http://news.ycombinator.com/formatdoc http://news.ycombinator.com/formatdoc (the help link is in the bottom-right corner)
- MostAwesomeDude 15y ago"There should be one -- and preferably only one -- obvious way to do it. If the implementation is easy to explain, it may be a good idea." AFAIK there is not a JavaScript version of Python which is fully compliant with the Python 2.6 specification.
- cschmidt 15y agoIf whoever created this stops by, I got an error message on this snippet: import itertools name_generator = itertools.imap("name-{}".format,itertools.count()) # to get the next name: new_name = next(name_generator)
- ronreiter 15y agothanks
- rplnt 15y agohttp://facts.learnpython.org/2003 http://facts.learnpython.org/2003 gives me error as well
- zalew 15y agoI came across another error map(int, "10 20 30".split()) Output:
- AgentConundrum 15y agoWhat's the error you're getting? That code worked fine for me (2.7.2) >>> import itertools >>> name_generator = itertools.imap("name-{}".format,itertools.count()) >>> new_name = next(name_generator) >>> new_name 'name-0' >>> new_name = next(name_generator) >>> new_name 'name-1'
- koenigdavidmj 15y agoIn 2.6 or earlier replace the last line with: new_name = name_generator.next()
- neq 15y agoThe python version available is 2.5.2 yet some of the tips use newer features and syntax. This is definitely a problem.
- c4urself 15y agocool initative! seems like snippet numbers are random: 1 works but 2, 3, 4 don't. it would be nice to have categories or tags and a place to let others contribute snippets. i like the fact that the snippets are small and communicate one thing, otherwise it's comparable to the ActiveState website. It would be nice to make it downloadable in a pdf. EDIT: Never mind I see there is an "Add" button.
- pace 15y agoCan it be true that the Python coverage on HN is overproportional compared to its real world usage? If I look around the world is full of Ruby and Rails. Sites, libs, meetups, developers, everything is on Ruby or Ruby on Rails. Python and Django devs are so damn rare in real world -- I just know two of 100. Not that I don't like Python but I am really wondering why Python gets such a strong coverage on HN. Every second day there's some Python thing on HN. BTW with Clojure it's the same but Clojure is something new, so I understand the visibility there. Please don't downvote -- it's nothing against Python, I just want to see if the Python base increased or something happend I've missed. Thanks How can it be? EDIT: Thanks to all for the replies. What's interesting about this thread: I got tons of downvotes (besides upvotes) for the first comment. So, I assume this Python vs Ruby discussion seems to be a very emotional topic. Thanks to the replies I have now a better understanding that Python is older and dominant in a many non-web environments. My impression is still that especially in web environments we have much more pace and development in Rails than Django (just compare what DHH put in 3.1, Coffee, Sass, etc. -- no flame war just a questions dear downvoters, don't freak out again)--Rails feels just more vibrant regarding web dev. But Rails is not Ruby ;-) It's just that I see all the Python stuff on HN -- which is slightly focussed on online/web/Internet -- and I really considered learning Python for web dev until I checked http://www.google.de/trends?q=python+django%2C+ruby+rails&ctab=0&geo=all&date=all&sort=0 http://www.google.de/trends?q=python+django%2C+ruby+rails... EDIT2: but there's a new rising star: http://www.google.de/trends?q=python+django%2C+ruby+rails%2C+node.js&ctab=0&geo=all&date=all&sort=0 http://www.google.de/trends?q=python+django%2C+ruby+rails%2C...
- JanezStupar 15y agoConversely I know 20 Python Django/Pyramid developers and one Rails developer.
- pace 15y agowhere r u located?
- JanezStupar 15y ago
- gren 15y agoNot convinced by this one: http://facts.learnpython.org/1004 http://facts.learnpython.org/1004
- RyanMcGreal 15y agoI prefer: [int(x) for x in "10 20 30".split(' ')]
- omaranto 15y agoWhy? It's longer and requires an extra check to make sure that it's the same variable mentioned twice (i.e., you read to read it carefully to distinguish from [int(x) for y in "10 20 30".split(' ')]). Is it just that since comprehensions are more commonly used you think some people might forget what map does nad have to look it up?
- trafficlight 15y agoThis one doesn't give me any output.
- ThePawnBreak 15y agoYou need to print the value.
- brown9-2 15y agoLove this idea, I think one small way to look some snippets look nicer would be to remove the absolute width/height on the snippet text box (to prevent the need for scrollbars).
- michaelschade 15y agoNeat project. One critique: I don't like having only five lines of the snippet visible at any given time, it makes it harder to easily understand what's going on in some of your longer snippets. I suspect that the five line limitation was done so that the "Give me another one!" button was always in relatively the same place and easily clickable (I appreciate that), but perhaps there could be a small, duplicate text link up above the snippet for this purpose too, thereby also letting you make the snippets longer.
- ronreiter 15y agoI like the idea. Yes, there's the need for both. I'm thinking about just making the text size variable according to the number of lines in the snippet - I think that makes more sense.
- michaelschade 15y agoThat's a thought, but even moderately sized snippets might get hard to read. I think this concern is especially valid because the rest of the text on the site is large and easily readable from a distance, so making the most important text–the snippet–smaller would be out of place.
- pietro 15y agoJust change the layout. The 'play' button and execution results are equally logically placed under the code. That should give you enough space for snippets of any size.
- ryall 15y agoJust make the area re-sizable. That way you can flick through them easily, but re-size ones you want to study.
- antirez 15y ago"While passing a single value to string formatting works, it's dangerous and can fail in subtle ways". AKA Python design errors.
- irahul 15y ago> it's dangerous and can fail in subtle way The only subtle way it fails, which I can think of is: In [27]: foo = (1,2) In [28]: '%s' % foo --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ----> 1 '%s' % foo TypeError: not all arguments converted during string formatting
- jrockway 15y agoAnd, that's easy to fix: '%s' % (foo,) Ugly, but you can be safe if you don't mind three more bytes of source code.
- irahul 15y agoOr '{}'.format(foo). Personally, I have never faced this issue as: 1. I know/control the input while string formatting. 2 String-formatting tuple comes up rarely.
- jrockway 15y agoI format tuples for debugging on a regular basis, but tend to just wrap every arg to the format string in repr, so this never comes up.
- TheNewAndy 15y agoThis won't solve the immediate problem, but if you use "%r" instead of "%s", python will do the repr() for you.
- msinghai 15y agoWorks fine, except that scrolling doesn't work on an iPad.
- bnegreve 15y agoWhen I click play it says "Error!" running debian linux with ff 3.5
- kisielk 15y agoA bit of a nitpick, but it would be nice if the facts were PEP8 compliant so they encouraged good code style as well as showing off Python features.
- ronreiter 15y agoi'm doing my best to moderate them, but you know how it works...
- drx 15y agoTry https://github.com/jcrocholl/pep8 https://github.com/jcrocholl/pep8 You could show the output of this to the submitter (somewhat bad -- barrier to submission) or flag them yourself so you can correct them occasionally. Examples: $ pep8 optparse.py optparse.py:69:11: E401 multiple imports on one line optparse.py:77:1: E302 expected 2 blank lines, found 1 optparse.py:88:5: E301 expected 1 blank line, found 0 $ pep8 --show-source --show-pep8 testsuite/E111.py testsuite/E111.py:2:3: E111 indentation is not a multiple of four print x ^ Use 4 spaces per indentation level. For really old code that you don't want to mess up, you can continue to use 8-space tabs.
- mapleoin 15y agoSo then you could add something like a 'report' button to allow users to say what they think is mistaken.
- shenberg 15y agoI'm not sure I agree - if it helps get the point of the snippet across more succinctly, it's worth breaking the guidelines.
- cbo 15y agoNot just PEP8-compliant. Some of these are just plain bad. The first one I was greeted with when I opened the site was: > print eval('+'.join(map(str, [1, 1]))) If I ever saw this in production code, I would lose my mind. It's the kind of one-liner I'd expect to find in an obfuscated code competition. It's not intuitively understood, shows a lack of basic Python functionality (the builtin sum() function), and most of all, it's SLOW. As in, 54 times slower than a simple sum -- tested on xrange(1,10) -- on my development Macbook Pro. That said, clicking through some other examples, there are a lot of great Python examples on this site. Just beware of some of them, and always make sure you test new code yourself.
- codecaine 15y agoadded this to my start tabs
- deleted 15y ago[deleted]
- deleted 15y ago[deleted]
- Rexxar 15y agoBug at the third try: http://facts.learnpython.org/7006 http://facts.learnpython.org/7006 Output: Traceback (most recent call last): File "/base/data/home/apps/s~learnpythonjail/1.350338289496947596/main.py", line 99, in post exec(cmd, safe_globals) File "<string>", line 2, in <module> TypeError: 'start' is an invalid keyword argument for this function
- shenberg 15y agoThe start argument was only added in Python 2.6...
- gcr 15y agoNice project, but you NEED some sandboxing. import os print os.listdir('.') print open('turtle.py').read() Edit: It seems like you're doing some; i can't inspect any directories outside the "jail", but being able to list the source code of your scripts is a security risk.
- shenberg 15y agoPython had an implementation of sandboxing (rexec), but gave up plugging the holes people kept finding in it (see http://docs.python.org/library/rexec.html http://docs.python.org/library/rexec.html). The problem is that sandboxing wasn't designed into the language so they don't give users a false sense of security with a bad sandbox. To see the legacy of the sandbox, open an interpreter and run 'del __builtins__' to activate the restricted execution mode. Now, a lot of simple things like the import statement should fail. A good exercise in python internals is to manage to execute unrestricted code from this state via clever use of introspection. Note: 'del __builtins__' is more than just removing access to builtin objects: >>> f = file >>> del __builtins__ >>> f('a.txt','w') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: file() constructor not accessible in restricted mode
- domlebo70 15y agoWould anyone be interested in something like this for Scala?
- hardik988 15y agoA small bug: Go on any random fact, eg: http://facts.learnpython.org/3007 http://facts.learnpython.org/3007 Click on "Add your own", and then click go Back in your browser. The snippet is blank. This is Chrome 15 on Windows 7.
- kisielk 15y agoSorry, I think I broke your site. I realized based on one of the comments here that you seem to be running a persistent interpreter and then just running the code snippets. So I decided to see what would happen if I changed one of them... So I found the snipped that did something like import collections foo = collections.defaultdict and added collections.defaultdict = None to the end of it. Next time I ran it the original snippet just gave a stack trace. Oops :) Anyway, looks like you need to work on sandboxing the snippets some more. I would have sent this to you via email or other means, but I couldn't find any other way to contact you in your HN profile or on your site.