title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Is there a way to convert indentation in Python code to braces?
118,643
<p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
73
2008-09-23T01:33:13Z
453,806
<p>There are various answers explaining how to do this. But I would recommend not taking this route. While you could use a script to do the conversion, it would make it hard to work on a team project.</p> <p>My recommendation would be to configure your screen reader to announce the tabs. This isn't as annoying as it sounds, since it would only say "indent 5" rather than "tab tab tab tab tab". Furthermore, the indentation would only be read whenever it changed, so you could go through an entire block of code without hearing the indentation level. In this way hearing the indentation is no more verbose than hearing the braces.</p> <p>As I don't know which operating system or screen reader you use I unfortunately can't give the exact steps for achieving this.</p>
1
2009-01-17T18:49:29Z
[ "python", "accessibility", "blind", "blindness" ]
Is there a way to convert indentation in Python code to braces?
118,643
<p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
73
2008-09-23T01:33:13Z
1,479,855
<p><a href="http://en.wikipedia.org/wiki/Edsger%5FDijkstra" rel="nofollow">Edsger Dijkstra</a> used <a href="http://en.wikipedia.org/wiki/Guarded%5FCommand%5FLanguage#Selection%3A%5Fif" rel="nofollow">if ~ fi</a> and <a href="http://en.wikipedia.org/wiki/Guarded%5FCommand%5FLanguage#Repetition%3A%5Fdo" rel="nofollow">do ~ od</a> in his "Guarded Command Language", these appear to originate from the <a href="https://sourceforge.net/projects/algol68/" rel="nofollow">Algol68</a>. There were also some example python guarded blocks used in <a href="http://rosettacode.org/wiki/Python" rel="nofollow">RosettaCode.org</a>. </p> <pre><code>fi = od = yrt = end = lambda object: None; class MyClass(object): def myfunction(self, arg1, arg2): for i in range(arg1) :# do if i &gt; 5 :# then print i fi od # or end(i) # end(myfunction) end(MyClass) </code></pre> <p>Whitespace mangled python code can be unambiguously unmangled and reindented if one uses guarded blocks if/fi, do/od &amp; try/yrt together with semicolons ";" to separate statements. Excellent for unambiguous magazine listings or cut/pasting from web pages.</p> <p>It should be easy enough to write a short python program to insert/remove the guard blocks and semicolons.</p>
0
2009-09-25T22:36:33Z
[ "python", "accessibility", "blind", "blindness" ]
Is there a way to convert indentation in Python code to braces?
118,643
<p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
73
2008-09-23T01:33:13Z
11,382,155
<p>All of these "no you can't" types of answers are really annoying. Of course you can.</p> <p>It's a hack, but you can do it.</p> <p><a href="http://timhatch.com/projects/pybraces/" rel="nofollow">http://timhatch.com/projects/pybraces/</a></p> <p>uses a custom encoding to convert braces to indented blocks before handing it off to the interpreter.</p> <hr> <p>As an aside, and as someone new to python - I don't accept the reasoning behind not even <em>allowing</em> braces/generic block delimiters ... apart from that being the preference of the python devs. Braces at least won't get eaten accidentally if you're doing some automatic processing of your code or working in an editor that doesn't understand that white space is important. If you're generating code automatically, it's handy to not have to keep track of indent levels. If you want to use python to do a perl-esque one-liner, you're automatically crippled. If nothing else, just as a safeguard. What if your 1000 line python program gets all of its tabs eaten? You're going to go line-by-line and figure out where the indenting should be?</p> <p>Asking about it will invariably get a tongue-in-cheek response like "just do 'from __ future __ import braces'", "configure your IDE correctly", "it's better anyway so get used to it" ... </p> <p>I see their point, but hey, if i wanted to, i could put a semicolon after every single line. So I don't understand why everyone is so adamant about the braces thing. If you need your language to force you to indent properly, you're not doing it right in the first place.</p> <p>Just my 2c - I'm going to use braces anyway.</p>
3
2012-07-08T09:42:09Z
[ "python", "accessibility", "blind", "blindness" ]
Is there a way to convert indentation in Python code to braces?
118,643
<p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
73
2008-09-23T01:33:13Z
11,996,920
<p>Searching an accessible Python IDE, found this and decided to answer. Under Windows with JAWS:</p> <ol> <li>Go to Settings Center by pressing <kbd>JawsKey</kbd>+<kbd>6</kbd> (on the number row above the letters) in your favorite text editor. If JAWS prompts to create a new configuration file, agree.</li> <li>In the search field, type "indent"</li> <li>There will be only one result: "Say indent characters". Turn this on.</li> <li>Enjoy!</li> </ol> <p>The only thing that is frustrating for us is that we can't enjoy code examples on websites (since indent speaking in browsers is not too comfortable — it generates superfluous speech).</p> <p>Happy coding from another Python beginner).</p>
2
2012-08-16T23:34:46Z
[ "python", "accessibility", "blind", "blindness" ]
Is there a way to convert indentation in Python code to braces?
118,643
<p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
73
2008-09-23T01:33:13Z
13,292,321
<p>If you're on Windows, I strongly recommend you take a look at EdSharp from: <a href="http://empowermentzone.com/EdSharp.htm">http://empowermentzone.com/EdSharp.htm</a> It supports all of the leading Windows screenreaders, it can be configured to speak the indentation levels of code, or it has a built in utility called PyBrace that can convert to and from braces syntax if you want to do that instead, and it supports all kinds of other features programmers have come to expect in our text editors. I've been using it for years, for everything from PHP to JavaScript to HTML to Python, and I love it. </p>
6
2012-11-08T15:40:12Z
[ "python", "accessibility", "blind", "blindness" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
118,671
<p>I haven't tested it, but I'd say it'll most likely work with the latest IPy2.</p> <p>As for distribution, it's very simple. Use the -X:SaveAssemblies option to compile your Python code down to a binary and then ship it with your other DLLs and the IPy dependencies.</p>
0
2008-09-23T01:42:48Z
[ ".net", "python", "ironpython" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
118,680
<p>If BeautifulSoup doesn't work on IronPython, it's because IronPython doesn't implement the whole Python language (the same way CPython does). BeautifulSoup is pure-python, no C-extensions, so the only problem is the compatibility of IronPython with CPython in terms of Python source code.There shouldn't be one, but if there is, the error will be obvious ("no module named ...", "no method named ...", etc.). Google says that only one of BS's tests fails with IronPython. it probably works, and that test may be fixed by now. I wouldn't know.</p> <p>Try it out and see, would be my advice, unless anybody has anything more concrete.</p>
5
2008-09-23T01:43:40Z
[ ".net", "python", "ironpython" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
118,713
<p>I've tested and used BeautifulSoup with both IPy 1.1 and 2.0 (forget which beta, but this was a few months back). Leave a comment if you are still having trouble and I'll dig out my test code and post it.</p>
8
2008-09-23T01:53:58Z
[ ".net", "python", "ironpython" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
119,713
<p>If you have the complete standard library and the real <code>re</code> module (google for IronPython community edition) it might work. But IronPython is an incredible bad python implementation, I wouldn't count on that.</p> <p>Besides, give <code>html5lib</code> a try. That parser parses with the same rules firefox parses documents.</p>
-2
2008-09-23T07:58:31Z
[ ".net", "python", "ironpython" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
123,532
<p>Regarding the second part of your question, you can use the DLR Hosting APIs to run IronPython code from within a C# application. The DLR hosting spec is <a href="http://compilerlab.members.winisp.net/dlr-spec-hosting.pdf" rel="nofollow">here</a>. This <a href="http://blogs.msdn.com/seshadripv/" rel="nofollow">blog</a> also contains some sample hosting applications</p>
1
2008-09-23T20:10:02Z
[ ".net", "python", "ironpython" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
123,589
<p>Also, regarding one of the previous comments about compiling with -X:SaveAssemblies - that is wrong. -X:SaveAssemblies is meant as a debugging feature. There is a API meant for compiling python code into binaries. <a href="http://blogs.msdn.com/srivatsn/archive/2008/08/06/static-compilation-of-ironpython-scripts.aspx" rel="nofollow">This post</a> explains the API and the difference between the two modes.</p>
2
2008-09-23T20:16:56Z
[ ".net", "python", "ironpython" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
170,856
<p>I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was anything comparable available for .NET, but then I found the <a href="http://www.codeplex.com/htmlagilitypack">HTML Agility Pack</a> and if anything I think I've actually gained some maintainability over BeautifulSoup. It takes clean or crufty HTML and produces a elegant XML DOM from it that can be queried via XPath. With a couple lines of code you can even get back a raw XDocument and then <a href="http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx">craft your queries in LINQ to XML</a>. Honestly, if web scraping is your goal, this is about the cleanest solution you are likely to find.</p> <p><b>Edit</b></p> <p>Here is a simple (read: not robust at all) example that parses out the US House of Representatives holiday schedule:</p> <pre><code>using System; using System.Collections.Generic; using HtmlAgilityPack; namespace GovParsingTest { class Program { static void Main(string[] args) { HtmlWeb hw = new HtmlWeb(); string url = @"http://www.house.gov/house/House_Calendar.shtml"; HtmlDocument doc = hw.Load(url); HtmlNode docNode = doc.DocumentNode; HtmlNode div = docNode.SelectSingleNode("//div[@id='primary']"); HtmlNodeCollection tableRows = div.SelectNodes(".//tr"); foreach (HtmlNode row in tableRows) { HtmlNodeCollection cells = row.SelectNodes(".//td"); HtmlNode dateNode = cells[0]; HtmlNode eventNode = cells[1]; while (eventNode.HasChildNodes) { eventNode = eventNode.FirstChild; } Console.WriteLine(dateNode.InnerText); Console.WriteLine(eventNode.InnerText); Console.WriteLine(); } //Console.WriteLine(div.InnerHtml); Console.ReadKey(); } } } </code></pre>
33
2008-10-04T19:04:21Z
[ ".net", "python", "ironpython" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
287,247
<p>We are distributing a 40k line IronPython application. We have not been able to compile the whole thing into a single binary distributable. Instead we have been distributing it as a zillion tiny dlls, one for each IronPython module. This works fine though.</p> <p>However, on the newer release, IronPython 2.0, we have a recent spike which seems to be able to compile everything into a single binary file. This also results in faster application start-up too (module importing is faster.) Hopefully this spike will migrate into our main tree in the next few days.</p> <p>To do the distribution we are using WiX, which is a Microsoft internal tool for creating msi installs, that has been open-sourced (or made freely available, at least.) It has given us no problems, even though our install has some quite fiddly requirements. I will definitely look at using WiX to distribute other IronPython projects in the future.</p>
1
2008-11-13T15:31:20Z
[ ".net", "python", "ironpython" ]
Iron python, beautiful soup, win32 app
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
20
2008-09-23T01:37:48Z
6,549,240
<p>Seems to work just fine with IronPython 2.7. Just need to point it at the right folder and away you go:</p> <pre><code>D:\Code&gt;ipy IronPython 2.7 (2.7.0.40) on .NET 4.0.30319.235 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path.append("D:\Code\IronPython\BeautifulSoup-3.2.0") &gt;&gt;&gt; import urllib2 &gt;&gt;&gt; from BeautifulSoup import BeautifulSoup &gt;&gt;&gt; page = urllib2.urlopen("http://www.example.com") &gt;&gt;&gt; soup = BeautifulSoup(page) &lt;string&gt;:1: DeprecationWarning: object.__new__() takes no parameters &gt;&gt;&gt; i = soup('img')[0] &gt;&gt;&gt; i['src'] 'http://example.com/blah.png' </code></pre>
1
2011-07-01T14:24:05Z
[ ".net", "python", "ironpython" ]
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
18
2008-09-23T02:38:04Z
118,820
<p>I have both installed:</p> <pre><code>$ which python /usr/bin/python $ which python2.5 /opt/local/bin/python2.5 </code></pre> <p>I also added the following line to my <code>.profile</code>:</p> <pre><code>export PATH=/opt/local/bin:/opt/local/sbin:$PATH </code></pre>
22
2008-09-23T02:40:05Z
[ "python", "osx", "osx-leopard", "macports" ]
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
18
2008-09-23T02:38:04Z
118,821
<p>Instead of uninstalling the built-in Python, install the MacPorts version and then modify your <code>$PATH</code> to have the MacPorts version first.</p> <p>For example, if MacPorts installs <code>/usr/local/bin/python</code>, then modify your <code>.bashrc</code> to include <code>PATH=/usr/local/bin:$PATH</code> at the end.</p>
4
2008-09-23T02:40:13Z
[ "python", "osx", "osx-leopard", "macports" ]
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
18
2008-09-23T02:38:04Z
118,823
<p>I wouldn't uninstall it since many scripts will expect python to be in the usual places when they do not follow convention and use <code>#!/usr/bin/env python</code>. You should simply edit your <code>.profile</code> or <code>.bash_profile</code> so the macports binaries are the first in your path.</p> <p>Your <code>.profile</code> should have this line: </p> <pre><code>export PATH=/opt/local/bin:/opt/local/sbin:$PATH </code></pre> <p>If not, add it in, and now your shell will search macport's <code>bin/</code> first, and should find macports python before system python.</p>
3
2008-09-23T02:41:15Z
[ "python", "osx", "osx-leopard", "macports" ]
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
18
2008-09-23T02:38:04Z
118,824
<p>Don't. Apple ships various system utilities that rely on the system Python (and particularly the Python "framework" build); removing it will cause you problems.</p> <p>Instead, modify your PATH environ variable in your <code>~/.bash_profile</code> to put <code>/opt/local/bin</code> first.</p>
29
2008-09-23T02:41:53Z
[ "python", "osx", "osx-leopard", "macports" ]
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
18
2008-09-23T02:38:04Z
604,946
<p>Use the <a href="http://www.macports.org/ports.php?by=name&amp;substr=python%5Fselect">python_select</a> port to switch python interpreters.</p> <pre><code>sudo port install python25 sudo port install python_select sudo python_select python25 </code></pre> <p>This will symlink <code>/opt/local/bin/python</code> to the selected version. Then export <code>PATH</code> as described above.</p>
20
2009-03-03T03:04:32Z
[ "python", "osx", "osx-leopard", "macports" ]
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
18
2008-09-23T02:38:04Z
2,621,262
<p>The current Macports installer does the .profile PATH modification automatically.</p>
3
2010-04-12T10:22:33Z
[ "python", "osx", "osx-leopard", "macports" ]
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
18
2008-09-23T02:38:04Z
6,166,416
<p><code>python_select</code> is now deprecated, use this instead:</p> <pre><code>sudo port select python python26 </code></pre>
17
2011-05-29T07:17:41Z
[ "python", "osx", "osx-leopard", "macports" ]
Adding code to __init__.py
119,167
<p>I'm taking a look at how the model system in django works and I noticed something that I don't understand.</p> <p>I know that you create an empty <code>__init__.py</code> file to specify that the current directory is a package. And that you can set some variable in <code>__init__.py</code> so that import * works properly.</p> <p>But django adds a bunch of from ... import ... statements and defines a bunch of classes in <code>__init__.py</code>. Why? Doesn't this just make things look messy? Is there a reason that requires this code in <code>__init__.py</code>?</p>
67
2008-09-23T04:41:18Z
119,178
<p>All imports in <code>__init__.py</code> are made available when you import the package (directory) that contains it.</p> <p>Example:</p> <p><code>./dir/__init__.py</code>:</p> <pre><code>import something </code></pre> <p><code>./test.py</code>:</p> <pre><code>import dir # can now use dir.something </code></pre> <p>EDIT: forgot to mention, the code in <code>__init__.py</code> runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code.</p> <p>EDIT2: dgrant pointed out to a possible confusion in my example. In <code>__init__.py</code> <code>import something</code> can import any module, not necessary from the package. For example, we can replace it with <code>import datetime</code>, then in our top level <code>test.py</code> both of these snippets will work:</p> <pre><code>import dir print dir.datetime.datetime.now() </code></pre> <p>and</p> <pre><code>import dir.some_module_in_dir print dir.datetime.datetime.now() </code></pre> <p>The bottom line is: all names assigned in <code>__init__.py</code>, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.</p>
63
2008-09-23T04:47:51Z
[ "python", "initialization", "package" ]
Adding code to __init__.py
119,167
<p>I'm taking a look at how the model system in django works and I noticed something that I don't understand.</p> <p>I know that you create an empty <code>__init__.py</code> file to specify that the current directory is a package. And that you can set some variable in <code>__init__.py</code> so that import * works properly.</p> <p>But django adds a bunch of from ... import ... statements and defines a bunch of classes in <code>__init__.py</code>. Why? Doesn't this just make things look messy? Is there a reason that requires this code in <code>__init__.py</code>?</p>
67
2008-09-23T04:41:18Z
119,346
<p>It's just personal preference really, and has to do with the layout of your python modules.</p> <p>Let's say you have a module called <code>erikutils</code>. There are two ways that it can be a module, either you have a file called <em>erikutils.py</em> on your <code>sys.path</code> or you have a directory called <em>erikutils</em> on your <code>sys.path</code> with an empty <em><code>__init__.py</code></em> file inside it. Then let's say you have a bunch of modules called <code>fileutils</code>, <code>procutils</code>, <code>parseutils</code> and you want those to be sub-modules under <code>erikutils</code>. So you make some .py files called <em>fileutils.py</em>, <em>procutils.py</em>, and <em>parseutils.py</em>:</p> <pre><code>erikutils __init__.py fileutils.py procutils.py parseutils.py </code></pre> <p>Maybe you have a few functions that just don't belong in the <code>fileutils</code>, <code>procutils</code>, or <code>parseutils</code> modules. And let's say you don't feel like creating a new module called <code>miscutils</code>. AND, you'd like to be able to call the function like so:</p> <pre><code>erikutils.foo() erikutils.bar() </code></pre> <p>rather than doing</p> <pre><code>erikutils.miscutils.foo() erikutils.miscutils.bar() </code></pre> <p>So because the <code>erikutils</code> module is a directory, not a file, we have to define it's functions inside the <em><code>__init__.py</code></em> file.</p> <p>In django, the best example I can think of is <code>django.db.models.fields</code>. ALL the django *Field classes are defined in the <em><code>__init__.py</code></em> file in the <em>django/db/models/fields</em> directory. I guess they did this because they didn't want to cram everything into a hypothetical <em>django/db/models/fields.py</em> model, so they split it out into a few submodules (<em>related.py</em>, <em>files.py</em>, for example) and they stuck the made *Field definitions in the fields module itself (hence, <em><code>__init__.py</code></em>).</p>
30
2008-09-23T06:12:15Z
[ "python", "initialization", "package" ]
Adding code to __init__.py
119,167
<p>I'm taking a look at how the model system in django works and I noticed something that I don't understand.</p> <p>I know that you create an empty <code>__init__.py</code> file to specify that the current directory is a package. And that you can set some variable in <code>__init__.py</code> so that import * works properly.</p> <p>But django adds a bunch of from ... import ... statements and defines a bunch of classes in <code>__init__.py</code>. Why? Doesn't this just make things look messy? Is there a reason that requires this code in <code>__init__.py</code>?</p>
67
2008-09-23T04:41:18Z
126,499
<p>Using the <code>__init__.py</code> file allows you to make the internal package structure invisible from the outside. If the internal structure changes (e.g. because you split one fat module into two) you only have to adjust the <code>__init__.py</code> file, but not the code that depends on the package. You can also make parts of your package invisible, e.g. if they are not ready for general usage.</p> <p>Note that you can use the <code>del</code> command, so a typical <code>__init__.py</code> may look like this:</p> <pre><code>from somemodule import some_function1, some_function2, SomeObject del somemodule </code></pre> <p>Now if you decide to split <code>somemodule</code> the new <code>__init__.py</code> might be:</p> <pre><code>from somemodule1 import some_function1, some_function2 from somemodule2 import SomeObject del somemodule1 del somemodule2 </code></pre> <p>From the outside the package still looks exactly as before.</p>
24
2008-09-24T11:02:55Z
[ "python", "initialization", "package" ]
Is it good to switch from c# to python?
119,198
<p>Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?</p>
2
2008-09-23T04:53:13Z
119,205
<p>Depends on what you will use it for. If you're making enterprise Windows forms applications, I don't think switching to Python would be a good idea.</p> <p>Also, it is possible to still use Python on the .NET CLR with IronPython.</p>
1
2008-09-23T04:55:35Z
[ "c#", "python" ]
Is it good to switch from c# to python?
119,198
<p>Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?</p>
2
2008-09-23T04:53:13Z
119,208
<p>Both are useful for different purposes. C# is a pretty good all-rounder, python's dynamic nature makes it more suitable for RAD experiences such as site building. </p> <p>I don't think your career will suffer if you were competant in both. To get going with Python consider an IDE with Python support such as Eclipse+PyDev or ActiveIDE's Komodo. (I found a subscription to Safari Bookshelf online really invaluable too!)</p>
1
2008-09-23T04:56:18Z
[ "c#", "python" ]
Is it good to switch from c# to python?
119,198
<p>Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?</p>
2
2008-09-23T04:53:13Z
119,215
<p>What's better is inherently subjective. If you like Python's syntax - learn it. It will probably be harder to find a Python job, C# and .NET in general seem to be more popular, but this may change.</p> <p>I also think it's worth to know at least one scripting language, even if your main job doesn't require it. Python is not a bad candidate.</p>
1
2008-09-23T04:59:52Z
[ "c#", "python" ]
Is it good to switch from c# to python?
119,198
<p>Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?</p>
2
2008-09-23T04:53:13Z
119,219
<p>Personally I feel you can write good/bad code in any language. I also firmly believe in learning a <a href="http://www.linuxjournal.com/article/6536" rel="nofollow">new language every so often</a> for the sake of learning itself. On those grounds I say if you have the time just go for it. Python is a great language that many others are inspired from.</p> <p>Whether one framework or language is better or not depends on your definition of better. Do you want more work as a programmer? Do you want to develop business apps quickly, or do you want to compute 3D matrix transformations? </p> <p>Once you've answered those questions you might find yourself taking a completely different direction, say F# if you had particular interest in the financial or scientific sector.</p>
5
2008-09-23T05:02:16Z
[ "c#", "python" ]
Is it good to switch from c# to python?
119,198
<p>Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?</p>
2
2008-09-23T04:53:13Z
119,224
<p>It can't hurt to learn Python, especially considering some of the heavy weights (Google) are really getting behind it.</p> <p>As for the actual use, it all depends on the application. Use the best tool for the job.</p>
3
2008-09-23T05:03:23Z
[ "c#", "python" ]
Is it good to switch from c# to python?
119,198
<p>Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?</p>
2
2008-09-23T04:53:13Z
119,232
<p>Yes, you should learn Python, but it has nothing to do with Python or C# being better. It is really about making you a better programmer.</p> <p>Learning Python will give you a whole new perspective on programmer and how problems can be solved. It's like lifting weights, except you're building up the developer muscles in your mind. </p> <p>For example, if you've only ever programmed using a statically typed language then it is hard to imagine any other way. Learning Python will teach you that there is an alternative in the form of dynamic typing.</p> <p>For a summary of Pythons benefits: <a href="http://www.cmswire.com/cms/enterprise-20/2007s-programming-language-of-the-year-is-002221.php">http://www.cmswire.com/cms/enterprise-20/2007s-programming-language-of-the-year-is-002221.php</a></p>
15
2008-09-23T05:05:53Z
[ "c#", "python" ]
Is it good to switch from c# to python?
119,198
<p>Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?</p>
2
2008-09-23T04:53:13Z
119,386
<p>Never stop learning! </p> <p>That said, how can you compare the two? How good is Python support in .Net? Is there C# support in Google App Engine? It really depends what your target system is. Therefore, the more languages you have the better equipped you will be to tackle different challenges.</p>
2
2008-09-23T06:28:30Z
[ "c#", "python" ]
Is it good to switch from c# to python?
119,198
<p>Currently I am developing in the .Net environment using C# but I want to know whether it is worth learning python. I'm thinking of learning the Django framework. What is better?</p>
2
2008-09-23T04:53:13Z
30,671,567
<p>I have been thinking about this same question myself. I believe however there is still a lot of stuff C# can offer that I want to get good at before I job into Python. Because Python is easier to learn it. One advantage I have found in languages is not the language itself but the materials available to learning them. For example let's say you could make a 3D game in JavaScript, but you would be more likely to find resources to do so in C++. Or you could make phone apps in PHP but C# or Java would have more material out there to help you with the phone apps. For me personally I know when I become good at programming in C# I will be able to branch off into other languages. This is the main reason I have chosen to devote most of my time to that one language. I also am learning a little bit of Java and C++ just practice thinking in other languages. I think in the future however Python will become more popular because coding is becoming more popular and Python is the easiest of mainstream languages right now.</p>
0
2015-06-05T16:35:48Z
[ "c#", "python" ]
time length of an mp3 file
119,404
<p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
13
2008-09-23T06:33:14Z
119,418
<p>You can use <a href="http://spacepants.org/src/pymad/">pymad</a>. It's an external library, but don't fall for the Not Invented Here trap. Any particular reason you don't want any external libraries?</p> <pre><code>import mad mf = mad.MadFile("foo.mp3") track_length_in_milliseconds = mf.total_time() </code></pre> <p>Spotted <a href="http://simonwillison.net/2003/Dec/4/mp3lengths/">here</a>.</p> <p>--</p> <p>If you really don't want to use an external library, have a look <a href="http://ibofobi.dk/stuff/mp3/">here</a> and check out how he's done it. Warning: it's complicated.</p>
23
2008-09-23T06:37:50Z
[ "python", "mp3", "media", "music" ]
time length of an mp3 file
119,404
<p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
13
2008-09-23T06:33:14Z
119,436
<p>You might count the number of frames in the file. Each frame has a start code, although I can't recollect the exact value of the start code and I don't have MPEG specs laying around. Each frame has a certain length, around 40ms for MPEG1 layer II.</p> <p>This method works for CBR-files (Constant Bit Rate), how VBR-files work is a completely different story.</p> <p>From the document below:</p> <p>For Layer I files us this formula:</p> <p>FrameLengthInBytes = (12 * BitRate / SampleRate + Padding) * 4</p> <p>For Layer II &amp; III files use this formula:</p> <p>FrameLengthInBytes = 144 * BitRate / SampleRate + Padding </p> <p><a href="http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm" rel="nofollow">Information about MPEG Audio Frame Header</a></p>
0
2008-09-23T06:43:57Z
[ "python", "mp3", "media", "music" ]
time length of an mp3 file
119,404
<p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
13
2008-09-23T06:33:14Z
119,616
<blockquote> <blockquote> <p>Simple, parse MP3 binary blob to calculate something, in Python</p> </blockquote> </blockquote> <p>That sounds like a pretty tall order. I don't know Python, but here's some code I've refactored from another program I once tried to write.</p> <p><strong>Note:</strong> It's in C++ (sorry, it's what I've got). Also, as-is, it'll only handle constant bit rate MPEG 1 Audio Layer 3 files. That <em>should</em> cover most, but I can't make any guarantee as to this working in all situations. Hopefully this does what you want, and hopefully refactoring it into Python is easier than doing it from scratch.</p> <pre class="lang-cpp prettyprint-override"><code>// determines the duration, in seconds, of an MP3; // assumes MPEG 1 (not 2 or 2.5) Audio Layer 3 (not 1 or 2) // constant bit rate (not variable) #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;cstdlib&gt; using namespace std; //Bitrates, assuming MPEG 1 Audio Layer 3 const int bitrates[16] = { 0, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, 0 }; //Intel processors are little-endian; //search Google or see: http://en.wikipedia.org/wiki/Endian int reverse(int i) { int toReturn = 0; toReturn |= ((i &amp; 0x000000FF) &lt;&lt; 24); toReturn |= ((i &amp; 0x0000FF00) &lt;&lt; 8); toReturn |= ((i &amp; 0x00FF0000) &gt;&gt; 8); toReturn |= ((i &amp; 0xFF000000) &gt;&gt; 24); return toReturn; } //In short, data in ID3v2 tags are stored as //"syncsafe integers". This is so the tag info //isn't mistaken for audio data, and attempted to //be "played". For more info, have fun Googling it. int syncsafe(int i) { int toReturn = 0; toReturn |= ((i &amp; 0x7F000000) &gt;&gt; 24); toReturn |= ((i &amp; 0x007F0000) &gt;&gt; 9); toReturn |= ((i &amp; 0x00007F00) &lt;&lt; 6); toReturn |= ((i &amp; 0x0000007F) &lt;&lt; 21); return toReturn; } //How much room does ID3 version 1 tag info //take up at the end of this file (if any)? int id3v1size(ifstream&amp; infile) { streampos savePos = infile.tellg(); //get to 128 bytes from file end infile.seekg(0, ios::end); streampos length = infile.tellg() - (streampos)128; infile.seekg(length); int size; char buffer[3] = {0}; infile.read(buffer, 3); if( buffer[0] == 'T' &amp;&amp; buffer[1] == 'A' &amp;&amp; buffer[2] == 'G' ) size = 128; //found tag data else size = 0; //nothing there infile.seekg(savePos); return size; } //how much room does ID3 version 2 tag info //take up at the beginning of this file (if any) int id3v2size(ifstream&amp; infile) { streampos savePos = infile.tellg(); infile.seekg(0, ios::beg); char buffer[6] = {0}; infile.read(buffer, 6); if( buffer[0] != 'I' || buffer[1] != 'D' || buffer[2] != '3' ) { //no tag data infile.seekg(savePos); return 0; } int size = 0; infile.read(reinterpret_cast&lt;char*&gt;(&amp;size), sizeof(size)); size = syncsafe(size); infile.seekg(savePos); //"size" doesn't include the 10 byte ID3v2 header return size + 10; } int main(int argCount, char* argValues[]) { //you'll have to change this ifstream infile("C:/Music/Bush - Comedown.mp3", ios::binary); if(!infile.is_open()) { infile.close(); cout &lt;&lt; "Error opening file" &lt;&lt; endl; system("PAUSE"); return 0; } //determine beginning and end of primary frame data (not ID3 tags) infile.seekg(0, ios::end); streampos dataEnd = infile.tellg(); infile.seekg(0, ios::beg); streampos dataBegin = 0; dataEnd -= id3v1size(infile); dataBegin += id3v2size(infile); infile.seekg(dataBegin,ios::beg); //determine bitrate based on header for first frame of audio data int headerBytes = 0; infile.read(reinterpret_cast&lt;char*&gt;(&amp;headerBytes),sizeof(headerBytes)); headerBytes = reverse(headerBytes); int bitrate = bitrates[(int)((headerBytes &gt;&gt; 12) &amp; 0xF)]; //calculate duration, in seconds int duration = (dataEnd - dataBegin)/(bitrate/8); infile.close(); //print duration in minutes : seconds cout &lt;&lt; duration/60 &lt;&lt; ":" &lt;&lt; duration%60 &lt;&lt; endl; system("PAUSE"); return 0; } </code></pre>
7
2008-09-23T07:37:41Z
[ "python", "mp3", "media", "music" ]
time length of an mp3 file
119,404
<p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
13
2008-09-23T06:33:14Z
5,059,165
<p>For google followers' sake, here are a few more external libs:</p> <p>mpg321 -t</p> <p>ffmpeg -i</p> <p>midentify (mplayer basically) see <a href="http://stackoverflow.com/questions/497681/using-mplayer-to-determine-length-of-audio-video-file">Using mplayer to determine length of audio/video file</a></p> <p>mencoder (pass it invalid params, it will spit out an error message but also give you info on the file in question, ex $ mencoder inputfile.mp3 -o fake)</p> <p>mediainfo program <a href="http://mediainfo.sourceforge.net/en">http://mediainfo.sourceforge.net/en</a></p> <p>exiftool</p> <p>the linux "file" command</p> <p>mp3info</p> <p>sox</p> <p>refs: <a href="http://superuser.com/questions/36871/linux-command-line-utility-to-determine-mp3-bitrate">http://superuser.com/questions/36871/linux-command-line-utility-to-determine-mp3-bitrate</a></p> <p><a href="http://www.ruby-forum.com/topic/139468">http://www.ruby-forum.com/topic/139468</a></p> <p><a href="http://stackoverflow.com/questions/993971/mp3-length-in-milliseconds">mp3 length in milliseconds</a></p> <p>(making this a wiki for others to add to).</p> <p>and libs: .net: naudio, java: jlayer, c: libmad</p> <p>Cheers!</p>
9
2011-02-20T18:49:58Z
[ "python", "mp3", "media", "music" ]
time length of an mp3 file
119,404
<p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
13
2008-09-23T06:33:14Z
10,132,100
<p>Also take a look at audioread (some linux distros including ubuntu have packages), <a href="https://github.com/sampsyo/audioread" rel="nofollow">https://github.com/sampsyo/audioread</a></p> <pre><code>audio = audioread.audio_open('/path/to/mp3') print audio.channels, audio.samplerate, audio.duration </code></pre>
3
2012-04-12T21:26:14Z
[ "python", "mp3", "media", "music" ]
time length of an mp3 file
119,404
<p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
13
2008-09-23T06:33:14Z
29,028,948
<p>simply use <code>mutagen</code></p> <pre><code>$pip install mutagen </code></pre> <p>use it in python shell:</p> <pre><code>from mutagen.mp3 import MP3 audio = MP3(file_path) print audio.info.length </code></pre>
3
2015-03-13T09:37:59Z
[ "python", "mp3", "media", "music" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
119,576
<p>Because <a href="http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces">PEP-8</a> tells us to use spaces :)</p>
180
2008-09-23T07:28:00Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
119,594
<p>I recently came across an article titled <a href="http://www.secnetix.de/olli/Python/block_indentation.hawk">Python: Myths about Indentation</a> which discusses this and related questions. The article has good reasons for recommending the use of spaces when writing Python code, but there is certainly room for disagreement.</p> <p>I believe it's true that most Python programmers use spaces only.</p>
21
2008-09-23T07:31:58Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
119,598
<p>The most "pythonic" way is to use 4 spaces per indentation level. The Python interpreter will however recognize spaces or tabs. The only gottcha is you <strong>must never mix spaces and tabs</strong>, pick one or the other. That said, the specification recommends spaces, most developers use spaces, so unless you have a really good reason not to, I'd say go with spaces.</p>
51
2008-09-23T07:32:35Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
119,693
<p>Editor-to-editor mistake occurs when you have <em>mixed indentation within a file</em>. This arises as follows: a block of code is indented with 4 spaces, and then one indentation level "in", it is indented with tabs. Now the heathen who did this (mixing tabs and spaces) had it so his tabs are also 4 spaces, so he sees no problems, and python sees no problems. Now our victim comes along later, and he has his tabs set to 8 spaces. Now our victims thinks the code looks all whacked, and <em>fixes it</em> by <em>removing one level of indentation</em>, which now makes the code <em>look</em> like it is still 2 levels of indentation, but is <em>really one level</em>. At this point all hell breaks loose.</p> <p>The lesson here is that you should never, ever, mix tabs and spaces. If you keep to this, then it is easy to reindent your code into spaces or tabs, regardless of which you personally use. The best way to ensure you don't mix tabs and spaces is to always run python with <code>-tt</code>, which will produce an error when tabs and spaces are mixed.</p> <p>As for tabs and spaces, I personally use tabs so separate indentation from appearance - it is much easier to change the appearance of code when it is indented with tabs than it is with spaces. I know this runs contrary to what 99% of python programmers do, but that is my <em>personal</em> preference, and it is easy in any case to convert a tabbed file to a spaced one. The reverse is not always true, since you can accidentally whack out 4 spaces in strings etc.</p>
6
2008-09-23T07:54:59Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
119,703
<p>You CAN mix tabs and spaces... BUT a tab is considered to be the same indentation as 8 spaces, so unless your editor is set up to consider a tab to be 8 spaces you're asking for trouble when mixing them.</p>
9
2008-09-23T07:56:34Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
120,249
<p>People will use different editors on the same code. These editors will represent a tab on the screen differently. If you're working on an editor that represents a tab as 4 spaces, if you indent the first line by <code>"\t "</code> and the second by <code>"\t\t"</code>, they'll look like they're in the same indent level: 8 spaces. </p> <p>The python interpreter doesn't know your editor, and he has to interpret the tab as some amount of indentation. In fact, it interprets the tab as 8 spaces, so he'll see different indent levels than what you intended: 12 spaces for the first line, 16 spaces for the second. You're toasted. </p>
-2
2008-09-23T10:35:03Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
120,265
<p>Use an editor that allows you to insert spaces up to the tabstop when you press the TAB key, instead of inserting a \t character. And then forget about it.</p>
13
2008-09-23T10:38:35Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
122,181
<p>I use two space indentation and an editor (kwrite) that inserts spaces instead of tabs when I hit the tab key.</p>
0
2008-09-23T16:37:41Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
132,652
<p>The only inconvenience I experience with using spaces instead of tabs is that you cannot easily remove an indentation level, you have to remove 4 spaces instead of just one tab.</p>
9
2008-09-25T11:11:33Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
1,777,008
<p>Tired of chasing after indentation typos ( 8 spaces ? no, 7 oops 9 ... ) I switched my sources to 'tabs only'.</p> <p><strong>1 tab == 1 indent level, full stop</strong></p> <p>The point is: if you want to display the indentation as 4, 8 or pi / 12 character width, just change the settings in your text editor, don't mess with the code :p</p> <p>(personally I use 4 char width tab... but some would prefer 3 or 8 space, or even use variable width fonts !!)</p>
315
2009-11-21T22:30:21Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
2,389,168
<p>My main reason for using tabs over spaces is the backspace key. If I'm on a line and I want to backspace-remove an indentation on just that one line I have to hit backspace 4x if it were spaces; whereas, I only need to hit it once if it's a tab.</p> <p>I will continue to use tabs because—like was stated before—it's easier to convert from tabs to spaces, but not the other way around.</p> <p>I'm thinking I want to write a simple program that converts code with spaces into code with tabs, because I freaking hate spaces. They drive me up the wall!</p> <p>Oh! And using the arrow keys to navigate left and right is always a pain in the ass when it's spaces.</p> <p><em>UPDATE: Sublime Text 3 now deletes a full soft tab with the backspace key; though, arrow-key navigation is still tedious.</em></p> <p><em>UPDATE: See some cool animated GIFs that illustrate my points above and more at <a href="https://web.archive.org/web/20150607064227/http://jedmao.ghost.io/2014/08/20/tabs-vs-spaces-the-age-old-war" rel="nofollow">Tabs vs. Spaces, We Meet Again</a></em></p>
43
2010-03-05T18:55:48Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
2,868,181
<p>USE AN EDITOR THAT DISPLAYS TAB CHARACTERS (all whitespace, for that matter). You're programming, not writing an article.</p> <p>I use tabs. There's no room for a one-space error in the tabs (if you can see them). The problem IS that people use different editors, and the only common thing in the world is: tab==indent, as above. Some bloke comes in with the tab key set to the wrong number of spaces or does it manually and makes a mess. TABs and use a real editor. (This isn't just contrary to the PEP, it's about C/C++ and other whitespace-agnostic languages too).</p> <p>/steps down from soapbox</p>
56
2010-05-19T18:14:16Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
6,312,842
<p>Everyone has different preferences on how much code should be indented. Let's say you share code with someone and he or she has different preferences regarding indentation. If the indentations are in tabs, your friend can always just change the tab width in their editor settings. However, if the indentations are in spaces, your friend will actually have to change the source code if he or she want to set it to their preference. Then when you get your friend's changes, you may decide to change it back to your preference. In this case, you will either have to deal with the tedium of changing indentation levels back and forth, or one person must adopt the other's preferences in indentation level. If both you and your friend use tabs, the fact that you have different preferences is a non-issue, as you can each see different indentation levels while the code remains unchanged. That is why, in my opinion, tabs are better than spaces for indentation in all programming languages. </p>
3
2011-06-10T22:55:45Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
6,338,054
<p><em>Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out.</em> -- Georg Brandl</p>
130
2011-06-14T01:02:09Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
7,773,894
<p>I know this is an old question, but it still comes up near the top of a google search on the topic, and I think I can add a little value. </p> <p>When I was first learning python, I was put off a little by the idea of significant white space, as most languages to use it are inflexible. That said, I was impressed by python's ability to understand a variety of indentation styles. When considering what style to use for a new project, I think it is important to keep two things in mind. </p> <ol> <li><p>First, it is important to understand how python interprets indentation. Bryan Oakley mentioned the possibility of off-by-one errors when using tabs, but this actually isn't possible with the default interpreter settings. There is a better explanation of this in <em>Learning Python</em>, from O'Rielly Media. </p> <p>Basically, there is a variable (which can be changed by including a comment at the top of a source file # tab-width: ) that defines the tab width. When python encounters a tab, it increases the indentation distance <em>to the next multiple of tab-width</em>. Thus if a space followed by a tab is entered along the left of the file, the next multiple of tab-width is 8. If a tab by itself is entered, the same thing happens. </p> <p>In this way, it is safe, if your editor is configured properly, to use tabs, and even to mix tabs and spaces. As long as you set your editor's tab stops to the same width as the python tab-width declaration (or 8 if it is absent). It is generally a bad idea to use an editor with a tab width of other than 8 spaces, unless you specify the tab-width in the file. </p></li> <li><p>Second, much of the syntactic design of python is to encourage code readability and consistent style between programmers on the same project. That said, the question becomes, for any particular project, what will make the code the most readable <em>by the people working on the project</em>. Certainly it is a good idea to keep a consistent indentation style, but depending on the platform and the editor used by the project, a different style may make sense for different projects. If there is no compelling reason to not conform to pep8, then it makes sense to do so, because it will conform to what people expect. </p> <p>I have encountered projects that use a mix of tabs and spaces successfully. Basically spaces are used to indent small sections, where the fact that it is in an indented section is relatively unimportant; while tabs are used to draw the reader's attention to a large structural feature. For example, classes begin with a tab, which simple conditional checks inside a function use 2 spaces. </p> <p>Tabs are also useful when dealing with large blocks of text indented multiple levels. When you drop out of 3-4 levels of indentation, it is far easier to line up with the proper tab than it is to line up with the proper number of spaces. If a project doesn't use the pep8 recommended style, it is probably best to write a style guide into a file somewhere so that the indentation pattern remains consistent and other people can read explicitly how to configure their editor to match. </p></li> </ol> <p>Also, python2.x has an option <code>-t</code> to issue warnings about mixed tabs and spaces and <code>-tt</code> to issue an error. This only applied to mixed tabs and spaces inside the same scope. python3 assumes <code>-tt</code> and so far as I've found, there is no way to disable that check.</p>
8
2011-10-14T21:43:41Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
7,882,145
<p>Tabs rule. Same argument for nested loops and you want to bring the outer loop "back" 1 level. Tip: If you want to convert old space-riddled python code into tabs use the TabOut utility available as an executable on <a href="http://www.textpad.com/add-ons/">http://www.textpad.com/add-ons/</a>.</p>
8
2011-10-24T21:21:55Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
8,315,782
<p>I'm primarily a C++ programmer, but sometimes my projects include small amounts of Python. I use tabs to indent my C++ code. This means that I have three options here:</p> <ol> <li>Use tabs in C++ and spaces in Python. This allows my C++ files to remain as they are and I follow the PEP-8 recommendation, but I am inconsistent within my project.</li> <li>Change my C++ code to use spaces. This allows all of my files within my project to be consistent, and I follow the PEP-8 recommendation, but requires me to go back and change all of my C++ files. I consider this a bad thing because I prefer tabs.</li> <li>Use tabs in my C++ code and Python code. This makes my entire project consistent and allows me to use my preferred indentation style: tabs. The downside is that I am not following the PEP-8 standard.</li> </ol> <p>For my projects, I generally go with option 3.</p>
4
2011-11-29T18:27:38Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
9,534,783
<p>There's a scenario in which tabs simply don't work, namely: depending on the coding style you are using, you might need to indent some lines of code to one-space accuracy, i.e:</p> <pre><code>def foobar(): x = some_call(arg1, arg2) </code></pre> <p>In that case, using purely tabs will not work at all; using tabs for main indent and spaces for sub-indent will work but will violate the hard rule of not mixing the two.</p> <p>This will not be the case however when using a coding style/conventions document that avoids situations like in the above code example.</p>
3
2012-03-02T14:19:42Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
12,974,668
<p>So far as I can tell, here are the pros and cons of tabs vs spaces.</p> <p>Pros of tabs:</p> <ul> <li>Fewer keystrokes required to indent, unindent, and traverse the indentation. (Even if your IDE has some space-indentation cleverness it will never be as good as tabs.)</li> <li>Different programmers can use different tab display sizes as they wish.</li> <li>You can never have the cursor "inside" an indentation character. For example say you are copying some lines, with tabs you can click vaguely near the start of a line to start your selection and you will get all of the first tab. With spaces you're likely to miss the first space character unless you hit the tiny target between it and the margin. Similarly to remove an indentation from a line, most editors don't handle pressing backspace well if your cursor is in the middle of a four-space indentation character. It will usually remove one space. With tabs it works as expected.</li> <li>Consistance with other languages, so you don't have to set your editor up to use, e.g. tabs for C++/Java and spaces for Python.</li> <li>Wrong indentations can be more obvious (i.e. an extra tab is much larger than an extra space).</li> </ul> <p>Cons of tabs:</p> <ul> <li>Most python programmers use spaces so you would be going against convention.</li> <li>Using spaces to align multi-line statements is easier than using tabs. You <em>could</em> use tabs-for-indentation, spaces-for-alignment, but it seems a bit risky in python!</li> </ul> <p>There are some non-issues that are overblown by some people:</p> <ol> <li><p>You might get stray spaces in tabbed indentation that screws things up: Virtually all IDEs/editors support visualising whitespace, and it's almost as likely that you'll get stray tabs in space indentations! I can't see this being a common error anyway. Besides, <em>most</em> indentation errors will be caught by python, and good IDEs should be able to highlight different indentations.</p></li> <li><p>You can't align things easily with tabs: This is true if you're going for character-perfect alignment, but PEP-8 recommends against this, and python doesn't play well with multi-line statements anyway.</p></li> <li><p>People have difference settings for tab display size in their editors so your code will look different in different places: Yeah, that's actually a beneficial feature of tabs.</p></li> </ol> <p>I've started out using spaces to be consistant with other python code, but to be honest it is frustrating enough that I will probably change back to tabs. A lot depends on the capabilities of your IDE, but in my experience no amount of IDE support for space indentation is as good as just using tabs.</p> <p>So unless you <em>really</em> don't like being inconsistant with <em>most</em> (presumably not all!) python code, use tabs and turn on whitespace visualisation and indentation highlighting (if available). The biggest reason for me is ease of selection and the (fairly significant IMO) reduction in keystrokes. Some conventions are stupid.</p>
29
2012-10-19T12:50:32Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
13,087,091
<p>Having recently had to deal with existing code that was mixing spaces and tabs, it's really confusing.</p> <p>When you're mixing (which you really shouldn't do, but which does exist out there unfortunately), it appears that "1 tab == 1 indent level" isn't true.</p> <p>Take the following example (tried with Python 2.7):</p> <pre><code># Mostly use spaces class TestClass: def __init__(self): self.total = 0 def add(self, x): # 8 spaces at the start of the following line: self.total += x # SO automatically uses spaces, but use tabs in the next 2 lines. # One tab at the start of the following line: if self.total &gt; 10: # Two tabs at the start of the following line: print "Greater than 10!" # Now use spaces again. return self.total tc = TestClass() print "Total: %d" % (tc.add(5),) print "Total: %d" % (tc.add(5),) print "Total: %d" % (tc.add(5),) </code></pre> <p>Here, there are 4 spaces before <code>def add(...)</code> (1 identation level), 8 spaces before <code>self.total += x</code> (2 indentation levels), and a single tab before <code>if self.total &gt; 10</code>.</p> <p>Yet, that single tab behaves like 2 indentation levels, since this code works. In contrast, if you replace all tabs with 4 spaces (a single indentation level, that's where the <code>def</code> within the class are), you'll get an unexpected indent error before <code>return</code>, because it's no longer in a <code>def</code> block.</p> <p>This is <em>really</em> confusing with editors that show tabs as 4 characters. Of course, this can be configured, but this also affect source code viewers (e.g. the likes of GitHub) where it's not necessarily easy to configure (or immediately visible that you need to do so, when you can).</p> <p>The tab v.s. space behaviour will always depend on the editor:</p> <ul> <li>If your editor automatically inserts spaces whenever you press tab, it will insert the right number of spaces, so that another editor will display the exact same style.</li> <li>If your editor doesn't use tabs, there's always a chance that you won't notice a line that's using spaces instead of tabs (especially if other editors are used in the project).</li> </ul> <p>Both have their downsides. The bottom line is that there needs to be an arbitrary choice between tabs and spaces, but they should never be mixed. Since you never know how your code is going to be read and used later, it's good to have a convention that affects all python coders. PEP-8 says spaces, so be it.</p> <p>What matters is <a href="http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#262" rel="nofollow">not to do it the Java way</a>:</p> <blockquote> <p>Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).</p> </blockquote> <p>Yes... 1 tab = 2 indentation levels in the Java world! Thankfully, it doesn't have the same significance in terms of compilation.</p>
0
2012-10-26T12:40:09Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
13,092,818
<p>I recently switched from tabs to spaces, for pep8 compliance.</p> <p>I liked tabs previously for two reasons:</p> <ol> <li>With tabs, everyone can see code with the indentation level of their choice; just use spaces on the right and tabs on the left.</li> <li>make wants tabs pretty badly</li> </ol> <p>...but after I realized how important pep8 has become, I switched anyway. As I see it, the chief value of spaces over tabs is simplicity - what you see is what you have. And pep8 compliance. And I came up with a vim rule that would turn on spaces for python files, leaving Makefile's tabbed.</p>
0
2012-10-26T19:00:46Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
17,443,506
<p>Experience and <a href="http://www.python.org/dev/peps/pep-0008/#indentation">PEP-8</a> both clearly conclude that mixing spaces and <code>TAB</code>s is to be avoided. If you want to mix them you have to visualize whitespace in the IDE - but then you loose the advantage of Python's indentation making scopes easily visible. Visualizing whitespace in an IDE clutters the display.</p> <p>If it's either TABs <strong>or</strong> spaces, then it must be spaces for a simple reason: One can switch almost all IDEs and text editors to automatically replace tabs with spaces, but the opposite is not true.</p> <p>Even though there are IDEs that can automatically convert leading spaces in a line to tabs, this will eventually lead to having a mixture of tabs and spaces. Consider multi line statements such as function calls with lots of parameters or doc strings. While "ascii-art" is also to be avoided it may easily happen by accident that a single space is left over after the leading tabs.</p> <p>Other answers brought several arguments in favor of tabs:</p> <ul> <li>Hitting <code>TAB</code> is more efficiently. Of course this is true, but all text editors allow to immediately insert the wanted number of spaces when a tab key is pressed</li> <li>Indenting/Dedenting is easier when just having to remove one tab instead of 2/3/4/8 spaces. True, but most text editors allow to do this automatically anyway: Block select, indent/dedent are basic functionality of a programming editor, like commenting/uncommenting. If a text editor hasn't got this implemented, it should at least have an easy to use macro functionality with which one can achieve the same thing.</li> <li>Different programmers like different indenting widths. That is true, and a clear advantage of using <code>TAB</code>s only. The problem is interaction with other individuals and/or teams. For this to work in the real world, everybody would have to agree on all using <code>TAB</code>s only. Since this has not happened, it does not work anyway. In a real world scenario there's a set of coding guidelines that a project agrees upon anyway, and the method of indentation is certainly one of them - even in other programming languages where the implications are "only" on a visual level.</li> </ul> <p>Imho, the main point that most (if not all) answers are missing here is the interaction between teams or individuals, especially in scenarios where the list of participants is not know at the start. When code meets code either all have to use tabs or all have to use spaces. It cannot be mixed without eventually running into functionality problems. People are not perfect. Tools are not perfect. That's why imho we should not use <code>TAB</code>s at all.</p> <p>No answer is complete without the link that <a href="http://stackoverflow.com/a/119594/923794">Greg provided in his answer</a> already: <a href="http://www.secnetix.de/olli/Python/block_indentation.hawk">Python: Myths about Indentation</a></p>
6
2013-07-03T08:46:14Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
19,744,585
<p>I'm just starting out but I find it much easier to use tabs than spaces, and do not understand the PEP-8 advocation of spaces only. Sublime Text 2 does a great job of visualizing tabs with the off-white vertical, dotted line and while there are cases of me mixing a space or two to line up elements of a list or dictionary, I have not experienced a situation where that would be detrimental thing. </p>
0
2013-11-02T17:14:16Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
21,134,845
<p>In addition to all the arguments already listed, I find this one fairly important (from <a href="http://www.secnetix.de/olli/Python/block_indentation.hawk" rel="nofollow">Myths about indentation</a>):</p> <blockquote> <p>Also, tabs often get destroyed or wrongly converted during copy&amp;paste operations, or when a piece of source code is inserted into a web page or other kind of markup code.</p> </blockquote> <p>Another argument (strongly environment-specific, though) against tabs is that they are <a href="http://stackoverflow.com/a/8747788/209489">sometimes missing on phone keyboards</a>. This could probably be remedied by installing an alternative keyboard, where possible.</p> <p>An argument <strong>for</strong> tabs which no one seemed to have mentioned yet is that 1 tab is 1 character (0x09, 1 byte in the file), while 4 spaces are 4 characters (4 times 0x20, 4 bytes in the file); thus, using spaces results in a 4x waste of space.</p> <p>To conclude this incoherent list of arguments, I would like to cite Tim Peters answer in the <a href="http://bugs.python.org/issue7012#msg93280" rel="nofollow">Issue 7012: Tabs is better than spaces for indentation</a>:</p> <blockquote> <p>The Python "spaces only" standard is for distributed code. Years of early experience taught us beyond doubt that tabs caused endless problems for <em>shared</em> code (...)</p> </blockquote>
0
2014-01-15T10:25:05Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
28,866,396
<p>I have read through all Answers, and most of the up-voted comments, and I believe I still have something to add, so I am going to post my own Answer. (Recently I have been reading a lot about tabs vs spaces while programming in Python.)</p> <p>I will attempt to answer your questions as directly as possible.</p> <blockquote> <p>How does that make a difference?</p> </blockquote> <p>Some editors are configured by default to replace a single tab character with a set number of space characters, but some are not. If everyone uses spaces, this difference in default editor settings can be ignored.</p> <blockquote> <p>Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> </blockquote> <p>Yes there are other valid reasons as pointed out by many answers before me. "PEP-8" says so, however, is NOT one of those reasons. This comes from the self perpetuating myth that PEP-8 is the coding standard for ALL Python codes, when in fact it's just the coding standard for the standard set of Python libraries. Some claim that PEP-8 is widely accepted, and some claim that most Python programmers use spaces instead of tabs. I would like to ask for proofs of these claims, as the number of votes on this site CLEARLY shows that tabs are preferred by the masses. I find it quite unfortunate that you have accepted "PEP8 says so" as the Answer to your question, when in fact there are many other answers that actually explains the relative advantages and disadvantages of spaces and tabs.</p> <blockquote> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p> </blockquote> <p>Depends, and the answer to this final question is where I thought I could actually add some value to this thread. IMHO, regardless of the language being used, the best coding standard to use depends on the situation that you are in:</p> <ul> <li>If you started to work on an already existing code base: don't be difficult, follow the existing coding standard</li> <li>If a team is starting on a new project from scratch: discuss, decide on a coding standard in the beginning as a team, and stick to it</li> <li>If you are going solo: do whatever that makes you feel the happiest and the most productive</li> </ul> <p>So which situation do you fall under?</p> <p>Finally to make my stance clear, for my own solo projects, I use tabs because tabs make more sense to me and I am more productive with tabs.</p>
1
2015-03-04T22:30:58Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
34,819,522
<p>I believe there is a solution to have both:</p> <ol> <li>compatibility with PEP and using spaces </li> <li>convenience of using tab instead of 4 spaces</li> </ol> <p>In notepad++, go to "preferences"--> "tab settings" and choose "Python" from the list on the right. Then make sure "tab size: 4", and check the box "replace [tab] by space". In this case, you can simply use the tab key to indent but notepad++ actually transform that to 4 spaces for you.</p>
1
2016-01-15T20:42:40Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
36,676,458
<p>I feel very strongly that whatever the historical convention, tabs are simply a better choice and should replace spaces in every future line of Python code written. Like kicking out an incompetent tyrant. My rationale for this is: <em>simplicty as a core value</em>. Use two or maybe four characters for the semantic task of one? There's no justification beyond tradition, IMO.</p>
1
2016-04-17T12:26:46Z
[ "python", "coding-style", "indentation", "conventions" ]
Tabs versus spaces in Python programming
119,562
<p>I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.</p> <p>How does that make a difference? Are there other reasons why one would use spaces instead of tabs for Python? Or is it simply not true?</p> <p>Should I switch my editor to insert spaces instead of tabs right away or keep on going like I used to?</p>
207
2008-09-23T07:26:00Z
39,398,626
<p>I love tabs but it is somehow incompatible with another rule I like: the 80 column limit.</p> <p>I one chooses 4 spaces tabs and inserts 10 tabs, then there is space left for 40 characters to fulfill the 80 column limit. If another coder prefers 8 spaces tabs, the same line will appear as 120 characters long and will not appear as a valid 80 columns line!</p> <p>If you want to define a 80 column limit, then you have to choose a length for a tab. In this case having x spaces or a tab of length x does not really make a difference.</p> <p>Edit: related thread: <a href="http://stackoverflow.com/questions/27327746/maintaining-maximum-line-length-when-using-tabs-instead-of-spaces">Maintaining Maximum Line Length When Using Tabs Instead of Spaces?</a></p>
1
2016-09-08T19:17:15Z
[ "python", "coding-style", "indentation", "conventions" ]
Find matching sequences in two binary files
119,651
<p>Let me start off with a bit of background.</p> <p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p> <p>A now, for the actual question.</p> <p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p> <p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p> <pre><code>from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) </code></pre> <p>Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.</p>
1
2008-09-23T07:46:02Z
119,671
<p>Why don't you contact CA and ask them to tell them what they're searching for, for that virus?</p> <p>Or, you could copy the file and change each individual byte until the warning disappeared (may take a while depending on the size).</p> <p>It's possible the virus detection may be a lot more complicated than simply looking for a fixed string.</p>
1
2008-09-23T07:51:00Z
[ "python", "binary", "diff", "antivirus" ]
Find matching sequences in two binary files
119,651
<p>Let me start off with a bit of background.</p> <p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p> <p>A now, for the actual question.</p> <p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p> <p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p> <pre><code>from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) </code></pre> <p>Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.</p>
1
2008-09-23T07:46:02Z
119,698
<p>Hey, better not wonder about the complexity and time these kinds of algorithms need.</p> <p>If you have interest in this - here <a href="http://www.acm.org/jea/ARTICLES/Vol4Nbr2.ps" rel="nofollow">.ps document linked here</a> you can find a good introduction into this thematic.</p> <p>If a good implementation for these algorithms exist, I can not tell. Maybe use google to find some - or put a new topic on stackoverflow :)</p> <p>regards</p>
1
2008-09-23T07:55:47Z
[ "python", "binary", "diff", "antivirus" ]
Find matching sequences in two binary files
119,651
<p>Let me start off with a bit of background.</p> <p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p> <p>A now, for the actual question.</p> <p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p> <p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p> <pre><code>from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) </code></pre> <p>Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.</p>
1
2008-09-23T07:46:02Z
119,718
<p>See <a href="http://en.wikipedia.org/wiki/Longest_common_substring_problem" rel="nofollow">the longest common substring problem</a>. I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays.</p> <p>Using perl <a href="http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm" rel="nofollow">Tree::Suffix</a> might be easiest solution. Apparently it gives all common substrings in a specified length range:</p> <pre><code>@lcs = $tree-&gt;lcs; @lcs = $tree-&gt;lcs($min_len, $max_len); @lcs = $tree-&gt;longest_common_substrings; </code></pre>
3
2008-09-23T08:00:13Z
[ "python", "binary", "diff", "antivirus" ]
Find matching sequences in two binary files
119,651
<p>Let me start off with a bit of background.</p> <p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p> <p>A now, for the actual question.</p> <p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p> <p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p> <pre><code>from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) </code></pre> <p>Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.</p>
1
2008-09-23T07:46:02Z
119,847
<p>Note that even if you did find it this way, there's no guarantee that the longest match is actually the one being looked for. Instead, you may find common initialisation code or string tables added by the same compiler for instance.</p>
2
2008-09-23T08:30:15Z
[ "python", "binary", "diff", "antivirus" ]
Find matching sequences in two binary files
119,651
<p>Let me start off with a bit of background.</p> <p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p> <p>A now, for the actual question.</p> <p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p> <p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p> <pre><code>from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) </code></pre> <p>Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.</p>
1
2008-09-23T07:46:02Z
120,589
<p>I suspect that looking for binary strings isn't going to help you. An install program is likely to be doing some 'suspicious' things. </p> <p>You probably need to talk to CA and spybot about white-listing your installer, or about what is triggering the alert.</p>
0
2008-09-23T12:14:51Z
[ "python", "binary", "diff", "antivirus" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
119,837
<p>I wonder what the original poster tried and which methods worked and not worked for him. I have never worked with DICOM, but a quick google search for "DICOM python" gave several interesting results. It seems that this project: <a href="http://www.creatis.univ-lyon1.fr/Public/Gdcm/" rel="nofollow">http://www.creatis.univ-lyon1.fr/Public/Gdcm/</a> should deliver what you want. It has python bindings and a pretty active mailing list.</p>
0
2008-09-23T08:28:25Z
[ "python", "image", "format", "dicom", "medical" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
120,988
<p>There are some libraries (most often implemented in C/C++) with Python bindings, e.g.:</p> <ul> <li><a href="http://dicomlib.swri.ca/pydicomlib.html" rel="nofollow">pydicomlib</a></li> <li><a href="http://www.creatis.univ-lyon1.fr/Public/Gdcm/" rel="nofollow">gdcmPython</a></li> </ul> <p>However, I'm looking for a native Python implementation to learn more about the DICOM file format.</p>
1
2008-09-23T13:28:56Z
[ "python", "image", "format", "dicom", "medical" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
121,065
<p>Some years ago I was looking for the same thing and found this: <a href="http://cvs.atamai.com/cgi-bin/viewvc.cgi/atamai/dicom/" rel="nofollow">Python DICOM lib</a></p> <p>I wasn't too impressed with the code, but it is native Python reading DICOM files.</p>
3
2008-09-23T13:40:45Z
[ "python", "image", "format", "dicom", "medical" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
177,470
<p>And as of today there's another pure Python package reading DICOM files available: <a href="https://github.com/darcymason/pydicom" rel="nofollow">pydicom</a></p>
13
2008-10-07T07:17:52Z
[ "python", "image", "format", "dicom", "medical" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
213,987
<p>If you want to learn about the DICOM format, "Digital Imaging and Communications in Medicine (DICOM): A Practical Introduction and Survival Guide" by Oleg Pianykh is quite readable and gives a good introduction to key DICOM concepts. Springer-Verlag is the publisher of this book. The full DICOM standard is, of course, the ultimate reference although it is somewhat more intimidating. It is available from NEMA (<a href="http://medical.nema.org">http://medical.nema.org</a>).</p> <p>The file format is actually less esoteric than you might imagine and consists of a preamble followed by a sequence of data elements. The preamble contains the ASCII text "DICM" and several reserved bytes that are unused. Following the preamble is a sequence of data elements. Each data element consists of the size of the element, a two-character ASCII code indicating the value representation, a DICOM tag, and the value. Data elements in the file are ordered by their DICOM tag numbers. The image itself is just another data element with a size, value representation, etc.</p> <p>Value representations specify exactly how to interpret the value. Is it a number? Is it a character string? If it's a character string, is it a short one or a long one and which characters are permitted? The value representation code tells you this.</p> <p>A DICOM tag is a 4 byte hexadecimal code composed of a 2 byte "group" number and a 2 byte "element" number. The group number is an identifier that tells you what information entity the tag applies to (for example, group 0010 refers to the patient and group 0020 refers to the study). The element number identifies the interpretation of the value (items such as the patient's ID number, the series description, etc.). To find out how you should interpret the value, your code looks up the DICOM tag in a dictionary file.</p> <p>There are some other details involved, but that's the essence of it. Probably the most instructive thing you can do to learn about the file format is to take an example DICOM file, look at it with a hex editor, and go through the process of parsing it mentally. I would advise against trying to learn about DICOM by looking at existing open source implementations, at least initially. It is more likely to confuse instead of enlighten. Getting the big picture is more important. Once you have the big picture, then you can descend into subtleties.</p>
8
2008-10-17T22:01:47Z
[ "python", "image", "format", "dicom", "medical" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
377,907
<p>Newer gdcm development now happen here:</p> <p><a href="http://gdcm.sourceforge.net/" rel="nofollow">http://gdcm.sourceforge.net/</a></p> <p>It supports Java and C# on top of python.</p> <p>Why write <strong>yet another</strong> dicom implementation when you can centralize a single C++ implementation and have it accessible to so many different languages</p>
3
2008-12-18T13:55:06Z
[ "python", "image", "format", "dicom", "medical" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
480,245
<p>The library <a href="http://code.google.com/p/pydicom">pydicom</a> mentioned above seems like a great library for accessing the DICOM data structures. To use it to access e.g. RT DOSE data, I guess one would do something like</p> <pre><code>import dicom,numpy dose = dicom.ReadFile("RTDOSE.dcm") d = numpy.fromstring(dose.PixelData,dtype=numpy.int16) d = d.reshape((dose.NumberofFrames,dose.Columns,dose.Rows)) </code></pre> <p>and then, if you're in mayavi,</p> <pre><code>from enthought.mayavi import mlab mlab.pipeline.scalar_field(d) </code></pre> <p>This gives wrong coordinates and dose scaling, but the principle ought to be sound.</p> <p>CT data should be very similar.</p>
7
2009-01-26T15:50:42Z
[ "python", "image", "format", "dicom", "medical" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
810,849
<p>I'm using <a href="https://github.com/darcymason/pydicom" rel="nofollow" title="pydicom">pydicom</a> heavily these days, and it rocks.</p> <p>It's pretty easy to start playing with it: </p> <pre><code>import dicom data = dicom.read_file("yourdicomfile.dcm") </code></pre> <p>To get the interesting stuff out of that "data" object, somehow resembling <a href="http://support.dcmtk.org/docs/dcmdump.html" rel="nofollow" title="dcmdump">dcmdump</a> output:</p> <pre><code>for key in data.dir(): value = getattr(data, key, '') if type(value) is dicom.UID.UID or key == "PixelData": continue print "%s: %s" % (key, value) </code></pre> <p>I think a great way to learn more about the dicom format is to open similar files and write code to compare them according to various aspects: study description, window width and center, pixel representation and so on.</p> <p>Have fun! :)</p>
15
2009-05-01T10:02:07Z
[ "python", "image", "format", "dicom", "medical" ]
Parse DICOM files in native Python
119,684
<p>What is the simplest and most-pythonic way to parse a DICOM file?</p> <p>A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look <a href="http://en.wikipedia.org/wiki/Digital_Imaging_and_Communications_in_Medicine">here</a> for more information). </p> <p>There are some C/C++ libraries that support reading (a subset) of DICOM files. Two or three of them even have Python bindings. A native Python parser would serve two purposes for me: </p> <ol> <li>No need to build any external C/C++ libraries.</li> <li>Learn about the DICOM file format.</li> </ol>
14
2008-09-23T07:53:50Z
5,011,901
<p>DICOM is a real pain... even when the manufacturer sticks to the standards. If you write your own DICOM library you'll find different manufacturers DICOMs are effectively incompatible with other vendors [citation needed].</p> <p>I tried (in my spare time) writing a C dicom parser borrowing heavily from a nice little Ruby parser I came across cunningly called '<a href="http://dicom.rubyforge.org/" rel="nofollow">ruby-dicom</a>'. It is actually very readable code (I looked at one of the smaller earlier versions).</p> <p>The biggest headache was trying to amass a library of the header tags with expected data types. There are the standard-defined tags, and the vendor tags. The ruby-dicom files contain a library of tags in a text format that can be easily inspected.</p> <p>I gave up on the official literature as I was only interested in the file format which seems to only be in one of the 10 or so huge PDFs.</p> <p>My local DICOM files are not compressed and follow standard easy to code bit-arrangements, but be prepared for various compressions and strange 12-bit images stored in 8-bit containers with big or little endianness and no padding bits...</p> <p>I gave up once time became very scarce.</p> <p>Python is probably a far better choice than C for this style of header parsing though...</p>
1
2011-02-16T02:26:29Z
[ "python", "image", "format", "dicom", "medical" ]
Using **kwargs with SimpleXMLRPCServer in python
119,802
<p>I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:</p> <pre><code>server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() </code></pre> <p>I then have a ServiceRemote class that looks like this:</p> <pre><code>def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) </code></pre> <p>So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:</p> <pre><code>@useDb def select(self, db, fields, **kwargs): pass </code></pre> <p>The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.</p> <p>When I call this method, I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.</p> <hr> <p>Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.</p>
11
2008-09-23T08:19:44Z
119,943
<p>As far as I know, the underlying protocol doesn't support named varargs (or any named args for that matter). The workaround for this is to create a wrapper that will take the **kwargs and pass it as an ordinary dictionary to the method you want to call. Something like this</p> <p>Server side:</p> <pre><code>def select_wrapper(self, db, fields, kwargs): """accepts an ordinary dict which can pass through xmlrpc""" return select(self,db,fields, **kwargs) </code></pre> <p>On the client side:</p> <pre><code>def select(self, db, fields, **kwargs): """you can call it with keyword arguments and they will be packed into a dict""" return self.rpcClient.select_wrapper(self,db,fields,kwargs) </code></pre> <p>Disclaimer: the code shows the general idea, you can do it a bit cleaner (for example writing a decorator to do that).</p>
1
2008-09-23T08:56:03Z
[ "python", "simplexmlrpcserver", "xmlrpclib" ]
Using **kwargs with SimpleXMLRPCServer in python
119,802
<p>I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:</p> <pre><code>server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() </code></pre> <p>I then have a ServiceRemote class that looks like this:</p> <pre><code>def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) </code></pre> <p>So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:</p> <pre><code>@useDb def select(self, db, fields, **kwargs): pass </code></pre> <p>The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.</p> <p>When I call this method, I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.</p> <hr> <p>Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.</p>
11
2008-09-23T08:19:44Z
119,963
<p>XML-RPC doesn't really have a concept of 'keyword arguments', so xmlrpclib doesn't try to support them. You would need to pick a convention, then modify xmlrpclib._Method to accept keyword arguments and pass them along using that convention.</p> <p>For instance, I used to work with an XML-RPC server that passed keyword arguments as two arguments, '-KEYWORD' followed by the actual argument, in a flat list. I no longer have access to the code I wrote to access that XML-RPC server from Python, but it was fairly simple, along the lines of:</p> <pre><code>import xmlrpclib _orig_Method = xmlrpclib._Method class KeywordArgMethod(_orig_Method): def __call__(self, *args, **kwargs): if args and kwargs: raise TypeError, "Can't pass both positional and keyword args" args = list(args) for key in kwargs: args.append('-%s' % key.upper()) args.append(kwargs[key]) return _orig_Method.__call__(self, *args) xmlrpclib._Method = KeywordArgMethod </code></pre> <p>It uses monkeypatching because that's by far the easiest method to do this, because of some clunky uses of module globals and name-mangled attributes (__request, for instance) in the ServerProxy class.</p>
3
2008-09-23T09:01:47Z
[ "python", "simplexmlrpcserver", "xmlrpclib" ]
Using **kwargs with SimpleXMLRPCServer in python
119,802
<p>I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:</p> <pre><code>server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() </code></pre> <p>I then have a ServiceRemote class that looks like this:</p> <pre><code>def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) </code></pre> <p>So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:</p> <pre><code>@useDb def select(self, db, fields, **kwargs): pass </code></pre> <p>The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.</p> <p>When I call this method, I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.</p> <hr> <p>Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.</p>
11
2008-09-23T08:19:44Z
119,974
<p>As Thomas Wouters said, XML-RPC does not have keyword arguments. Only the order of arguments matters as far as the protocol is concerned and they can be called anything in XML: arg0, arg1, arg2 is perfectly fine, as is cheese, candy and bacon for the same arguments.</p> <p>Perhaps you should simply rethink your use of the protocol? Using something like document/literal SOAP would be much better than a workaround such as the ones presented in other answers here. Of course, this may not be feasible.</p>
0
2008-09-23T09:06:05Z
[ "python", "simplexmlrpcserver", "xmlrpclib" ]
Using **kwargs with SimpleXMLRPCServer in python
119,802
<p>I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:</p> <pre><code>server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() </code></pre> <p>I then have a ServiceRemote class that looks like this:</p> <pre><code>def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) </code></pre> <p>So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:</p> <pre><code>@useDb def select(self, db, fields, **kwargs): pass </code></pre> <p>The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.</p> <p>When I call this method, I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.</p> <hr> <p>Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.</p>
11
2008-09-23T08:19:44Z
120,225
<p>Using the above advice, I created some working code.</p> <p>Server method wrapper:</p> <pre><code>def unwrap_kwargs(func): def wrapper(*args, **kwargs): print args if args and isinstance(args[-1], list) and len(args[-1]) == 2 and "kwargs" == args[-1][0]: func(*args[:-1], **args[-1][1]) else: func(*args, **kwargs) return wrapper </code></pre> <p>Client setup (do once):</p> <pre><code>_orig_Method = xmlrpclib._Method class KeywordArgMethod(_orig_Method): def __call__(self, *args, **kwargs): args = list(args) if kwargs: args.append(("kwargs", kwargs)) return _orig_Method.__call__(self, *args) xmlrpclib._Method = KeywordArgMethod </code></pre> <p>I tested this, and it supports method with fixed, positional and keyword arguments.</p>
0
2008-09-23T10:26:43Z
[ "python", "simplexmlrpcserver", "xmlrpclib" ]
Using **kwargs with SimpleXMLRPCServer in python
119,802
<p>I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:</p> <pre><code>server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() </code></pre> <p>I then have a ServiceRemote class that looks like this:</p> <pre><code>def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) </code></pre> <p>So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:</p> <pre><code>@useDb def select(self, db, fields, **kwargs): pass </code></pre> <p>The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.</p> <p>When I call this method, I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.</p> <hr> <p>Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.</p>
11
2008-09-23T08:19:44Z
120,291
<p>You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, example below:</p> <h2>Server</h2> <pre><code>from SimpleXMLRPCServer import SimpleXMLRPCServer class Server(object): def __init__(self, hostport): self.server = SimpleXMLRPCServer(hostport) def register_function(self, function, name=None): def _function(args, kwargs): return function(*args, **kwargs) _function.__name__ = function.__name__ self.server.register_function(_function, name) def serve_forever(self): self.server.serve_forever() #example usage server = Server(('localhost', 8000)) def test(arg1, arg2): print 'arg1: %s arg2: %s' % (arg1, arg2) return 0 server.register_function(test) server.serve_forever() </code></pre> <h2>Client</h2> <pre><code>import xmlrpclib class ServerProxy(object): def __init__(self, url): self._xmlrpc_server_proxy = xmlrpclib.ServerProxy(url) def __getattr__(self, name): call_proxy = getattr(self._xmlrpc_server_proxy, name) def _call(*args, **kwargs): return call_proxy(args, kwargs) return _call #example usage server = ServerProxy('http://localhost:8000') server.test(1, 2) server.test(arg2=2, arg1=1) server.test(1, arg2=2) server.test(*[1,2]) server.test(**{'arg1':1, 'arg2':2}) </code></pre>
10
2008-09-23T10:47:37Z
[ "python", "simplexmlrpcserver", "xmlrpclib" ]
Dynamically create variables inside function
119,941
<p>I want to create variables inside function from dictionary.</p> <p>Lets say I have a dictionary</p> <pre><code>bar = {'a': 1, 'b': 2, 'c': 3} </code></pre> <p>and function</p> <pre><code>def foo(): pass </code></pre> <p>What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values</p> <p>So in the end it should be similar to</p> <pre><code>def foo(): a = 1 b = 2 c = 3 </code></pre> <p>Is it possible at all? And if it does, how to do such thing?</p>
1
2008-09-23T08:55:24Z
119,964
<p>Why would you want to do such a thing? Unless you actually do anything with the variables inside the function, a function that just assigns several variables and then discards them is indistinguishable to def foo(): pass (An optimiser would be justified in generating exactly the same bytecode).</p> <p>If you also want to dynamically append code that uses the values, then you could do this by using exec (though unless this is really user-input code, there are almost certainly better ways to do what you want). eg:</p> <pre><code>some_code = ' return a+b+c' exec "def foo():\n " + '\n '.join('%s = %s' for k,v in bar.items()) + '\n' + some_code </code></pre> <p>(Note that your code must be indented to the same level.)</p> <p>On the other hand, if you want to actually assign these values to the function <strong>object</strong> (so you can do foo.a and get 1 - note that your sample code doesn't do this), you can do this by:</p> <pre><code>for key, val in bar.items(): setattr(foo, key, val) </code></pre>
1
2008-09-23T09:02:55Z
[ "python" ]
Dynamically create variables inside function
119,941
<p>I want to create variables inside function from dictionary.</p> <p>Lets say I have a dictionary</p> <pre><code>bar = {'a': 1, 'b': 2, 'c': 3} </code></pre> <p>and function</p> <pre><code>def foo(): pass </code></pre> <p>What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values</p> <p>So in the end it should be similar to</p> <pre><code>def foo(): a = 1 b = 2 c = 3 </code></pre> <p>Is it possible at all? And if it does, how to do such thing?</p>
1
2008-09-23T08:55:24Z
119,983
<p>Your question is not clear.</p> <p>If you want to "set" said variables when foo is not running, no, you can't. There is no frame object yet to "set" the local variables in.</p> <p>If you want to do that in the function body, you shouldn't (check the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="nofollow">python documentation</a> for locals()).</p> <p>However, you <em>could</em> do a <code>foo.__dict__.update(bar)</code>, and then you could access those variables even from inside the function as foo.a, foo.b and foo.c. The question is: why do you want to do that, and why isn't a class more suitable for your purposes?</p>
2
2008-09-23T09:08:06Z
[ "python" ]
Dynamically create variables inside function
119,941
<p>I want to create variables inside function from dictionary.</p> <p>Lets say I have a dictionary</p> <pre><code>bar = {'a': 1, 'b': 2, 'c': 3} </code></pre> <p>and function</p> <pre><code>def foo(): pass </code></pre> <p>What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values</p> <p>So in the end it should be similar to</p> <pre><code>def foo(): a = 1 b = 2 c = 3 </code></pre> <p>Is it possible at all? And if it does, how to do such thing?</p>
1
2008-09-23T08:55:24Z
120,103
<p>Thanks guys, I got the point. I should not do such thing. But if your curios what I tried to do is to somehow short number of lines in my view function in django. I have form with many fields, and instead of receive every field in form of:</p> <pre><code>first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] .. </code></pre> <p>i was thinking to take every attribute name of my form class and loop over it. Like so:</p> <pre><code>for name in ProfileRegistration.base_fields.__dict__['keyOrder']: # and here the variables that i tried to assign </code></pre>
1
2008-09-23T09:46:57Z
[ "python" ]
Dynamically create variables inside function
119,941
<p>I want to create variables inside function from dictionary.</p> <p>Lets say I have a dictionary</p> <pre><code>bar = {'a': 1, 'b': 2, 'c': 3} </code></pre> <p>and function</p> <pre><code>def foo(): pass </code></pre> <p>What I want to do is to create inside function "foo" variables with names of each dictionary item name and values as dictionary item values</p> <p>So in the end it should be similar to</p> <pre><code>def foo(): a = 1 b = 2 c = 3 </code></pre> <p>Is it possible at all? And if it does, how to do such thing?</p>
1
2008-09-23T08:55:24Z
120,214
<p>From your comment, perhaps what you're really looking for is something like a bunch object:</p> <pre><code>class Bunch(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) b=Bunch(**form.cleaned_data) print b.first_name, b.last_name </code></pre> <p>(The ** syntax is because Bunch-type objects are usually used like Bunch(foo=12, bar='blah') - not used in your case but I've left it for consistency with normal usage)</p> <p>This does require a "b." prefix to access your variables, but if you think about it, this is no bad thing. Consider what would happen if someone crafted a POST request to overwrite variables you <em>aren't</em> expecting to be overwritten - it makes it easy to produce crashes and DOS attacks, and could easily introduce more serious security vulnerabilities.</p>
3
2008-09-23T10:23:19Z
[ "python" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
120,073
<p>Try changing the user agent header you are sending in your request to something like: User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008072820 Ubuntu/8.04 (hardy) Firefox/3.0.1 (Linux Mint)</p>
1
2008-09-23T09:41:22Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
120,104
<p>You don't need to impersonate a browser user-agent; any user-agent at all will work, just not a blank one.</p>
1
2008-09-23T09:48:05Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
120,113
<p>It is not a solution to the specific problem. But it might be intersting for you to use the mwclient library (<a href="http://botwiki.sno.cc/wiki/Python:Mwclient">http://botwiki.sno.cc/wiki/Python:Mwclient</a>) instead. That would be so much easier. Especially since you will directly get the article contents which removes the need for you to parse the html.</p> <p>I have used it myself for two projects, and it works very well.</p>
36
2008-09-23T09:49:44Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
120,118
<p>You need to use the <a href="http://docs.python.org/lib/module-urllib2.html" rel="nofollow">urllib2</a> that superseedes <a href="http://docs.python.org/lib/module-urllib.html" rel="nofollow">urllib</a> in the <a href="http://docs.python.org/lib/" rel="nofollow">python std library</a> in order to change the user agent.</p> <p>Straight from the <a href="http://web.archive.org/web/20070202031348/http://docs.python.org/lib/urllib2-examples.html" rel="nofollow">examples</a></p> <pre><code>import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes') page = infile.read() </code></pre>
48
2008-09-23T09:50:39Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
120,121
<p>The general solution I use for any site is to access the page using Firefox and, using an extension such as Firebug, record all details of the HTTP request including any cookies.</p> <p>In your program (in this case in Python) you should try to send a HTTP request as similar as necessary to the one that worked from Firefox. This often includes setting the User-Agent, Referer and Cookie fields, but there may be others.</p>
2
2008-09-23T09:51:31Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
980,529
<p>Rather than trying to trick Wikipedia, you should consider using their <a href="http://www.mediawiki.org/wiki/API">High-Level API</a>.</p>
14
2009-06-11T11:14:20Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
4,168,237
<p>In case you are trying to access Wikipedia content (and don't need any specific information about the page itself), instead of using the api you should just call index.php with 'action=raw' in order to get the wikitext, like in:</p> <p>'http://en.wikipedia.org/w/index.php?<strong>action=raw</strong>&amp;title=Main_Page'</p> <p>Or, if you want the HTML code, use 'action=render' like in:</p> <p>'http://en.wikipedia.org/w/index.php?<strong>action=render</strong>&amp;title=Main_Page'</p> <p>You can also define a section to get just part of the content with something like 'section=3'.</p> <p>You could then access it using the urllib2 module (as sugested in the chosen answer). However, if you need information about the page itself (such as revisions), you'll be better using the mwclient as sugested above.</p> <p>Refer to <a href="http://www.mediawiki.org/wiki/API%3aFAQ#get_the_content_of_a_page_.28wikitext.29.3F" rel="nofollow">MediaWiki's FAQ</a> if you need more information.</p>
3
2010-11-12T19:16:55Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
4,795,011
<pre><code>import urllib s = urllib.urlopen('http://en.wikipedia.org/w/index.php?action=raw&amp;title=Albert_Einstein').read() </code></pre> <p>This seems to work for me without changing the user agent. Without the "action=raw" it does not work for me.</p>
0
2011-01-25T15:02:18Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
25,927,059
<p><a href="http://docs.python-requests.org/en/latest/" rel="nofollow"><code>requests</code></a> is awesome!</p> <p>Here is how you can get the html content with <code>requests</code>:</p> <pre><code>import requests html = requests.get('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes').text </code></pre> <p>Done!</p>
1
2014-09-19T05:37:15Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Fetch a Wikipedia article with Python
120,061
<p>I try to fetch a Wikipedia article with Python's urllib:</p> <pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes") s = f.read() f.close() </code></pre> <p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p> <pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&amp;printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT </code></pre> <p>Wikipedia seems to block request which are not from a standard browser.</p> <p>Anybody know how to work around this?</p>
35
2008-09-23T09:37:21Z
33,645,006
<p>Requesting the page with <a href="https://en.wikipedia.org/wiki/Albert_Einstein?printable=yes" rel="nofollow"><code>?printable=yes</code></a> gives you an entire relatively clean HTML document. <a href="https://en.wikipedia.org/wiki/Albert_Einstein?action=render" rel="nofollow"><code>?action=render</code></a> gives you just the body HTML. Requesting to parse the page through the MediaWiki action API with <a href="https://en.wikipedia.org/w/api.php?action=parse&amp;page=Albert%20Einstein&amp;formatversion=2" rel="nofollow"><code>action=parse</code></a> likewise gives you just the body HTML but would be good if you want finer control, <a href="https://en.wikipedia.org/w/api.php?action=help&amp;modules=parse" rel="nofollow">see parse API help</a>.</p> <p>If you just want the page HTML so you can render it, it's faster and better is to use the new <a href="https://en.wikipedia.org/api/rest_v1/?doc" rel="nofollow">RESTBase</a> API, which returns a cached HTML representation of the page. In this case, <a href="https://en.wikipedia.org/api/rest_v1/page/html/Albert_Einstein" rel="nofollow">https://en.wikipedia.org/api/rest_v1/page/html/Albert_Einstein</a>.</p> <p>As of November 2015, you don't have to set your user-agent, but <a href="https://www.mediawiki.org/wiki/API:Etiquette#User-Agent_header" rel="nofollow">it's strongly encouraged</a>. Also, nearly all Wikimedia wikis <a href="http://blog.wikimedia.org/2015/06/12/securing-wikimedia-sites-with-https/" rel="nofollow">require HTTPS</a>, so avoid a 301 redirect and make http<strong>s</strong> requests.</p>
0
2015-11-11T05:56:24Z
[ "python", "urllib2", "user-agent", "wikipedia", "http-status-code-403" ]
Short Integers in Python
120,250
<p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p> <p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
10
2008-09-23T10:35:09Z
120,256
<p>Nope. But you can use short integers in arrays:</p> <pre><code>from array import array a = array("h") # h = signed short, H = unsigned short </code></pre> <p>As long as the value stays in that array it will be a short integer.</p> <ul> <li>documentation for the <a href="http://docs.python.org/dev/library/array">array module</a></li> </ul>
30
2008-09-23T10:36:44Z
[ "python", "memory-management", "short" ]