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
How to find the mime type of a file in python?
43,580
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
101
2008-09-04T12:07:27Z
39,356,849
<p>In Python 3.x and webapp with url to the file which couldn't have an extension or a fake extension. You should install python-magic, using </p> <pre><code>pip3 install python-magic </code></pre> <p>For Mac OS X, you should also install libmagic using</p> <pre><code>brew install libmagic </code></pre> <p>Code snippet</p> <pre><code>import urllib import magic from urllib.request import urlopen url = "http://...url to the file ..." request = urllib.request.Request(url) response = urlopen(request) mime_type = magic.from_buffer(response.read()) print(mime_type) </code></pre>
2
2016-09-06T19:55:29Z
[ "python", "mime" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
43,736
<p>If you've never done any CGI programming before I think it would be worth doing one project - perhaps just a sample play site just for yourself - using the DIY approach. You'll learn a lot more about how all the various parts work than you would by using a framework. This will help in you design and debug and so on all your future web applications however you write them.</p> <p>Personally I now use <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>. The real benefit is very fast application deployment. The object relational mapping gets things moving fast and the template library is a joy to use. Also the admin interface gives you basic CRUD screens for all your objects so you don't need to write any of the "boring" stuff.</p> <p>The downside of using an ORM based solution is that if you do want to handcraft some SQL, say for performance reasons, it much harder than it would have been otherwise, although still very possible. </p>
2
2008-09-04T13:17:38Z
[ "python", "frameworks", "cgi", "wsgi" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
43,753
<p>If you decide to go with a framework that is WSGI-based (for instance <a href="http://www.turbogears.org/2.0" rel="nofollow">TurboGears</a>), I would recommend you go through the excellent article <a href="http://pythonpaste.org/webob/do-it-yourself.html" rel="nofollow">Another Do-It-Yourself Framework</a> by Ian Bicking.</p> <p>In the article, he builds a simple web application framework from scratch.</p> <p>Also, check out the video <a href="http://www.vimeo.com/3258566" rel="nofollow">Creating a web framework with WSGI</a> by Kevin Dangoor. Dangoor is the founder of the TurboGears project.</p>
7
2008-09-04T13:24:55Z
[ "python", "frameworks", "cgi", "wsgi" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
43,773
<p>CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in memory. You can go with FastCGI, but I would argue that you'd be better off just writing a straight <a href="http://www.python.org/dev/peps/pep-0333/">WSGI</a> app if you're going to go that route (the way WSGI works really isn't a whole heck of a lot different from CGI).</p> <p>Other than that, your choices are for the most part how much you want the framework to do. You can go with an all singing, all dancing framework like Django or Pylons. Or you can go with a mix-and-match approach (use something like CherryPy for the HTTP stuff, SQLAlchemy for the database stuff, paste for deployment, etc). I should also point out that most frameworks will also let you switch different components out for others, so these two approaches aren't necessarily mutually exclusive.</p> <p>Personally, I dislike frameworks that do too much magic for me and prefer the mix-and-match technique, but I've been told that I'm also completely insane. :)</p> <p>How much web programming experience do you have? If you're a beginner, I say go with Django. If you're more experienced, I say to play around with the different approaches and techniques until you find the right one.</p>
17
2008-09-04T13:35:45Z
[ "python", "frameworks", "cgi", "wsgi" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
43,835
<p>The simplest web program is a CGI script, which is basically just a program whose standard output is redirected to the web browser making the request. In this approach, every page has its own executable file, which must be loaded and parsed on every request. This makes it really simple to get something up and running, but scales badly both in terms of performance and organization. So when I need a very dynamic page very quickly that won't grow into a larger system, I use a CGI script.</p> <p>One step up from this is embedding your Python code in your HTML code, such as with PSP. I don't think many people use this nowadays, since modern template systems have made this pretty obsolete. I worked with PSP for awhile and found that it had basically the same organizational limits as CGI scripts (every page has its own file) plus some whitespace-related annoyances from trying to mix whitespace-ignorant HTML with whitespace-sensitive Python.</p> <p>The next step up is very simple web frameworks such as web.py, which I've also used. Like CGI scripts, it's very simple to get something up and running, and you don't need any complex configuration or automatically generated code. Your own code will be pretty simple to understand, so you can see what's happening. However, it's not as feature-rich as other web frameworks; last time I used it, there was no session tracking, so I had to roll my own. It also has "too much magic behavior" to quote Guido ("upvars(), bah").</p> <p>Finally, you have feature-rich web frameworks such as Django. These will require a bit of work to get simple Hello World programs working, but every major one has a great, well-written tutorial (especially Django) to walk you through it. I highly recommend using one of these web frameworks for any real project because of the convenience and features and documentation, etc.</p> <p>Ultimately you'll have to decide what you prefer. For example, frameworks all use template languages (special code/tags) to generate HTML files. Some of them such as Cheetah templates let you write arbitrary Python code so that you can do anything in a template. Others such as Django templates are more restrictive and force you to separate your presentation code from your program logic. It's all about what you personally prefer.</p> <p>Another example is URL handling; some frameworks such as Django have you define the URLs in your application through regular expressions. Others such as CherryPy automatically map your functions to urls by your function names. Again, this is a personal preference.</p> <p>I personally use a mix of web frameworks by using CherryPy for my web server stuff (form parameters, session handling, url mapping, etc) and Django for my object-relational mapping and templates. My recommendation is to start with a high level web framework, work your way through its tutorial, then start on a small personal project. I've done this with all of the technologies I've mentioned and it's been really beneficial. Eventually you'll get a feel for what you prefer and become a better web programmer (and a better programmer in general) in the process.</p>
12
2008-09-04T14:11:54Z
[ "python", "frameworks", "cgi", "wsgi" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
44,638
<p>OK, rails is actually pretty good, but there is just a little bit too much magic going on in there (from the Ruby world I would much prefer merb to rails). I personally use Pylons, and am pretty darn happy. I'd say (compared to django), that pylons allows you to interchange ints internal parts easier than django does. The downside is that you will have to write more stuff all by youself (like the basic CRUD). </p> <p>Pros of using a framework:</p> <ol> <li>get stuff done quickly (and I mean lighning fast once you know the framework)</li> <li>everything is compying to standards (which is probably not that easy to achieve when rolling your own)</li> <li>easier to get something working (lots of tutorials) without reading gazillion articles and docs</li> </ol> <p>Cons:</p> <ol> <li>you learn less</li> <li>harder to replace parts (not that much of an issue in pylons, more so with django)</li> <li>harder to tweak some low-level stuff (like the above mentioned SQLs)</li> </ol> <p>From that you can probably devise what they are good for :-) Since you get all the code it is possible to tweak it to fit even the most bizzare situations (pylons supposedly work on the Google app engine now...).</p>
1
2008-09-04T19:55:29Z
[ "python", "frameworks", "cgi", "wsgi" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
87,048
<p>If you want to go big, choose Django and you are set. But if you want just to learn, roll your own framework using already mentioned <a href="http://pythonpaste.org/webob/" rel="nofollow">WebOb</a> - this can be really fun and I am sure you'll learn much more (plus you can use components you like: template system, url dispatcher, database layer, sessions, et caetera).</p> <p>In last 2 years I built few large sites using Django and all I can say, Django will fill 80% of your needs in 20% of time. Remaining 20% of work will take 80% of the time, no matter which framework you'd use.</p>
4
2008-09-17T20:04:12Z
[ "python", "frameworks", "cgi", "wsgi" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
222,159
<p>It's always worth doing something the hard way - once - as a learning exercise. Once you understand how it works, pick a framework that suits your application, and use that. You don't need to reinvent the wheel once you understand angular velocity. :-)</p> <p>It's also worth making sure that you have a fairly robust understanding of the programming language behind the framework <em>before</em> you jump in -- trying to learn both Django and Python at the same time (or Ruby and Rails, or X and Y), can lead to even more confusion. Write some code in the language first, then add the framework.</p> <p>We learn to develop, not by using tools, but by solving problems. Run into a few walls, climb over, and find some higher walls!</p>
3
2008-10-21T14:49:57Z
[ "python", "frameworks", "cgi", "wsgi" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
1,209,580
<p>If you are using Python you should <em>not</em> start with CGI, instead start with WSGI (and you can use <a href="http://docs.python.org/library/wsgiref.html#wsgiref.handlers.CGIHandler" rel="nofollow">wsgiref.handlers.CGIHandler</a> to run your WSGI script as a CGI script. The result is something that is basically as low-level as CGI (which might be useful in an educational sense, but will also be somewhat annoying), but without having to write to an entirely outdated interface (and binding your application to a single process model).</p> <p>If you want a less annoying, but similarly low-level interface, using <a href="http://pythonpaste.org/webob/" rel="nofollow">WebOb</a> would provide that. You would be implementing <em>all</em> the logic, and there will be few dark corners that you won't understand, but you won't have to spend time figuring out how to parse HTTP dates (they are weird!) or parse POST bodies. I write applications this way (without any other framework) and it is entirely workable. As a beginner, I'd advise this if you were interested in understanding what frameworks do, because it is inevitable you will be writing your own mini framework. OTOH, a real framework will probably teach you good practices of application design and structure. To be a really good web programmer, I believe you need to try both seriously; you should understand everything a framework does and not be afraid of its internals, but you should also spend time in a thoughtful environment someone else designed (i.e., an existing framework) and understand how that structure helps you.</p>
2
2009-07-30T21:44:35Z
[ "python", "frameworks", "cgi", "wsgi" ]
Pros and Cons of different approaches to web programming in Python
43,709
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
24
2008-09-04T13:00:13Z
1,873,745
<p>For smaller projects, rolling your own is fairly easy. Especially as you can simply import a templating engine like <a href="http://genshi.edgewall.org/" rel="nofollow">Genshi</a> and get alot happening quite quickly and easily. Sometimes it's just quicker to use a screwdriver than to go looking for the power drill.</p> <p>Full blown frameworks provide alot more power, but do have to be installed and setup first before you can leverage that power. For larger projects, this is a negligible concern, but for smaller projects this might wind up taking most of your time - especially if the framework is unfamiliar.</p>
1
2009-12-09T13:02:23Z
[ "python", "frameworks", "cgi", "wsgi" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,780
<p>Your Python interpreter is correct. One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1).</p> <p>e.g.: 13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3</p> <p>or in your case: −2 mod 5 = (−2 + 5) mod 5 = 3</p>
9
2008-09-04T13:40:59Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,781
<p>Well, -2 divided by 5 would be 0 with a remainder of 3. I don't believe that should be very platform dependent, but I've seen stranger things.</p>
0
2008-09-04T13:41:04Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,782
<p>It is indeed 3. In <a href="http://en.wikipedia.org/wiki/Modular_arithmetic" rel="nofollow">modular arithmetic</a>, a modulus is simply the remainder of a division, and the remainder of -2 divided by 5 is 3.</p>
0
2008-09-04T13:41:19Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,783
<p>The result of the modulus operation on negatives seems to be programming language dependent and here is a listing <a href="http://en.wikipedia.org/wiki/Modulo_operation">http://en.wikipedia.org/wiki/Modulo_operation</a></p>
11
2008-09-04T13:41:25Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,785
<p>Well, 0 % 5 should be 0, right?</p> <p>-1 % 5 should be 4 because that's the next allowed digit going in the reverse direction (i.e., it can't be 5, since that's out of range).</p> <p>And following along by that logic, -2 must be 3.</p> <p>The easiest way to think of how it will work is that you keep adding or subtracting 5 until the number falls between 0 (inclusive) and 5 (exclusive).</p> <p>I'm not sure about machine dependence - I've never seen an implementation that was, but I can't say it's never done.</p>
4
2008-09-04T13:41:40Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,794
<p>By the way: most programming languages would disagree with Python and give the result <code>-2</code>. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of <em>a</em> and <em>b</em> is the (strictly positive) rest <em>r</em> of the division of <em>a</em> / <em>b</em>. More precisely, 0 &lt;= <em>r</em> &lt; <em>b</em> by definition.</p>
15
2008-09-04T13:46:23Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,799
<p>The result depends on the language. Python returns the sign of the divisor, where for example c# returns the sign of the dividend (ie. -2 % 5 returns -2 in c#).</p>
0
2008-09-04T13:53:07Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,837
<p>One explanation might be that negative numbers are stored using <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow">2's complement</a>. When the python interpreter tries to do the modulo operation it converts to unsigned value. As such instead of doing (-2) % 5 it actually computes 0xFFFF_FFFF_FFFF_FFFD % 5 which is 3. </p>
0
2008-09-04T14:12:16Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,863
<p>As explained in other answers, there are many choices for a modulo operation with negative values. In general different languages (and different machine architectures) will give a different result.</p> <p>According to the <a href="http://docs.python.org/ref/binary.html" rel="nofollow">Python reference manual</a>,</p> <blockquote> <p>The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand.</p> </blockquote> <p>is the choice taken by Python. Basically modulo is defined so that this always holds:</p> <pre><code>x == (x/y)*y + (x%y) </code></pre> <p>so it makes sense that (-2)%5 = -2 - (-2/5)*5 = 3</p>
4
2008-09-04T14:25:05Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
43,916
<p>Be careful not to rely on this mod behavior in C/C++ on all OSes and architectures. If I recall correctly, I tried to rely on C/C++ code like</p> <pre><code>float x2 = x % n; </code></pre> <p>to keep x2 in the range from 0 to n-1 but negative numbers crept in when I would compile on one OS, but things would work fine on another OS. This made for an evil time debugging since it only happened half the time!</p>
0
2008-09-04T14:46:11Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
3,224,825
<p>Like the documentation says in <a href="http://docs.python.org/reference/expressions.html#binary">Binary arithmetic operations</a>, Python assures that:</p> <blockquote> <p>The integer division and modulo operators are connected by the following identity: <code>x == (x/y)*y + (x%y)</code>. Integer division and modulo are also connected with the built-in function divmod(): <code>divmod(x, y) == (x/y, x%y)</code>.</p> </blockquote> <p>And truly,</p> <pre><code>&gt;&gt;&gt; divmod(-2, 5) (-1, 3). </code></pre> <p>Another way to visualize the uniformity of this method is to calculate <code>divmod</code> for a small sequence of numbers:</p> <pre><code>&gt;&gt;&gt; for number in xrange(-10, 10): ... print divmod(number, 5) ... (-2, 0) (-2, 1) (-2, 2) (-2, 3) (-2, 4) (-1, 0) (-1, 1) (-1, 2) (-1, 3) (-1, 4) (0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (1, 0) (1, 1) (1, 2) (1, 3) (1, 4) </code></pre>
5
2010-07-11T22:18:00Z
[ "python", "math", "modulo" ]
Modulus operation with negatives values - weird thing?
43,775
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
14
2008-09-04T13:36:46Z
5,203,460
<p>There seems to be a common confusion between the terms "modulo" and "remainder".</p> <p>In math, a remainder should <em>always</em> be defined consistent with the quotient, so that if <code>a / b == c rem d</code> then <code>(c * b) + d == a</code>. Depending on how you round your quotient, you get different remainders.</p> <p>However, modulo should always give a result <code>0 &lt;= r &lt; divisor</code>, which is only consistent with round-to-minus-infinity division if you allow negative integers. If division rounds towards zero (which is common), modulo and remainder are only equivalent for non-negative values.</p> <p>Some languages (notably C and C++) don't define the required rounding/remainder behaviours and <code>%</code> is ambiguous. Many define rounding as towards zero, yet use the term modulo where remainder would be more correct. Python is relatively unusual in that it rounds to negative infinity, so modulo and remainder are equivalent.</p> <p>Ada rounds towards zero IIRC, but has both <code>mod</code> and <code>rem</code> operators.</p> <p>The C policy is intended to allow compilers to choose the most efficient implementation for the machine, but IMO is a false optimisation, at least these days. A good compiler will probably be able to use the equivalence for optimisation wherever a negative number cannot occur (and almost certainly if you use unsigned types). On the other hand, where negative numbers can occur, you almost certainly care about the details - for portability reasons you have to use very carefully designed overcomplex algorithms and/or checks to ensure that you get the results you want irrespective of the rounding and remainder behaviour.</p> <p>In other words, the gain for this "optimisation" is mostly (if not always) an illusion, whereas there are very real costs in some cases - so it's a false optimisation.</p>
0
2011-03-05T11:16:46Z
[ "python", "math", "modulo" ]
How do I document a module in Python?
44,084
<p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p> <pre><code>def foo(): """This function does nothing.""" pass </code></pre> <p>But what about a module? How can I document what a <em>file.py</em> does?</p>
31
2008-09-04T16:06:48Z
44,094
<p>It's easy, you just add a docstring at the top of the module.</p>
5
2008-09-04T16:12:07Z
[ "python", "documentation", "python-module" ]
How do I document a module in Python?
44,084
<p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p> <pre><code>def foo(): """This function does nothing.""" pass </code></pre> <p>But what about a module? How can I document what a <em>file.py</em> does?</p>
31
2008-09-04T16:06:48Z
44,095
<p>For the packages, you can document it in <code>__init__.py</code>. For the modules, you can add a docstring simply in the module file.</p> <p>All the information is here: <a href="http://www.python.org/dev/peps/pep-0257/">http://www.python.org/dev/peps/pep-0257/</a></p>
33
2008-09-04T16:12:23Z
[ "python", "documentation", "python-module" ]
How do I document a module in Python?
44,084
<p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p> <pre><code>def foo(): """This function does nothing.""" pass </code></pre> <p>But what about a module? How can I document what a <em>file.py</em> does?</p>
31
2008-09-04T16:06:48Z
44,098
<p>You do it the exact same way. Put a string in as the first statement in the module.</p>
6
2008-09-04T16:12:52Z
[ "python", "documentation", "python-module" ]
How do I document a module in Python?
44,084
<p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p> <pre><code>def foo(): """This function does nothing.""" pass </code></pre> <p>But what about a module? How can I document what a <em>file.py</em> does?</p>
31
2008-09-04T16:06:48Z
23,450,896
<p>Add your docstring as the <a href="http://legacy.python.org/dev/peps/pep-0257/#what-is-a-docstring">first statement in the module</a>.</p> <p>Since I like seeing an example:</p> <pre><code>""" Your module's verbose yet thorough docstring. """ import foo # ... </code></pre>
14
2014-05-03T23:29:51Z
[ "python", "documentation", "python-module" ]
Iterate over subclasses of a given class in a given module
44,352
<p>In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>
15
2008-09-04T18:05:23Z
44,381
<p>Here's one way to do it:</p> <pre><code>import inspect def get_subclasses(mod, cls): """Yield the classes in module ``mod`` that inherit from ``cls``""" for name, obj in inspect.getmembers(mod): if hasattr(obj, "__bases__") and cls in obj.__bases__: yield obj </code></pre>
9
2008-09-04T18:20:21Z
[ "python", "oop" ]
Iterate over subclasses of a given class in a given module
44,352
<p>In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>
15
2008-09-04T18:05:23Z
44,403
<p>Given the module foo.py</p> <pre><code>class foo(object): pass class bar(foo): pass class baz(foo): pass class grar(Exception): pass def find_subclasses(module, clazz): for name in dir(module): o = getattr(module, name) try: if issubclass(o, clazz): yield name, o except TypeError: pass &gt;&gt;&gt; import foo &gt;&gt;&gt; list(foo.find_subclasses(foo, foo.foo)) [('bar', &lt;class 'foo.bar'&gt;), ('baz', &lt;class 'foo.baz'&gt;), ('foo', &lt;class 'foo.foo'&gt;)] &gt;&gt;&gt; list(foo.find_subclasses(foo, object)) [('bar', &lt;class 'foo.bar'&gt;), ('baz', &lt;class 'foo.baz'&gt;), ('foo', &lt;class 'foo.foo'&gt;), ('grar', &lt;class 'foo.grar'&gt;)] &gt;&gt;&gt; list(foo.find_subclasses(foo, Exception)) [('grar', &lt;class 'foo.grar'&gt;)] </code></pre>
1
2008-09-04T18:29:59Z
[ "python", "oop" ]
Iterate over subclasses of a given class in a given module
44,352
<p>In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>
15
2008-09-04T18:05:23Z
47,032
<p>Can I suggest that neither of the answers from Chris AtLee and zacherates fulfill the requirements? I think this modification to zacerates answer is better:</p> <pre><code>def find_subclasses(module, clazz): for name in dir(module): o = getattr(module, name) try: if (o != clazz) and issubclass(o, clazz): yield name, o except TypeError: pass </code></pre> <p>The reason I disagree with the given answers is that the first does not produce classes that are a distant subclass of the given class, and the second includes the given class.</p>
4
2008-09-05T22:54:42Z
[ "python", "oop" ]
Iterate over subclasses of a given class in a given module
44,352
<p>In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>
15
2008-09-04T18:05:23Z
408,465
<p>Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library.</p> <ol> <li>You can avoid the getattr call by using <code>inspect.getmembers()</code></li> <li>The try/catch can be avoided by using <code>inspect.isclass()</code></li> </ol> <p>With those, you can reduce the whole thing to a single list comprehension if you like:</p> <pre><code>def find_subclasses(module, clazz): return [ cls for name, cls in inspect.getmembers(module) if inspect.isclass(cls) and issubclass(cls, clazz) ] </code></pre>
19
2009-01-03T01:56:21Z
[ "python", "oop" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
44,781
<pre><code>myList = ['a','b','c','d'] myString = ",".join(myList ) </code></pre> <p>This won't work if the list contains numbers.</p> <hr> <p>As <a href="http://stackoverflow.com/users/3399/ricardo-reyes">Ricardo Reyes</a> suggested, if it contains non-string types (such as integers, floats, bools, None) then do:</p> <pre><code>myList = ','.join(map(str, myList)) </code></pre>
333
2008-09-04T21:06:12Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
44,788
<p>Why the map/lambda magic? Doesn't this work?</p> <pre><code>&gt;&gt;&gt;foo = [ 'a', 'b', 'c' ] &gt;&gt;&gt;print ",".join(foo) a,b,c &gt;&gt;&gt;print ",".join([]) &gt;&gt;&gt;print ",".join(['a']) a </code></pre> <p>Edit: @mark-biek points out the case for numbers. Perhaps the list comprehension:</p> <pre><code>&gt;&gt;&gt;','.join([str(x) for x in foo]) </code></pre> <p>is more "pythonic".</p> <p>Edit2: Thanks for the suggestions. I'll use the generator rather than the list comprehension in the future.</p> <pre><code>&gt;&gt;&gt;','.join(str(x) for x in foo) </code></pre>
42
2008-09-04T21:08:29Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
44,791
<p>Don't you just want:</p> <pre><code>",".join(l) </code></pre> <p>Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:</p> <p><a href="https://docs.python.org/library/csv.html" rel="nofollow">https://docs.python.org/library/csv.html</a></p>
10
2008-09-04T21:09:33Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
44,794
<p>Unless I'm missing something, <code>','.join(foo)</code> should do what you're asking for.</p> <pre><code>&gt;&gt;&gt; ','.join(['']) '' &gt;&gt;&gt; ','.join(['s']) 's' &gt;&gt;&gt; ','.join(['a','b','c']) 'a,b,c' </code></pre> <p>(edit: and as jmanning2k points out, </p> <pre><code>','.join([str(x) for x in foo]) </code></pre> <p>is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the <code>csv</code> module, as Douglas points out in his answer.)</p>
2
2008-09-04T21:10:25Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
44,878
<p>@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator</p> <pre><code>from itertools import imap l = [1, "foo", 4 ,"bar"] ",".join(imap(str, l)) </code></pre>
5
2008-09-04T21:57:51Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
46,233
<p>@<a href="#44878">Peter Hoffmann</a></p> <p>Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.</p> <pre><code>&gt;&gt;&gt; l = [1, "foo", 4 ,"bar"] &gt;&gt;&gt; ",".join(str(bit) for bit in l) '1,foo,4,bar' </code></pre>
6
2008-09-05T16:29:25Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
65,255
<pre><code>l=['a', 1, 'b', 2] print str(l)[1:-1] Output: "'a', 1, 'b', 2" </code></pre>
2
2008-09-15T18:08:41Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
156,851
<p>Here is a alternative solution in Python 3.0 which allows non-string list items:</p> <pre><code>&gt;&gt;&gt; alist = ['a', 1, (2, 'b')] </code></pre> <ul> <li><p>a standard way</p> <pre><code>&gt;&gt;&gt; ", ".join(map(str, alist)) "a, 1, (2, 'b')" </code></pre></li> <li><p>the alternative solution</p> <pre><code>&gt;&gt;&gt; import io &gt;&gt;&gt; s = io.StringIO() &gt;&gt;&gt; print(*alist, file=s, sep=', ', end='') &gt;&gt;&gt; s.getvalue() "a, 1, (2, 'b')" </code></pre></li> </ul> <p>NOTE: The space after comma is intentional.</p>
5
2008-10-01T09:23:00Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
12,297,685
<p>for converting list containing numbers do the following:</p> <pre><code>string = ''.join([str(i) for i in list]) </code></pre>
4
2012-09-06T10:08:13Z
[ "python", "list" ]
How would you make a comma-separated string from a list?
44,778
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
180
2008-09-04T21:04:04Z
35,319,592
<p><code>",".join(l)</code> will not work for all cases. I'd suggest using the csv module with StringIO</p> <pre><code>import StringIO import csv l = ['list','of','["""crazy"quotes"and\'',123,'other things'] line = StringIO.StringIO() writer = csv.writer(line) writer.writerow(l) csvcontent = line.getvalue() # 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n' </code></pre>
4
2016-02-10T15:43:06Z
[ "python", "list" ]
Can someone explain __all__ in Python?
44,834
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
409
2008-09-04T21:28:18Z
44,842
<p>It's a list of public objects of that module. It overrides the default of hiding everything that begins with an underscore.</p>
198
2008-09-04T21:30:46Z
[ "python", "syntax", "namespaces" ]
Can someone explain __all__ in Python?
44,834
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
409
2008-09-04T21:28:18Z
44,843
<p>From <a href="http://effbot.org/pyref/__all__.htm">(An Unofficial) Python Reference Wiki</a>:</p> <blockquote> <p>The public names defined by a module are determined by checking the module's namespace for a variable named <code>__all__</code>; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in <code>__all__</code> are all considered public and are required to exist. If <code>__all__</code> is not defined, the set of public names includes all names found in the module's namespace which do not begin with an underscore character ("_"). <code>__all__</code> should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).</p> </blockquote>
43
2008-09-04T21:31:16Z
[ "python", "syntax", "namespaces" ]
Can someone explain __all__ in Python?
44,834
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
409
2008-09-04T21:28:18Z
64,130
<p>Linked to, but not explicitly mentioned here, is exactly when <code>__all__</code> is used. It is a list of strings defining what symbols in a module will be exported when <code>from &lt;module&gt; import *</code> is used on the module.</p> <p>For example, the following code in a <code>foo.py</code> explicitly exports the symbols <code>bar</code> and <code>baz</code>:</p> <pre><code>__all__ = ['bar', 'baz'] waz = 5 bar = 10 def baz(): return 'baz' </code></pre> <p>These symbols can then be imported like so:</p> <pre><code>from foo import * print bar print baz # The following will trigger an exception, as "waz" is not exported by the module print waz </code></pre> <p>If the <code>__all__</code> above is commented out, this code will then execute to completion, as the default behaviour of <code>import *</code> is to import all symbols that do not begin with an underscore, from the given namespace.</p> <p>Reference: <a href="https://docs.python.org/3.5/tutorial/modules.html#importing-from-a-package">https://docs.python.org/3.5/tutorial/modules.html#importing-from-a-package</a></p> <p><strong>NOTE:</strong> <code>__all__</code> affects the <code>from &lt;module&gt; import *</code> behavior only. Members that are not mentioned in <code>__all__</code> are still accessible from outside the module and can be imported with <code>from &lt;module&gt; import &lt;member&gt;</code>.</p>
483
2008-09-15T15:49:50Z
[ "python", "syntax", "namespaces" ]
Can someone explain __all__ in Python?
44,834
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
409
2008-09-04T21:28:18Z
2,838,800
<p>It also changes what pydoc will show:</p> <p>module1.py</p> <pre><code>a = "A" b = "B" c = "C" </code></pre> <p>module2.py</p> <pre><code>__all__ = ['a', 'b'] a = "A" b = "B" c = "C" </code></pre> <p>$ pydoc module1</p> <pre> Help on module module1: <b>NAME</b> module1 <b>FILE</b> module1.py <b>DATA</b> <b>a</b> = 'A' <b>b</b> = 'B' <b>c</b> = 'C' </pre> <p>$ pydoc module2</p> <pre> Help on module module2: <b>NAME</b> module2 <b>FILE</b> module2.py <b>DATA</b> <b>__all__</b> = ['a', 'b'] <b>a</b> = 'A' <b>b</b> = 'B' </pre> <p>I declare <code>__all__</code> in all my modules, as well as underscore internal details, these really help when using things you've never used before in live interpreter sessions.</p>
76
2010-05-15T03:22:29Z
[ "python", "syntax", "namespaces" ]
Can someone explain __all__ in Python?
44,834
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
409
2008-09-04T21:28:18Z
16,595,377
<p>I'm just adding this to be precise:</p> <p>All other answers refer to <em>modules</em>. The original question explicitely mentioned <code>__all__</code> in <code>__init__.py</code> files, so this is about python <em>packages</em>.</p> <p>Generally, <code>__all__</code> only comes into play when the <code>from xxx import *</code> variant of the <code>import</code> statement is used. This applies to packages as well as to modules.</p> <p>The behaviour for modules is explained in the other answers. The exact behaviour for packages is described <a href="http://docs.python.org/2/tutorial/modules.html#importing-from-a-package">here</a> in detail.</p> <p>In short, <code>__all__</code> on package level does approximately the same thing as for modules, except it deals with <em>modules within the package</em> (in contrast to specifying <em>names within the module</em>). So <code>__all__</code> specifies all modules that shall be loaded and imported into the current namespace when us use <code>from package import *</code>.</p> <p>The big difference is, that when you <em>omit</em> the declaration of <code>__all__</code> in a package's <code>__init__.py</code>, the statement <code>from package import *</code> will not import anything at all (with exceptions explained in the documentation, see link above). </p> <p>On the other hand, if you omit <code>__all__</code> in a module, the "starred import" will import all names (not starting with an underscore) defined in the module.</p>
84
2013-05-16T19:01:48Z
[ "python", "syntax", "namespaces" ]
Can someone explain __all__ in Python?
44,834
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
409
2008-09-04T21:28:18Z
35,710,527
<blockquote> <p><strong>Explain __all__ in Python?</strong></p> <p>I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files.</p> <p>What does this do?</p> </blockquote> <h1>What does <code>__all__</code> do?</h1> <p>It declares the semantically "public" names from a module. If there is a name in <code>__all__</code>, users are expected to use it, and they can have the expectation that it will not change. </p> <p>It also will have programmatic affects:</p> <h2><code>import *</code></h2> <p><code>__all__</code> in a module, e.g. <code>module.py</code>:</p> <pre><code>__all__ = ['foo', 'Bar'] </code></pre> <p>means that when you <code>import *</code> from the module, only those names in the <code>__all__</code> are imported:</p> <pre><code>from module import * # imports foo and Bar </code></pre> <h2>Documentation tools</h2> <p>Documentation and code autocompletion tools may (in fact, should) also inspect the <code>__all__</code> to determine what names to show as available from a module.</p> <h1><code>__init__.py</code> makes a directory a Python package</h1> <p>From the <a href="https://docs.python.org/2/tutorial/modules.html#packages">docs</a>:</p> <blockquote> <p>The <code>__init__.py</code> files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.</p> <p>In the simplest case, <code>__init__.py</code> can just be an empty file, but it can also execute initialization code for the package or set the <code>__all__</code> variable.</p> </blockquote> <p>So the <code>__init__.py</code> can declare the <code>__all__</code> for a <em>package</em>.</p> <h1>Managing an API:</h1> <p>A package is typically made up of modules that may import one another, but that are necessarily tied together with an <code>__init__.py</code> file. That file is what makes the directory an actual Python package. For example, say you have the following:</p> <pre><code> package/ |-__init__.py # makes directory a Python package |-module_1.py |-module_2.py </code></pre> <p>in the <code>__init__.py</code> you write:</p> <pre><code>from module_1 import * from module_2 import * </code></pre> <p>and in <code>module_1</code> you have:</p> <pre><code>__all__ = ['foo',] </code></pre> <p>and in <code>module_2</code> you have:</p> <pre><code>__all__ = ['Bar',] </code></pre> <p>And now you have presented a complete api that someone else can use when they import your package, like so: </p> <pre><code>import package package.foo() package.Bar() </code></pre> <p>And they won't have all the other names you used when creating your modules cluttering up the <code>package</code> namespace.</p> <h1><code>__all__</code> in <code>__init__.py</code></h1> <p>After more work, maybe you've decided that the modules are too big and need to be split up. So you do the following:</p> <pre><code> package/ |-__init__.py |-module_1/ | |-__init__.py | |-foo_implementation.py |-module_2/ |-__init__.py |-Bar_implementation.py </code></pre> <p>And in each <code>__init__.py</code> you declare an <code>__all__</code>, e.g. in module_1:</p> <pre><code>from foo_implementation import * __all__ = ['foo'] </code></pre> <p>And module_2's <code>__init__.py</code>:</p> <pre><code>from Bar_implementation import * __all__ = ['Bar'] </code></pre> <p>And you can easily add things to your API that you can manage at the subpackage level instead of the subpackage's module level. If you want to add a new name to the API, you simply update the <code>__init__.py</code>, e.g. in module_2:</p> <pre><code>from Bar_implementation import * from Baz_implementation import * __all__ = ['Bar', 'Baz'] </code></pre> <p>And if you're not ready to publish <code>Baz</code> in the top level API, in your top level <code>__init__.py</code> you could have:</p> <pre><code>from module_1 import * # also constrained by __all__'s from module_2 import * # in the __init__.py's __all__ = ['foo', 'Bar'] # further constraining the names advertised </code></pre> <p>and if your users are aware of the availability of <code>Baz</code>, they can use it:</p> <pre><code>import package package.Baz() </code></pre> <p>but if they don't know about it, other tools (like <a href="https://hg.python.org/cpython/file/2.7/Lib/pydoc.py#l173">pydoc</a>) won't inform them.</p> <p>You can later change that when <code>Baz</code> is ready for prime time:</p> <pre><code>from module_1 import * from module_2 import * __all__ = ['foo', 'Bar', 'Baz'] </code></pre> <h1>Prefixing <code>_</code> versus <code>__all__</code>:</h1> <p>By default, Python will export all names that do not start with an <code>_</code>. You certainly <em>could</em> rely on this mechanism. Some packages in the Python standard library, in fact, <em>do</em> rely on this, but to do so, they alias their imports, for example, in <a href="https://hg.python.org/cpython/file/default/Lib/ctypes/__init__.py#l3"><code>ctypes/__init__.py</code></a>:</p> <pre><code>import os as _os, sys as _sys </code></pre> <p>Using the <code>_</code> convention can be more elegant because it removes the redundancy of naming the names again. But it adds the redundancy for imports (if you have a lot of them) and it is <em>easy</em> to forget to do this consistently - and the last thing you want is to have to indefinitely support something you intended to only be an implementation detail, just because you forgot to prefix an <code>_</code> when naming a function.</p> <p>I personally write an <code>__all__</code> early in my development lifecycle for modules so that others who might use my code know what they should use and not use.</p> <p>Most packages in the standard library also use <code>__all__</code>.</p> <h1>When avoiding <code>__all__</code> makes sense</h1> <p>It makes sense to stick to the <code>_</code> prefix convention in lieu of <code>__all__</code> when:</p> <ul> <li>You're still in early development mode and have no users, and are constantly tweaking your API.</li> <li>Maybe you do have users, but you have unittests that cover the API, and you're still actively adding to the API and tweaking in development.</li> </ul> <h1>An <code>export</code> decorator</h1> <p>The downside of using <code>__all__</code> is that you have to write the names of functions and classes being exported twice - and the information is kept separate from the definitions. We <em>could</em> use a decorator to solve this problem.</p> <p>I got the idea for such an export decorator from David Beazley's talk on packaging. This implementation seems to work well in CPython's traditional importer. If you have a special import hook or system, I do not guarantee it, but if you adopt it, it is fairly trivial to back out - you'll just need to manually add the names back into the <code>__all__</code></p> <p>So in, for example, a utility library, you would define the decorator:</p> <pre><code>import sys def export(fn): mod = sys.modules[fn.__module__] if hasattr(mod, '__all__'): mod.__all__.append(fn.__name__) else: mod.__all__ = [fn.__name__] return fn </code></pre> <p>and then, where you would define an <code>__all__</code>, you do this:</p> <pre><code>$ cat &gt; main.py from lib import export __all__ = [] # optional - we create a list if __all__ is not there. @export def foo(): pass @export def bar(): 'bar' def main(): print('main') if __name__ == '__main__': main() </code></pre> <p>And this works fine whether run as main or imported by another function.</p> <pre><code>$ cat &gt; run.py import main main.main() $ python run.py main </code></pre> <p>And API provisioning with <code>import *</code> will work too:</p> <pre><code>$ cat &gt; run.py from main import * foo() bar() main() # expected to error here, not exported $ python run.py Traceback (most recent call last): File "run.py", line 4, in &lt;module&gt; main() # expected to error here, not exported NameError: name 'main' is not defined </code></pre>
22
2016-02-29T21:58:50Z
[ "python", "syntax", "namespaces" ]
Can someone explain __all__ in Python?
44,834
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
409
2008-09-04T21:28:18Z
36,119,040
<h1><code>__all__</code> customizes <strong>the asterisk</strong> in <a href="https://docs.python.org/2/tutorial/modules.html#importing-from-a-package" rel="nofollow"><code>from &lt;module&gt; import *</code></a></h1> <hr> <pre><code>""" cheese.py """ __all__ = ['swiss', 'cheddar'] swiss = 4.99 cheddar = 3.99 gouda = 10.99 </code></pre> <p>As <a href="http://stackoverflow.com/a/35710527/673991">@AaronHall points out</a>, <code>__all__</code> declares to users and maintainers the "public" features of the module. (And to pydoc, thanks @Longpoke.) The import-asterisk statement below brings only <code>swiss</code> and <code>cheddar</code> into the local namespace, and <code>gouda</code> is hidden.</p> <h2>from <em>module</em> import *</h2> <pre><code>&gt;&gt;&gt; from cheese import * &gt;&gt;&gt; swiss, cheddar (4.99, 3.99) &gt;&gt;&gt; gouda Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'gouda' is not defined </code></pre> <p>Without <code>__all__</code>, any symbol (that doesn't start with an underscore) would have been available. </p> <hr> <h1>Imports without <code>*</code> are not affected by <code>__all__</code></h1> <hr> <h2>import <em>module</em></h2> <pre><code>&gt;&gt;&gt; import cheese &gt;&gt;&gt; cheese.swiss, cheese.cheddar, cheese.gouda (4.99, 3.99, 10.99) </code></pre> <h2>from <em>module</em> import <em>names</em></h2> <pre><code>&gt;&gt;&gt; from cheese import swiss, cheddar, gouda &gt;&gt;&gt; swiss, cheddar, gouda (4.99, 3.99, 10.99) </code></pre> <h2>import <em>module</em> as <em>localname</em></h2> <pre><code>&gt;&gt;&gt; import cheese as ch &gt;&gt;&gt; ch.swiss, ch.cheddar, ch.gouda (4.99, 3.99, 10.99) </code></pre> <hr> <p><a href="http://stackoverflow.com/a/16595377/673991">@MartinStettner</a> points out that in the <code>__init__.py</code> of a <strong>package</strong>, <code>__all__</code> is a list of public module names.</p> <hr> <p>@ToolmakerSteve cites <a href="https://www.python.org/dev/peps/pep-0008/#imports" rel="nofollow">PEP 0008</a> that wildcard imports confuse humans and bots, and should be avoided.</p>
4
2016-03-20T20:20:43Z
[ "python", "syntax", "namespaces" ]
Can someone explain __all__ in Python?
44,834
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
409
2008-09-04T21:28:18Z
36,853,901
<p><code>__all__</code> is used to document the public API of a Python module. Here is the relevant excerpt from <a href="https://docs.python.org/3/reference/simple_stmts.html#the-import-statement" rel="nofollow">the Python language reference</a>:</p> <blockquote> <p>The public names defined by a module are determined by checking the module’s namespace for a variable named <code>__all__</code>; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in <code>__all__</code> are all considered public and are required to exist. If <code>__all__</code> is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). <code>__all__</code> should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).</p> </blockquote> <p><a href="https://www.python.org/dev/peps/pep-0008/#id47" rel="nofollow">PEP 8</a> uses similar wording, although it also makes it clear that imported names are not part of the public API, regardless of <code>__all__</code>:</p> <blockquote> <p>To better support introspection, modules should explicitly declare the names in their public API using the <code>__all__</code> attribute. Setting <code>__all__</code> to an empty list indicates that the module has no public API.</p> <p>[...]</p> <p>Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as <code>os.path</code> or a package's <code>__init__</code> module that exposes functionality from submodules.</p> </blockquote> <p>Furthermore, as pointed out in other answers, <code>__all__</code> is used to enable <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package" rel="nofollow">wildcard importing for packages</a>:</p> <blockquote> <p>The import statement uses the following convention: if a package’s <code>__init__.py</code> code defines a list named <code>__all__</code>, it is taken to be the list of module names that should be imported when <code>from package import *</code> is encountered.</p> </blockquote>
1
2016-04-26T01:39:25Z
[ "python", "syntax", "namespaces" ]
Can the HTTP version or headers affect the visual appearance of a web page?
45,013
<p>I know, I would have thought the answer was obviously "no" as well, but I am experiencing a strange situation where when I view my site from our staging server it appears slightly larger than when I view it from my local dev server. I have used Charles to confirm that all of the content -- the HTML, the images, the CSS, the javascript, <strong>everything</strong> is the same.</p> <p>The ONLY difference in the traffic is that (because the local site is served from the Django development mode server) the response headers look like this:</p> <pre><code>HTTP/1.0 200 OK Server WSGIServer/0.1 Python/2.5.2 Date Thu, 04 Sep 2008 23:56:10 GMT Vary Cookie Content-Length 2301 Content-Type text/html; charset=utf-8 </code></pre> <p>Whereas on the staging server (where Django is running inside Apache) the headers look like this:</p> <pre><code>HTTP/1.1 200 OK Date Thu, 04 Sep 2008 23:56:06 GMT Server Apache/2.2.8 (Ubuntu) mod_python/3.3.1 Python/2.5.2 PHP/5.2.4-2ubuntu5 with Suhosin-Patch Vary Cookie Content-Length 2301 Content-Type text/html; charset=utf-8 </code></pre> <p>So, as far as I can tell the only differences are HTTP/1.1 vs HTTP/1.0, the server identifer (Apache vs WSGIServer) and the order of the Date/Server headers.</p> <p>To elaborate a bit further on the differences in appearance, basically it appears as if the version of the site on the staging server is "zoomed in" by about 10%. For example, the primary logo which dominates our home page is 220 pixels wide but when server from our staging server shows up as 245 pixels wide. Everything else on the page, (other images, text, spacing, etc) is also proportionately larger.</p> <p>This is all in Firefox 3. I don't have any other browsers available to test with at the moment.</p> <p>Has anyone else encountered any bizarre behavior anything like this before? I am at a loss.</p>
1
2008-09-05T00:10:37Z
45,016
<p>Have you tried View -> Zoom -> Reset on both sites?</p>
8
2008-09-05T00:12:41Z
[ "python", "django", "firefox" ]
Python packages - import by class, not file
45,122
<p>Say I have the following file structure:</p> <pre><code>app/ app.py controllers/ __init__.py project.py plugin.py </code></pre> <p>If app/controllers/project.py defines a class Project, app.py would import it like this:</p> <pre><code>from app.controllers.project import Project </code></pre> <p>I'd like to just be able to do:</p> <pre><code>from app.controllers import Project </code></pre> <p>How would this be done?</p>
35
2008-09-05T02:15:33Z
45,126
<p>You need to put</p> <pre><code>from project import Project </code></pre> <p>in <code>controllers/__init__.py</code>.</p> <p>Note that when <a href="http://www.python.org/dev/peps/pep-0328/" rel="nofollow">Absolute imports</a> become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named <code>project</code>), i.e.,</p> <pre><code>from .project import Project </code></pre>
71
2008-09-05T02:18:21Z
[ "python", "packages" ]
Where can I find the time and space complexity of the built-in sequence types in Python
45,228
<p>I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?</p>
14
2008-09-05T04:27:46Z
45,245
<p>If your asking what I think your asking, you can find them <a href="http://books.google.com/books?id=vpTAq4dnmuAC&amp;pg=RA1-PA476&amp;lpg=RA1-PA476&amp;dq=Big-O+of+Python+data+structures&amp;source=web&amp;ots=AOM5B5D7yA&amp;sig=deLGb6VrftTpnNYN6fILVbiirXM&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=7&amp;ct=result#PRA1-PA479,M1" rel="nofollow">Here</a>... page 476 and on.</p> <p>It's written around optimization techniques for Python; It's mostly Big-O notation of time efficiencies not much memory.</p>
2
2008-09-05T04:52:09Z
[ "python", "performance", "complexity-theory", "big-o", "sequences" ]
Where can I find the time and space complexity of the built-in sequence types in Python
45,228
<p>I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?</p>
14
2008-09-05T04:27:46Z
45,538
<p>Raymond D. Hettinger does <a href="http://www.youtube.com/watch?v=hYUsssClE94" rel="nofollow">an excellent talk</a> (<a href="http://wenku.baidu.com/view/9c6fb20dcc1755270722089d.html" rel="nofollow">slides</a>) about Python's built-in collections called 'Core Python Containers - Under the Hood'. The version I saw focussed mainly on <code>set</code> and <code>dict</code>, but <code>list</code> was covered too.</p> <p>There are also some photos of the pertinent slides from EuroPython in <a href="http://paranoid-engineering.blogspot.com/2008/07/europython-2008-day-3.html" rel="nofollow">a blog</a>.</p> <p>Here is a summary of my notes on <code>list</code>:</p> <ul> <li>Stores items as an array of pointers. Subscript costs O(1) time. Append costs amortized O(1) time. Insert costs O(n) time.</li> <li>Tries to avoid <code>memcpy</code> when growing by over-allocating. Many small lists will waste a lot of space, but large lists never waste more than about 12.5% to overallocation.</li> <li>Some operations pre-size. Examples given were <code>range(n)</code>, <code>map()</code>, <code>list()</code>, <code>[None] * n</code>, and slicing.</li> <li>When shrinking, the array is <code>realloc</code>ed only when it is wasting 50% of space. <code>pop</code> is cheap.</li> </ul>
12
2008-09-05T11:04:04Z
[ "python", "performance", "complexity-theory", "big-o", "sequences" ]
Where can I find the time and space complexity of the built-in sequence types in Python
45,228
<p>I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?</p>
14
2008-09-05T04:27:46Z
46,201
<p>Checkout the <a href="http://wiki.python.org/moin/TimeComplexity">TimeComplexity</a> page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes.</p>
16
2008-09-05T16:19:03Z
[ "python", "performance", "complexity-theory", "big-o", "sequences" ]
Wacom tablet Python interface
45,500
<p>If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?</p>
7
2008-09-05T10:13:16Z
45,564
<p>You could perhaps take a look at the <a href="http://www.alexmac.cc/tablet-apps/tablet-apps-0.3.1.tar.bz2" rel="nofollow">software</a> described <a href="http://www.alexmac.cc/tablet-apps/" rel="nofollow">here</a>. It is a gnome applet, written in Python.</p> <p>From the web site:</p> <p>"The gnome wacom applet is a small gnome panel applet that shows how much pressure is being applied to your wacom tablet by the current device. Clicking on the panel icon brings up a dialog allowing you to select a different device and check what pressure and tilt information is being recieved from it. This dialog also contains a small drawing test area to give your pen a quick test."</p> <p><a href="http://www.google.com/search?q=wacom+tablet+python" rel="nofollow">Google is your friend</a></p>
3
2008-09-05T11:21:35Z
[ "python", "interface", "wacom" ]
Wacom tablet Python interface
45,500
<p>If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?</p>
7
2008-09-05T10:13:16Z
5,088,138
<p>Use PySide (wrapper for QT)'s QTabletEvent: <a href="http://www.pyside.org/docs/pyside/PySide/QtGui/QTabletEvent.html#PySide.QtGui.QTabletEvent" rel="nofollow">http://www.pyside.org/docs/pyside/PySide/QtGui/QTabletEvent.html#PySide.QtGui.QTabletEvent</a></p>
2
2011-02-23T07:36:18Z
[ "python", "interface", "wacom" ]
Wacom tablet Python interface
45,500
<p>If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?</p>
7
2008-09-05T10:13:16Z
10,476,121
<p>For Mac OS X:</p> <p><a href="https://bitbucket.org/AnomalousUnderdog/pythonmactabletlib" rel="nofollow">https://bitbucket.org/AnomalousUnderdog/pythonmactabletlib</a></p> <blockquote> <p>A small Python library to allow Python scripts to access pen tablet input data in Mac OS X.</p> <p>The library exists as plain C code compiled as a dynamic library/shared object. It interfaces with the Mac OS X's API to get data on pen tablet input.</p> <p>Then, Python scripts can use ctypes to get the data.</p> </blockquote> <p>Send me a message if you have any problems with it.</p>
2
2012-05-07T02:47:32Z
[ "python", "interface", "wacom" ]
Wacom tablet Python interface
45,500
<p>If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?</p>
7
2008-09-05T10:13:16Z
28,655,874
<p>Pressure data is available in <a href="http://python-gtk-3-tutorial.readthedocs.org/en/latest/" rel="nofollow">PyGObject to access Gtk+ 3</a> on multiple platforms, though "Windows users may still want to keep using PyGTK until more convenient installers are published." [<a href="https://wiki.python.org/moin/PyGtk" rel="nofollow">citation</a>] Motion event objects generated by pressure sensitive devices will carry pressure data.</p>
1
2015-02-22T08:15:26Z
[ "python", "interface", "wacom" ]
Is there a Python library for generating .ico files?
45,507
<p>I'm looking to create <code>favicon.ico</code> files programatically from Python, but PIL only has support for reading <code>ico</code> files.</p>
11
2008-09-05T10:26:47Z
45,519
<p>Perhaps the following would work:</p> <ul> <li>Generate your icon image using PIL</li> <li>Convert the image to .ico format using the python interface to ImageMagick, <a href="http://www.imagemagick.org/download/python/">PythonMagick</a></li> </ul> <p>I have not tried this approach. The ImageMagick convert command line program was able to convert a .png file to .ico format, so at least ImageMagick supports the .ico format.</p>
6
2008-09-05T10:36:58Z
[ "python", "favicon" ]
Is there a Python library for generating .ico files?
45,507
<p>I'm looking to create <code>favicon.ico</code> files programatically from Python, but PIL only has support for reading <code>ico</code> files.</p>
11
2008-09-05T10:26:47Z
45,520
<p>I don't know if this applies for all cases, but on WinXP an .ico can be a bmp of size 16x16, 32x32 or 64x64. Just change the extension to ico from bmp and you're ready to go.</p>
2
2008-09-05T10:38:00Z
[ "python", "favicon" ]
Is there a Python library for generating .ico files?
45,507
<p>I'm looking to create <code>favicon.ico</code> files programatically from Python, but PIL only has support for reading <code>ico</code> files.</p>
11
2008-09-05T10:26:47Z
45,832
<p>According to <a href="http://en.wikipedia.org/wiki/Favicon">Wikipedia</a> modern browsers can handle favicons in PNG format, so maybe you could just generate that?</p> <p>Alternatively the <a href="http://en.wikipedia.org/wiki/ICO_(icon_image_file_format)">ICO article</a> describes the format...</p>
6
2008-09-05T13:35:32Z
[ "python", "favicon" ]
Is there a Python library for generating .ico files?
45,507
<p>I'm looking to create <code>favicon.ico</code> files programatically from Python, but PIL only has support for reading <code>ico</code> files.</p>
11
2008-09-05T10:26:47Z
36,168,447
<p>You can use <a href="http://pillow.readthedocs.org" rel="nofollow">Pillow</a>:</p> <pre><code>from PIL import Image filename = r'logo.png' img = Image.open(filename) img.save('logo.ico') </code></pre> <p>Optionally, you may specify the icon sizes you want:</p> <pre><code>icon_sizes = [(16,16), (32, 32), (48, 48), (64,64)] img.save('logo.ico', sizes=icon_sizes) </code></pre> <p>The <a href="http://pillow.readthedocs.org/en/3.1.x/handbook/image-file-formats.html" rel="nofollow">Pillow docs</a> say that by default it will generate sizes <code>[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)]</code> and any size bigger than the original size or 255 will be ignored.</p> <p>Yes, it is in the <strong>Read-only</strong> section of the docs, but it works to some extent.</p>
4
2016-03-23T01:49:37Z
[ "python", "favicon" ]
How to know whether a window with a given title is already open in Tk?
45,540
<p>I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.</p> <pre><code>from Tkinter import * import tkMessageBox root = Tk() root.withdraw() # TODO not if a window with this title exists tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:])) </code></pre> <p>Any idea how to check that?</p>
5
2008-09-05T11:07:06Z
46,205
<p>I believe you want:</p> <pre><code>if 'normal' != root.state(): tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:])) </code></pre>
1
2008-09-05T16:19:35Z
[ "python", "tkinter", "tk" ]
Analizing MIPS binaries: is there a Python library for parsing binary data?
45,954
<p>I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information.</p> <p>I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working.</p> <p>I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org.</p> <p>Is there a suitable module available somewhere?</p>
10
2008-09-05T14:44:25Z
46,028
<p>I don't know of any, but if all else fails you could use <a href="http://docs.python.org/lib/module-ctypes.html" rel="nofollow">ctypes</a> to directly use libdwarf, libelf or libbfd.</p>
3
2008-09-05T15:23:13Z
[ "python", "x86", "mips", "elf", "dwarf" ]
Analizing MIPS binaries: is there a Python library for parsing binary data?
45,954
<p>I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information.</p> <p>I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working.</p> <p>I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org.</p> <p>Is there a suitable module available somewhere?</p>
10
2008-09-05T14:44:25Z
510,623
<p>You should give <a href="http://construct.wikispaces.com/" rel="nofollow">Construct</a> a try. It is very useful to parse binary data into python objects. </p> <p>There is even an example for the <a href="http://sebulbasvn.googlecode.com/svn/trunk/construct/formats/executable/elf32.py" rel="nofollow">ELF32</a> file format.</p>
4
2009-02-04T09:19:06Z
[ "python", "x86", "mips", "elf", "dwarf" ]
Analizing MIPS binaries: is there a Python library for parsing binary data?
45,954
<p>I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information.</p> <p>I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working.</p> <p>I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org.</p> <p>Is there a suitable module available somewhere?</p>
10
2008-09-05T14:44:25Z
1,352,742
<p>I've been developing a DWARF parser using <a href="http://construct.wikispaces.com/" rel="nofollow">Construct</a>. Currently fairly rough, and parsing is slow. But I thought I should at least let you know. It may suit your needs, with a bit of work.</p> <p>I've got the code in Mercurial, hosted at bitbucket:</p> <ul> <li><a href="http://bitbucket.org/cmcqueen1975/pythondwarf/" rel="nofollow">http://bitbucket.org/cmcqueen1975/pythondwarf/</a></li> <li><a href="http://bitbucket.org/cmcqueen1975/construct/" rel="nofollow">http://bitbucket.org/cmcqueen1975/construct/</a> (necessary modifications to Construct library)</li> </ul> <p><a href="http://construct.wikispaces.com/" rel="nofollow">Construct</a> is a very interesting library. DWARF is a complex format (as I'm discovering) and pushes Construct to its limits I think.</p>
3
2009-08-30T00:48:04Z
[ "python", "x86", "mips", "elf", "dwarf" ]
Analizing MIPS binaries: is there a Python library for parsing binary data?
45,954
<p>I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information.</p> <p>I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working.</p> <p>I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org.</p> <p>Is there a suitable module available somewhere?</p>
10
2008-09-05T14:44:25Z
3,023,558
<p><a href="http://bitbucket.org/haypo/hachoir/wiki/Home" rel="nofollow">hachior</a> is another library for parsing binary data</p>
2
2010-06-11T14:23:05Z
[ "python", "x86", "mips", "elf", "dwarf" ]
Analizing MIPS binaries: is there a Python library for parsing binary data?
45,954
<p>I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information.</p> <p>I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working.</p> <p>I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org.</p> <p>Is there a suitable module available somewhere?</p>
10
2008-09-05T14:44:25Z
3,647,010
<p>You might be interested in the DWARF library from <a href="http://code.google.com/p/pydevtools/" rel="nofollow">pydevtools</a>:</p> <pre><code>&gt;&gt;&gt; from bintools.dwarf import DWARF &gt;&gt;&gt; dwarf = DWARF('test/test') &gt;&gt;&gt; dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) </code></pre>
8
2010-09-05T17:29:19Z
[ "python", "x86", "mips", "elf", "dwarf" ]
Analizing MIPS binaries: is there a Python library for parsing binary data?
45,954
<p>I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information.</p> <p>I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working.</p> <p>I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org.</p> <p>Is there a suitable module available somewhere?</p>
10
2008-09-05T14:44:25Z
8,754,578
<p>Please check <a href="https://github.com/eliben/pyelftools" rel="nofollow">pyelftools</a> - a new pure Python library meant to do this.</p>
4
2012-01-06T07:11:55Z
[ "python", "x86", "mips", "elf", "dwarf" ]
Which Version of Python to Use for Maximum Compatibility
47,198
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p> <p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
14
2008-09-06T02:22:50Z
47,201
<p>I've not seen a system with less than 2.3 installed for some time. Mostly 2.4+ is installed by default for most OS I use now. 2.3 is just on an older Solaris machine. Linux distros tend to have 2.4+, as does OS X.</p> <p>IIRC, 2.4 has a lot of the features 2.5 does, but usable only with</p> <pre><code>from __future__ import * </code></pre>
4
2008-09-06T02:27:45Z
[ "python", "compatibility" ]
Which Version of Python to Use for Maximum Compatibility
47,198
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p> <p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
14
2008-09-06T02:22:50Z
47,208
<p>As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the <a href="http://www.python.org/dev/peps/pep-3000/#timeline" rel="nofollow">time line</a> there will be at least one or two following releases of the 2.x series after 2.6/3.0 in october.</p> <p>Beside not having python 3 available on your target platforms, it will take some time until important external python libraries will be ported and usable on python 3.</p> <p>So as Matthew suggests staying at 2.4/2.5 and keeping the <a href="http://www.python.org/dev/peps/pep-3000/#compatibility-and-transition" rel="nofollow">transition</a> plan to python 3 in mind is a solid choice.</p>
6
2008-09-06T02:44:31Z
[ "python", "compatibility" ]
Which Version of Python to Use for Maximum Compatibility
47,198
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p> <p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
14
2008-09-06T02:22:50Z
47,264
<p>You can use different versions of python on each machine. </p> <p>Coding something new, I would not use anything less than python2.5. You can do <code>apt-get install python2.5</code> on stock debian stable. </p> <p>For windows, don't really worry about it. It's very easy to install the python2.5 msi. </p> <p>If the users can't be bothered to do that, you can deploy an executable with py2exe (so simple) and build an installer with inno setup (again simple) then it will behave like a standard windows application and will use its own python dlls, so no need to have python installed. </p> <p>Like Peter said: keep in mind the transition to 3.0 but don't build on it yet.</p>
1
2008-09-06T05:25:47Z
[ "python", "compatibility" ]
Which Version of Python to Use for Maximum Compatibility
47,198
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p> <p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
14
2008-09-06T02:22:50Z
48,175
<p>Python 2.3, or 2.2 if you can live without the many modules that were added (e.g. datetime, csv, logging, optparse, zipimport), aren't using SSL, and are willing to add boilerplate for True/False.</p> <p>2.4 added decorators. generator expressions, reversed(), sorted(), and the subprocess and decimal modules. Although these are all nice, it's easy to write Pythonic code without them (assuming that your project wouldn't make heavy use of them).</p> <p>2.5 added with, relative imports, better 64 bit support, and quite a bit of speed. You could live without all of those easily enough.</p> <p>2.6 isn't released (although it's very close), so while it might appeal to developers, it doesn't have the compatibility you're after.</p> <p>Take a look at the release notes for 2.3, 2.4, 2.5, and the upcoming 2.6 (use <a href="http://www.python.org/download/releases/2.Y/highlights/" rel="nofollow">http://www.python.org/download/releases/2.Y/highlights/</a> where 'Y' is the minor version).</p> <p>FWIW, for SpamBayes we support 2.2 and above (2.2 requires installing the email package separately). This isn't overly taxing, but the 2.3 additions are useful enough and 2.3 old enough that we'll probably drop 2.2 before long.</p>
1
2008-09-07T05:21:11Z
[ "python", "compatibility" ]
Which Version of Python to Use for Maximum Compatibility
47,198
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p> <p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
14
2008-09-06T02:22:50Z
2,036,609
<p>If the project is going to be mainstream and will be run on Linux the <strong>only</strong> sensible choise is 2.4 - just because it is a pain to get anything else installed as default on Enterprise Linuxes.</p> <p>In any case, any <em>modern</em> OS will/can have 2.4 or newer.</p>
0
2010-01-10T09:36:52Z
[ "python", "compatibility" ]
Which Version of Python to Use for Maximum Compatibility
47,198
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p> <p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
14
2008-09-06T02:22:50Z
7,695,227
<p>You should use <strong>Python 2.7</strong>, the final major version of Python 2.</p> <p>Python 3.x currently has limited 3rd-party library support, and is often not installed by default. So you are looking at the 2.x series.</p> <p>Python 2.7 is essentially fully backwards-compatible with earlier 2.xs. In addition, it can give deprecation warnings about things that won't work in Python 3. (Particularly, it will pay to maintain unit tests, and to be pedantic about Unicode- vs. byte-strings.) The warnings will force you to write good code that the automated <code>2to3</code> tool will be able to translate to Python 3.</p> <p>Guido van Rossum <a href="http://www.python.org/dev/peps/pep-3000/#compatibility-and-transition" rel="nofollow">officially recommends maintaining a single Python 2 code-base</a>, and using 2to3 together with unit testing to produce compatible releases for Python 2 and 3. (Since PEP 3000 was written, Python 2.6 has been superseded by 2.7.)</p>
0
2011-10-08T06:40:31Z
[ "python", "compatibility" ]
Django: Print url of view without hardcoding the url
47,207
<p>Can i print out a url <code>/admin/manage/products/add</code> of a certain view in a template?</p> <p>Here is the rule i want to create a link for</p> <pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>I would like to have /manage/products/add in a template without hardcoding it. How can i do this?</p> <p><strong>Edit:</strong> I am not using the default admin (well, i am but it is at another url), this is my own</p>
7
2008-09-06T02:42:49Z
47,212
<p>If you use <a href="https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns" rel="nofollow">named url patterns</a> you can do the follwing in your template</p> <pre><code>{% url create_object %} </code></pre>
2
2008-09-06T02:49:38Z
[ "python", "django" ]
Django: Print url of view without hardcoding the url
47,207
<p>Can i print out a url <code>/admin/manage/products/add</code> of a certain view in a template?</p> <p>Here is the rule i want to create a link for</p> <pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>I would like to have /manage/products/add in a template without hardcoding it. How can i do this?</p> <p><strong>Edit:</strong> I am not using the default admin (well, i am but it is at another url), this is my own</p>
7
2008-09-06T02:42:49Z
47,213
<p>The preferred way of creating the URL is by adding a <code>get_absolute_url</code> method to your model classes. You can hardcode the path there so you at least get closer to following the KISS philosophy.</p> <p>You can go further by utilizing the <code>permalink</code> decorator that figures the path based on the urls configuration.</p> <p>You can read more in the django documentation <a href="https://docs.djangoproject.com/en/dev/ref/models/instances/#get-absolute-url" rel="nofollow">here</a>.</p>
0
2008-09-06T02:50:08Z
[ "python", "django" ]
Django: Print url of view without hardcoding the url
47,207
<p>Can i print out a url <code>/admin/manage/products/add</code> of a certain view in a template?</p> <p>Here is the rule i want to create a link for</p> <pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>I would like to have /manage/products/add in a template without hardcoding it. How can i do this?</p> <p><strong>Edit:</strong> I am not using the default admin (well, i am but it is at another url), this is my own</p>
7
2008-09-06T02:42:49Z
47,304
<p>You can use <code>get_absolute_url</code>, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case.</p> <p>You want to use <a href="https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns" rel="nofollow">named URL patterns</a>. Here's a quick intro:</p> <p>Change the line in your urls.py to:</p> <pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"), </code></pre> <p>Then, in your template you use this to display the URL:</p> <pre><code>{% url create-product %} </code></pre> <p>If you're using Django 1.5 or higher you need this:</p> <pre><code>{% url 'create-product' %} </code></pre> <p>You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0).</p>
15
2008-09-06T07:22:52Z
[ "python", "django" ]
How do you set up a python wsgi server under IIS?
47,253
<p>I work in a windows environment and would prefer to deploy code to IIS. At the same time I would like to code in python.</p> <p>Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else.</p> <p>Does anyone have experience getting a <strong>Python</strong> framework <strong>running under IIS</strong> using something other that plain old CGI?</p> <p>If so can you explain to direct me to some instructions on setting this up?</p>
22
2008-09-06T04:26:49Z
47,266
<p>There shouldn't be any need to use FastCGI. There exists a <a href="https://github.com/hexdump42/isapi-wsgi">ISAPI extension for WSGI</a>.</p>
20
2008-09-06T05:32:39Z
[ "python", "iis", "deployment", "windows-server", "iis-modules" ]
How do you set up a python wsgi server under IIS?
47,253
<p>I work in a windows environment and would prefer to deploy code to IIS. At the same time I would like to code in python.</p> <p>Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else.</p> <p>Does anyone have experience getting a <strong>Python</strong> framework <strong>running under IIS</strong> using something other that plain old CGI?</p> <p>If so can you explain to direct me to some instructions on setting this up?</p>
22
2008-09-06T04:26:49Z
37,523,628
<p>We can use iiswsgi framework to setup WSGI over IIS since it is compatible with IIS web server's FastCGI protocol.It's bundled with distutils for building, distribution and installing packages with the help of Microsoft Web Deploy and Web Platform Installer. </p> <p>For more info refer the following link:</p> <p><a href="https://pypi.python.org/pypi/iiswsgi#serving-python-wsgi-applications-natively-from-iis" rel="nofollow">Serving Python WSGI applications natively from IIS</a></p>
4
2016-05-30T10:39:30Z
[ "python", "iis", "deployment", "windows-server", "iis-modules" ]
How do you set up a python wsgi server under IIS?
47,253
<p>I work in a windows environment and would prefer to deploy code to IIS. At the same time I would like to code in python.</p> <p>Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else.</p> <p>Does anyone have experience getting a <strong>Python</strong> framework <strong>running under IIS</strong> using something other that plain old CGI?</p> <p>If so can you explain to direct me to some instructions on setting this up?</p>
22
2008-09-06T04:26:49Z
37,529,437
<p>Microsoft itself develops <a href="https://pypi.python.org/pypi/wfastcgi" rel="nofollow">wfastcgi</a> (<a href="https://github.com/Microsoft/PTVS/tree/master/Python/Product/WFastCgi" rel="nofollow">source code</a>) to host Python code on IIS.</p>
4
2016-05-30T15:39:37Z
[ "python", "iis", "deployment", "windows-server", "iis-modules" ]
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
24
2008-09-06T18:14:05Z
47,744
<p>What platform are you attempting this on? Most debuggers allow you to attach to a running process by using the process id. You can either output the process id via logging or using something like Task Manager. Once that is achieved it will be possible to inspect individual threads and their call stacks.</p> <p>EDIT: I don't have any experience with GNU Debugger (GDB), which is cross platform, however I found this <a href="http://wiki.python.org/moin/DebuggingWithGdb" rel="nofollow">link</a> and it may start you on the right path. It explains how to add debug symbols (handy for reading stack traces) and how to instruct gdb to attach to a running python process.</p>
0
2008-09-06T19:08:14Z
[ "python", "debugging" ]
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
24
2008-09-06T18:14:05Z
56,510
<p>Yeah, gdb is good for lower level debugging.</p> <p>You can change threads with the <em>thread</em> command.</p> <p>e.g</p> <pre><code>(gdb) thr 2 [Switching to thread 2 (process 6159 thread 0x3f1b)] (gdb) backtrace .... </code></pre> <p>You could also check out Python specific debuggers like <a href="http://winpdb.org/about/">Winpdb</a>, or <a href="http://bashdb.sourceforge.net/pydb/">pydb</a>. Both platform independent. </p>
8
2008-09-11T13:19:10Z
[ "python", "debugging" ]
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
24
2008-09-06T18:14:05Z
59,179
<p>If you mean the pydb, there is no way to do it. There was some effort in that direction: <a href="http://svn.python.org/projects/sandbox/trunk/pdb/mpdb.py" rel="nofollow">see the svn commit</a>, but it was abandoned. Supposedly <a href="http://winpdb.org/docs/launch-time/" rel="nofollow">winpdb supports it</a>.</p>
3
2008-09-12T14:51:51Z
[ "python", "debugging" ]
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
24
2008-09-06T18:14:05Z
277,800
<p>My experience debugging multi-threaded programs in PyDev (Eclipse on Windows XP) is, threads created using thread.start_new_thread could not be hooked, but thread created using threading.Thread could be hooked. Hope the information is helpful.</p>
3
2008-11-10T12:58:24Z
[ "python", "debugging" ]
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
24
2008-09-06T18:14:05Z
550,795
<p>You can attach a debugger to a multi-threaded Python process, but you need to do it at the C level. To make sense of what's going on, you need the Python interpreter to be compiled with symbols. If you don't have one, you need to download source from python.org and build it yourself:</p> <pre><code>./configure --prefix=/usr/local/pydbg make OPT=-g sudo make install sudo ln -s /usr/local/pydbg/bin/python /usr/local/bin/dbgpy </code></pre> <p>Make sure your workload is running on that version of the interpreter. You can then attach to it with GDB at any time. The Python folks have included a sample ".gdbinit" in their Misc directory, which has some useful macros. However it's broken for multi-threaded debugging (!). You need to replace lines like this</p> <pre><code>while $pc &lt; Py_Main || $pc &gt; Py_GetArgcArgv </code></pre> <p>with the following:</p> <pre><code>while ($pc &lt; Py_Main || $pc &gt; Py_GetArgcArgv) &amp;&amp; ($pc &lt; t_bootstrap || $pc &gt; thread_PyThread_start_new_thread) </code></pre> <p>Otherwise commands like <code>pystack</code> won't terminate on threads other than the main thread. With this stuff in place, you can do stuff like</p> <pre><code>gdb&gt; attach &lt;PID&gt; gdb&gt; info threads gdb&gt; thread &lt;N&gt; gdb&gt; bt gdb&gt; pystack gdb&gt; detach </code></pre> <p>and see what's going on. Kind of.</p> <p>You can parse what the objects are with the "pyo" macro. <a href="http://chrismiles.livejournal.com/20226.html">Chris has some examples</a> on his blog.</p> <p>Good luck.</p> <p>(Shoutout for <a href="http://mcfunley.com/cs/blogs/dan/archive/2007/10/19/1530.aspx">Dan's blog</a> for some key information for me, notably the threading fix!)</p>
6
2009-02-15T12:18:34Z
[ "python", "debugging" ]
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
24
2008-09-06T18:14:05Z
553,633
<p>Use <a href="http://winpdb.org/">Winpdb</a>. It is a <strong>platform independent</strong> graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p> <p>Features:</p> <ul> <li>GPL license. Winpdb is Free Software.</li> <li>Compatible with CPython 2.3 through 2.6 and Python 3000</li> <li>Compatible with wxPython 2.6 through 2.8</li> <li>Platform independent, and tested on Ubuntu Gutsy and Windows XP.</li> <li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li> </ul> <p><img src="http://winpdb.org/images/screenshot%5Fwinpdb%5Fsmall.jpg" alt="Screenshot"></p>
12
2009-02-16T15:18:44Z
[ "python", "debugging" ]
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
24
2008-09-06T18:14:05Z
29,093,342
<p><a href="https://github.com/dcramer/pdbinject" rel="nofollow">pdbinject</a> allows you to inject pdb into an already running python process.</p> <p>The pdbinject executable only works under python2, but can inject into python3 just fine too. </p>
0
2015-03-17T07:18:57Z
[ "python", "debugging" ]
Is there a way to attach a debugger to a multi-threaded Python process?
47,701
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
24
2008-09-06T18:14:05Z
29,354,135
<p><a href="https://www.jetbrains.com/pycharm/" rel="nofollow">PyCharm IDE</a> allows attaching to a running Python process since version 4.0. </p> <p><a href="https://www.jetbrains.com/pycharm/help/attaching-to-process.html" rel="nofollow">Here</a> is described how to do that.</p>
0
2015-03-30T19:02:50Z
[ "python", "debugging" ]
Generator Expressions vs. List Comprehension
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
213
2008-09-06T20:07:59Z
47,792
<p>Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use generator expressions where the range is large or infinite.</p>
59
2008-09-06T20:10:59Z
[ "python", "list-comprehension", "generator" ]
Generator Expressions vs. List Comprehension
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
213
2008-09-06T20:07:59Z
47,793
<p>Iterating over the <em>generator expression</em> or the <em>list comprehension</em> will do the same thing. However, the <em>list comprehension</em> will create the entire list in memory first while the <em>generator expression</em> will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.</p>
89
2008-09-06T20:11:17Z
[ "python", "list-comprehension", "generator" ]
Generator Expressions vs. List Comprehension
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
213
2008-09-06T20:07:59Z
47,826
<p>John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:</p> <pre><code>def gen(): return (something for something in get_some_stuff()) print gen()[:2] # generators don't support indexing or slicing print [5,6] + gen() # generators can't be added to lists </code></pre> <p>Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.</p> <p>Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.</p>
168
2008-09-06T20:54:08Z
[ "python", "list-comprehension", "generator" ]
Generator Expressions vs. List Comprehension
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
213
2008-09-06T20:07:59Z
53,255
<p>Sometimes you can get away with the <em>tee</em> function from <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow">itertools</a>, it returns multiple iterators for the same generator that can be used independently.</p>
3
2008-09-10T00:58:03Z
[ "python", "list-comprehension", "generator" ]
Generator Expressions vs. List Comprehension
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
213
2008-09-06T20:07:59Z
189,840
<p>The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.</p> <p>For example:</p> <pre><code>sum(x*2 for x in xrange(256)) dict( ((k, some_func(k) for k in some_list_of_keys) ) </code></pre> <p>The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)</p> <p>You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.</p> <p>For example:</p> <pre><code>reversed( [x*2 for x in xrange(256)] ) </code></pre>
34
2008-10-10T01:42:30Z
[ "python", "list-comprehension", "generator" ]
Generator Expressions vs. List Comprehension
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
213
2008-09-06T20:07:59Z
22,858,478
<p>The important point is that the list comprehension creates a new list. The generator creates a an iterable object that will "filter" the source material on-the-fly as you consume the bits.</p> <p>Imagine you have a 2TB log file called "hugefile.txt", and you want the content and length for all the lines that start with the word "ENTRY".</p> <p>So you try starting out by writing a list comprehension:</p> <pre><code>logfile = open("hugefile.txt","r") entry_lines = [(line,len(line)) for line in logfile if line.startswith("ENTRY")] </code></pre> <p>This slurps up the whole file, processes each line, and stores the matching lines in your array. This array could therefore contain up to 2TB of content. That's a lot of RAM, and probably not practical for your purposes.</p> <p>So instead we can use a generator to apply a "filter" to our content. No data is actually read until we start iterating over the result.</p> <pre><code>logfile = open("hugefile.txt","r") entry_lines = ((line,len(line)) for line in logfile if line.startswith("ENTRY")) </code></pre> <p>Not even a single line has been read from our file yet. In fact, say we want to filter our result even further:</p> <pre><code>long_entries = ((line,length) for (line,length) in entry_lines if length &gt; 80) </code></pre> <p>Still nothing has been read, but we've specified now two generators that will act on our data as we wish.</p> <p>Lets write out our filtered lines to another file:</p> <pre><code>outfile = open("filtered.txt","a") for entry,length in long_entries: outfile.write(entry) </code></pre> <p><em>Now</em> we read the input file. As our <code>for</code> loop continues to request additional lines, the <code>long_entries</code> generator demands lines from the <code>entry_lines</code> generator, returning only those whose length is greater than 80 characters. And in turn, the <code>entry_lines</code> generator requests lines (filtered as indicated) from the <code>logfile</code> iterator, which in turn reads the file.</p> <p>So instead of "pushing" data to your output function in the form of a fully-populated list, you're giving the output function a way to "pull" data only when its needed. This is in our case much more efficient, but not quite as flexible. Generators are one way, one pass; the data from the log file we've read gets immediately discarded, so we can't go back to a previous line. On the other hand, we don't have to worry about keeping data around once we're done with it.</p>
27
2014-04-04T09:14:57Z
[ "python", "list-comprehension", "generator" ]
Generator Expressions vs. List Comprehension
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
213
2008-09-06T20:07:59Z
34,599,335
<p>I'm using the Hadoop Mincemeat module. I think this is a great example to take a note of:</p> <pre><code>def mapfn(k,v): for w in v: yield 'sum',w #yield 'count',1 def reducefn(k,v): r1=sum(v) r2=len(v) print r2 m=r1/r2 std=0 for i in range(r2): std+=pow(abs(v[i]-m),2) res=pow((std/r2),0.5) return r1,r2,res </code></pre> <p>Here the generator gets numbers out of a text file (as big as 15GB) and applies simple math on those numbers using Hadoop's map-reduce. If I had not used the yield function, but instead a list comprehension, it would have taken a much longer time calculating the sums and average (not to mention the space complexity).</p> <p>Hadoop is the best example for using all the advantages of Generators.</p>
1
2016-01-04T20:31:50Z
[ "python", "list-comprehension", "generator" ]
Generator Expressions vs. List Comprehension
47,789
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
213
2008-09-06T20:07:59Z
35,964,024
<p>When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:</p> <pre><code>&gt;&gt;&gt; mylist = ["a", "b", "c"] &gt;&gt;&gt; gen = (elem + "1" for elem in mylist) &gt;&gt;&gt; mylist.clear() &gt;&gt;&gt; for x in gen: print (x) # nothing </code></pre> <p>If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.</p>
1
2016-03-12T22:21:00Z
[ "python", "list-comprehension", "generator" ]
User Authentication in Pylons + AuthKit
47,801
<p>I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook.com/alpha1/authentication_and_authorization">PylonsBook</a> page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?</p> <p>I tried downloading the <a href="http://pypi.python.org/pypi/SimpleSiteTemplate/">SimpleSiteTemplate</a> from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:</p> <pre><code> File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' </code></pre> <p>I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.</p>
6
2008-09-06T20:17:45Z
52,136
<p>I don't think AuthKit is actively maintained anymore. It does use the Paste (<a href="http://pythonpaste.org" rel="nofollow">http://pythonpaste.org</a>) libs though for things like HTTP Basic/Digest authentication. I would probably go ahead and take a look at the source for some inspiration and then use the Paste tools if you want to use HTTP authentication. </p> <p>There is also OpenID which is very easy to setup. The python-openid libs have an excellent example that is easy to translate to WSGI for wrapping a Pylons app. You can look at an example:</p> <p><a href="http://ionrock.org/hg/brightcontent-main/file/d87b7dcc606c/brightcontent/plugins/openidauth.py" rel="nofollow">http://ionrock.org/hg/brightcontent-main/file/d87b7dcc606c/brightcontent/plugins/openidauth.py</a></p>
1
2008-09-09T15:18:50Z
[ "python", "authentication", "sqlalchemy", "pylons", "authkit" ]
User Authentication in Pylons + AuthKit
47,801
<p>I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook.com/alpha1/authentication_and_authorization">PylonsBook</a> page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?</p> <p>I tried downloading the <a href="http://pypi.python.org/pypi/SimpleSiteTemplate/">SimpleSiteTemplate</a> from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:</p> <pre><code> File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' </code></pre> <p>I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.</p>
6
2008-09-06T20:17:45Z
61,614
<p>This actually got me interested:<a href="http://groups.google.com/group/pylons-discuss/browse_thread/thread/644deb53612af362?hl=en" rel="nofollow">Check out this mailing on the pylons list</a>. So AuthKit is being developed, and I will follow the book and get back on the results.</p>
1
2008-09-14T20:26:02Z
[ "python", "authentication", "sqlalchemy", "pylons", "authkit" ]
User Authentication in Pylons + AuthKit
47,801
<p>I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook.com/alpha1/authentication_and_authorization">PylonsBook</a> page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?</p> <p>I tried downloading the <a href="http://pypi.python.org/pypi/SimpleSiteTemplate/">SimpleSiteTemplate</a> from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:</p> <pre><code> File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' </code></pre> <p>I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.</p>
6
2008-09-06T20:17:45Z
139,574
<p>Ok, another update on the subject. It seems that the cheeseshop template is broken. I've followed the chapter you linked in the post and it seems that authkit is working fine. There are some caveats:</p> <ol> <li>sqlalchemy has to be in 0.5 version</li> <li>authkit has to be the dev version from svn (easy_install authkit==dev)</li> </ol> <p>I managed to get it working fine.</p>
2
2008-09-26T13:42:50Z
[ "python", "authentication", "sqlalchemy", "pylons", "authkit" ]
User Authentication in Pylons + AuthKit
47,801
<p>I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook.com/alpha1/authentication_and_authorization">PylonsBook</a> page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?</p> <p>I tried downloading the <a href="http://pypi.python.org/pypi/SimpleSiteTemplate/">SimpleSiteTemplate</a> from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:</p> <pre><code> File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' </code></pre> <p>I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.</p>
6
2008-09-06T20:17:45Z
255,183
<p>Check out this tutorial:</p> <p><a href="http://wiki.pylonshq.com/display/pylonscookbook/AuthKit+0.4+UsersFromDatabase+with+SQLAlchemy+0.4+and+SQLAlchemyManager" rel="nofollow">http://wiki.pylonshq.com/display/pylonscookbook/AuthKit+0.4+UsersFromDatabase+with+SQLAlchemy+0.4+and+SQLAlchemyManager</a></p>
0
2008-10-31T22:47:23Z
[ "python", "authentication", "sqlalchemy", "pylons", "authkit" ]