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
list
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
844,828
<p>I ended up adding a method to the model in question, and that method can be accessed like an attribute in the template.</p> <p>Still, i think it would be great if a built in tag allowed you to dynamically lookup an attribute, since this is a problem a lot of us constantly have in our templates. </p>
2
2009-05-10T06:32:43Z
[ "python", "django", "django-templates" ]
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
1,112,236
<p>I also had to <a href="http://snipt.net/Fotinakis/django-template-tag-for-dynamic-attribute-lookups/">write this code</a> as a custom template tag recently. To handle all look-up scenarios, it first does a standard attribute look-up, then tries to do a dictionary look-up, then tries a <strong>getitem</strong> lookup (for lists to work), then follows standard Django template behavior when an object is not found.</p> <p>(updated 2009-08-26 to now handle list index lookups as well)</p> <pre><code># app/templatetags/getattribute.py import re from django import template from django.conf import settings numeric_test = re.compile("^\d+$") register = template.Library() def getattribute(value, arg): """Gets an attribute of an object dynamically from a string name""" if hasattr(value, str(arg)): return getattr(value, arg) elif hasattr(value, 'has_key') and value.has_key(arg): return value[arg] elif numeric_test.match(str(arg)) and len(value) &gt; int(arg): return value[int(arg)] else: return settings.TEMPLATE_STRING_IF_INVALID register.filter('getattribute', getattribute) </code></pre> <p>Template usage:</p> <pre><code>{% load getattribute %} {{ object|getattribute:dynamic_string_var }} </code></pre> <p><br /></p>
48
2009-07-10T22:09:44Z
[ "python", "django", "django-templates" ]
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
9,778,611
<p>Keeping the distinction between get and getattr, </p> <pre><code>@register.filter(name='get') def get(o, index): try: return o[index] except: return settings.TEMPLATE_STRING_IF_INVALID @register.filter(name='getattr') def getattrfilter(o, attr): try: return getattr(o, attr) except: return settings.TEMPLATE_STRING_IF_INVALID </code></pre>
2
2012-03-19T22:01:55Z
[ "python", "django", "django-templates" ]
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
27,964,123
<p>That snippet saved my day but i needed it to span it over relations so I changed it to split the arg by "." and recursively get the value. It could be done in one line: <code>return getattribute(getattribute(value,str(arg).split(".")[0]),".".join(str(arg).split(".")[1:]))</code> but I left it in 4 for readability. I hope someone has use for this.</p> <pre><code>import re from django import template from django.conf import settings numeric_test = re.compile("^\d+$") register = template.Library() def getattribute(value, arg): """Gets an attribute of an object dynamically AND recursively from a string name""" if "." in str(arg): firstarg = str(arg).split(".")[0] value = getattribute(value,firstarg) arg = ".".join(str(arg).split(".")[1:]) return getattribute(value,arg) if hasattr(value, str(arg)): return getattr(value, arg) elif hasattr(value, 'has_key') and value.has_key(arg): return value[arg] elif numeric_test.match(str(arg)) and len(value) &gt; int(arg): return value[int(arg)] else: #return settings.TEMPLATE_STRING_IF_INVALID return 'no attr.' + str(arg) + 'for:' + str(value) register.filter('getattribute', getattribute) </code></pre>
0
2015-01-15T13:03:27Z
[ "python", "django", "django-templates" ]
Defining dynamic functions to a string
844,886
<p>I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For example I got a file where for each line, i need to use line.replace(' ','') and line.strip()...</p> <p>What's the best way to make all of these as part of my script? So I can just say assign numbers to each functions and just say apply function 1 and 4 for each line. </p>
1
2009-05-10T07:44:22Z
844,907
<p>It is possible to map string operations to numbers:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; ops = {1:string.split, 2:string.replace} &gt;&gt;&gt; my = "a,b,c" &gt;&gt;&gt; ops[1](",", my) [','] &gt;&gt;&gt; ops[1](my, ",") ['a', 'b', 'c'] &gt;&gt;&gt; ops[2](my, ",", "-") 'a-b-c' &gt;&gt;&gt; </code></pre> <p>But maybe string descriptions of the operations will be more readable.</p> <pre><code>&gt;&gt;&gt; ops2={"split":string.split, "replace":string.replace} &gt;&gt;&gt; ops2["split"](my, ",") ['a', 'b', 'c'] &gt;&gt;&gt; </code></pre> <p>Note: Instead of using the <code>string</code> module, you can use the <code>str</code> type for the same effect.</p> <pre><code>&gt;&gt;&gt; ops={1:str.split, 2:str.replace} </code></pre>
2
2009-05-10T08:02:55Z
[ "python" ]
Defining dynamic functions to a string
844,886
<p>I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For example I got a file where for each line, i need to use line.replace(' ','') and line.strip()...</p> <p>What's the best way to make all of these as part of my script? So I can just say assign numbers to each functions and just say apply function 1 and 4 for each line. </p>
1
2009-05-10T07:44:22Z
844,923
<p>If you insist on numbers, you can't do much better than a dict (as gimel suggests) or list of functions (with indices zero and up). With names, though, you don't necessarily need an auxiliary data structure (such as gimel's suggested dict), since you can simply use getattr to retrieve the method to call from the object itself or its type. E.g.:</p> <pre><code>def all_lines(somefile, methods): """Apply a sequence of methods to all lines of some file and yield the results. Args: somefile: an open file or other iterable yielding lines methods: a string that's a whitespace-separated sequence of method names. (note that the methods must be callable without arguments beyond the str to which they're being applied) """ tobecalled = [getattr(str, name) for name in methods.split()] for line in somefile: for tocall in tobecalled: line = tocall(line) yield line </code></pre>
2
2009-05-10T08:18:04Z
[ "python" ]
Defining dynamic functions to a string
844,886
<p>I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For example I got a file where for each line, i need to use line.replace(' ','') and line.strip()...</p> <p>What's the best way to make all of these as part of my script? So I can just say assign numbers to each functions and just say apply function 1 and 4 for each line. </p>
1
2009-05-10T07:44:22Z
845,041
<p>First of all, many string functions – including strip and replace – are <a href="http://docs.python.org/library/string.html#deprecated-string-functions" rel="nofollow" title="Deprecated string functions">deprecated</a>. The following answer uses string methods instead. (Instead of <code>string.strip(" Hello ")</code>, I use the equivalent of <code>" Hello ".strip()</code>.)</p> <p>Here's some code that will simplify the job for you. The following code assumes that whatever methods you call on your string, that method will return another string.</p> <pre><code>class O(object): c = str.capitalize r = str.replace s = str.strip def process_line(line, *ops): i = iter(ops) while True: try: op = i.next() args = i.next() except StopIteration: break line = op(line, *args) return line </code></pre> <p>The <code>O</code> class exists so that your highly abbreviated method names don't pollute your namespace. When you want to add more string methods, you add them to <code>O</code> in the same format as those given.</p> <p>The <code>process_line</code> function is where all the interesting things happen. First, here is a description of the argument format:</p> <ul> <li>The first argument is the string to be processed.</li> <li>The remaining arguments must be given in pairs. <ul> <li>The first argument of the pair is a string method. Use the shortened method names here.</li> <li>The second argument of the pair is a list representing the arguments to that particular string method.</li> </ul></li> </ul> <p>The <code>process_line</code> function returns the string that emerges after all these operations have performed.</p> <p>Here is some example code showing how you would use the above code in your own scripts. I've separated the arguments of <code>process_line</code> across multiple lines to show the grouping of the arguments. Of course, if you're just hacking away and using this code in day-to-day scripts, you can compress all the arguments onto one line; this actually makes it a little easier to read.</p> <pre><code>f = open("parrot_sketch.txt") for line in f: p = process_line( line, O.r, ["He's resting...", "This is an ex-parrot!"], O.c, [], O.s, [] ) print p </code></pre> <p>Of course, if you very specifically wanted to use numerals, you could name your functions <code>O.f1</code>, <code>O.f2</code>, <code>O.f3</code>… but I'm assuming that wasn't the spirit of your question.</p>
2
2009-05-10T10:04:52Z
[ "python" ]
Defining dynamic functions to a string
844,886
<p>I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For example I got a file where for each line, i need to use line.replace(' ','') and line.strip()...</p> <p>What's the best way to make all of these as part of my script? So I can just say assign numbers to each functions and just say apply function 1 and 4 for each line. </p>
1
2009-05-10T07:44:22Z
845,875
<p>To map names (or numbers) to different string operations, I'd do something like</p> <pre><code>OPERATIONS = dict( strip = str.strip, lower = str.lower, removespaces = lambda s: s.replace(' ', ''), maketitle = lamdba s: s.title().center(80, '-'), # etc ) def process(myfile, ops): for line in myfile: for op in ops: line = OPERATIONS[op](line) yield line </code></pre> <p>which you use like this</p> <pre><code>for line in process(afile, ['strip', 'removespaces']): ... </code></pre>
0
2009-05-10T18:57:59Z
[ "python" ]
"x Days ago' template filter in Django?
845,009
<p>I'm looking for a filter that turns a datetime instance into 'x Days' or 'x years y months' format (as on SO). Suggestions? Am I overlooking something very obvious?</p>
7
2009-05-10T09:35:55Z
845,014
<p>Have a look at the <a href="http://docs.djangoproject.com/en/1.0/ref/templates/builtins/#timesince">timesince</a> template filter. It's builtin.</p> <p>The following returns a humanized diff between now and <code>comment_date</code> (e.g. <code>'8 hours'</code>):</p> <pre><code>{{ comment_date|timesince }} </code></pre> <p>The following returns a humanized diff between <code>question_date</code> and <code>comment_date</code>:</p> <pre><code>{{ comment_date|timesince:question_date }} </code></pre>
21
2009-05-10T09:43:02Z
[ "python", "django" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
845,069
<p>You could execute a subprocess and run <code>wc -l filename</code></p> <pre><code>import subprocess def file_len(fname): p = subprocess.Popen(['wc', '-l', fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, err = p.communicate() if p.returncode != 0: raise IOError(err) return int(result.strip().split()[0]) </code></pre>
49
2009-05-10T10:28:29Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
845,075
<pre><code>def file_len(full_path): """ Count number of lines in a file.""" f = open(full_path) nr_of_lines = sum(1 for line in f) f.close() return nr_of_lines </code></pre>
5
2009-05-10T10:33:41Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
845,081
<p>You can't get any better than that.</p> <p>After all, any solution will have to read the entire file, figure out how many <code>\n</code> you have, and return that result.</p> <p>Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you can do is make sure you don't use unnecessary memory, but it looks like you have that covered.</p>
157
2009-05-10T10:37:42Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
845,151
<p>As for me this variant will be the fastest:</p> <pre><code>#!/usr/bin/env python def main(): f = open('filename') lines = 0 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) print lines if __name__ == '__main__': main() </code></pre> <p>reasons: buffering faster than reading line by line and <code>string.count</code> is also very fast</p>
3
2009-05-10T11:29:12Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
845,157
<p>the result of opening a file is an iterator, which can be converted to a sequence, which has a length:</p> <pre><code>with open(filename) as f: return len(list(f)) </code></pre> <p>this is more concise than your explicit loop, and avoids the <code>enumerate</code>.</p>
3
2009-05-10T11:35:26Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
845,802
<p>What about this</p> <pre><code>def file_len(fname): counts = itertools.count() with open(fname) as f: for _ in f: counts.next() return counts.next() </code></pre>
3
2009-05-10T18:20:28Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
845,836
<p>Why not read the first 100 and the last 100 lines and estimate the average line length, then divide the total file size through that numbers? If you don't need a exact value this could work.</p>
0
2009-05-10T18:36:20Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
850,962
<p>I believe that a memory mapped file will be the fastest solution. I tried four functions: the function posted by the OP (<code>opcount</code>); a simple iteration over the lines in the file (<code>simplecount</code>); readline with a memory-mapped filed (mmap) (<code>mapcount</code>); and the buffer read solution offered by Mykola Kharechko (<code>bufcount</code>).</p> <p>I ran each function five times, and calculated the average run-time for a 1.2 million-line text file.</p> <p>Windows XP, Python 2.5, 2GB RAM, 2 GHz AMD processor</p> <p>Here are my results:</p> <pre><code>mapcount : 0.465599966049 simplecount : 0.756399965286 bufcount : 0.546800041199 opcount : 0.718600034714 </code></pre> <p><strong>Edit</strong>: numbers for Python 2.6:</p> <pre><code>mapcount : 0.471799945831 simplecount : 0.634400033951 bufcount : 0.468800067902 opcount : 0.602999973297 </code></pre> <p>So the buffer read strategy seems to be the fastest for Windows/Python 2.6</p> <p>Here is the code:</p> <pre><code>from __future__ import with_statement import time import mmap import random from collections import defaultdict def mapcount(filename): f = open(filename, "r+") buf = mmap.mmap(f.fileno(), 0) lines = 0 readline = buf.readline while readline(): lines += 1 return lines def simplecount(filename): lines = 0 for line in open(filename): lines += 1 return lines def bufcount(filename): f = open(filename) lines = 0 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines def opcount(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 counts = defaultdict(list) for i in range(5): for func in [mapcount, simplecount, bufcount, opcount]: start_time = time.time() assert func("big_file.txt") == 1209138 counts[func].append(time.time() - start_time) for key, vals in counts.items(): print key.__name__, ":", sum(vals) / float(len(vals)) </code></pre>
139
2009-05-12T02:49:04Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
1,019,572
<p>One line, probably pretty fast:</p> <pre><code>num_lines = sum(1 for line in open('myfile.txt')) </code></pre>
308
2009-06-19T19:07:06Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
2,772,853
<p>Just to complete the above methods I tried a variant with the fileinput module:</p> <pre><code>import fileinput as fi def filecount(fname): for line in fi.input(fname): pass return fi.lineno() </code></pre> <p>And passed a 60mil lines file to all the above stated methods:</p> <pre><code>mapcount : 6.1331050396 simplecount : 4.588793993 opcount : 4.42918205261 filecount : 43.2780818939 bufcount : 0.170812129974 </code></pre> <p>It's a little surprise to me that fileinput is that bad and scales far worse than all the other methods...</p>
4
2010-05-05T11:48:21Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
3,119,185
<p>what about this?</p> <pre><code>import sys sys.stdin=open('fname','r') data=sys.stdin.readlines() print "counted",len(data),"lines" </code></pre>
0
2010-06-25T15:17:32Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
4,359,897
<p>Why wouldn't the following work?</p> <pre><code>import sys # input comes from STDIN file = sys.stdin data = file.readlines() # get total number of lines in file lines = len(data) print lines </code></pre> <p>In this case, the len function uses the input lines as a means of determining the length.</p>
0
2010-12-05T16:45:54Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
5,278,398
<p><code>count = max(enumerate(open(filename)))[0]</code></p>
3
2011-03-11T21:09:52Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
6,750,195
<p>How about this?</p> <pre><code>import fileinput import sys counter=0 for line in fileinput.input([sys.argv[1]]): counter+=1 fileinput.close() print counter </code></pre>
0
2011-07-19T15:55:39Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
6,826,326
<p>Here is a python program to use the multiprocessing library to distribute the line counting across machines/cores. My test improves counting a 20million line file from 26 seconds to 7 seconds using an 8 core windows 64 server. Note: not using memory mapping makes things much slower.</p> <pre><code>import multiprocessing, sys, time, os, mmap import logging, logging.handlers def init_logger(pid): console_format = 'P{0} %(levelname)s %(message)s'.format(pid) logger = logging.getLogger() # New logger at root level logger.setLevel( logging.INFO ) logger.handlers.append( logging.StreamHandler() ) logger.handlers[0].setFormatter( logging.Formatter( console_format, '%d/%m/%y %H:%M:%S' ) ) def getFileLineCount( queues, pid, processes, file1 ): init_logger(pid) logging.info( 'start' ) physical_file = open(file1, "r") # mmap.mmap(fileno, length[, tagname[, access[, offset]]] m1 = mmap.mmap( physical_file.fileno(), 0, access=mmap.ACCESS_READ ) #work out file size to divide up line counting fSize = os.stat(file1).st_size chunk = (fSize / processes) + 1 lines = 0 #get where I start and stop _seedStart = chunk * (pid) _seekEnd = chunk * (pid+1) seekStart = int(_seedStart) seekEnd = int(_seekEnd) if seekEnd &lt; int(_seekEnd + 1): seekEnd += 1 if _seedStart &lt; int(seekStart + 1): seekStart += 1 if seekEnd &gt; fSize: seekEnd = fSize #find where to start if pid &gt; 0: m1.seek( seekStart ) #read next line l1 = m1.readline() # need to use readline with memory mapped files seekStart = m1.tell() #tell previous rank my seek start to make their seek end if pid &gt; 0: queues[pid-1].put( seekStart ) if pid &lt; processes-1: seekEnd = queues[pid].get() m1.seek( seekStart ) l1 = m1.readline() while len(l1) &gt; 0: lines += 1 l1 = m1.readline() if m1.tell() &gt; seekEnd or len(l1) == 0: break logging.info( 'done' ) # add up the results if pid == 0: for p in range(1,processes): lines += queues[0].get() queues[0].put(lines) # the total lines counted else: queues[0].put(lines) m1.close() physical_file.close() if __name__ == '__main__': init_logger( 'main' ) if len(sys.argv) &gt; 1: file_name = sys.argv[1] else: logging.fatal( 'parameters required: file-name [processes]' ) exit() t = time.time() processes = multiprocessing.cpu_count() if len(sys.argv) &gt; 2: processes = int(sys.argv[2]) queues=[] # a queue for each process for pid in range(processes): queues.append( multiprocessing.Queue() ) jobs=[] prev_pipe = 0 for pid in range(processes): p = multiprocessing.Process( target = getFileLineCount, args=(queues, pid, processes, file_name,) ) p.start() jobs.append(p) jobs[0].join() #wait for counting to finish lines = queues[0].get() logging.info( 'finished {} Lines:{}'.format( time.time() - t, lines ) ) </code></pre>
23
2011-07-26T06:51:01Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
8,270,828
<p>I have modified the buffer case like this:</p> <pre><code>def CountLines(filename): f = open(filename) try: lines = 1 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) # Empty file if not buf: return 0 while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines finally: f.close() </code></pre> <p>Now also empty files and the last line (without \n) are counted.</p>
2
2011-11-25T14:55:52Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
15,074,925
<p>I got a small (4-8%) improvement with this version which re-uses a constant buffer so it should avoid any memory or GC overhead:</p> <pre><code>lines = 0 buffer = bytearray(2048) with open(filename) as f: while f.readinto(buffer) &gt; 0: lines += buffer.count('\n') </code></pre> <p>You can play around with the buffer size and maybe see a little improvement.</p>
5
2013-02-25T19:31:53Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
18,638,592
<p>Similarly:</p> <pre><code>lines = 0 with open(path) as f: for line in f: lines += 1 </code></pre>
0
2013-09-05T14:08:16Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
19,149,178
<p>How about this one-liner:</p> <pre><code>file_length = len(open('myfile.txt','r').read().split('\n')) </code></pre> <p>Takes 0.003 sec using this method to time it on a 3900 line file</p> <pre><code>def c(): import time s = time.time() file_length = len(open('myfile.txt','r').read().split('\n')) print time.time() - s </code></pre>
-1
2013-10-03T00:55:36Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
19,248,109
<p>I would use Python's file object method <code>readlines</code>, as follows:</p> <pre><code>with open(input_file) as foo: lines = len(foo.readlines()) </code></pre> <p>This opens the file, creates a list of lines in the file, counts the length of the list, saves that to a variable and closes the file again.</p>
8
2013-10-08T12:46:12Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
22,551,496
<pre><code>print open('file.txt', 'r').read().count("\n") + 1 </code></pre>
5
2014-03-21T06:10:30Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
24,003,811
<pre><code>def line_count(path): count = 0 with open(path) as lines: for count, l in enumerate(lines, start=1): pass return count </code></pre>
1
2014-06-02T21:45:10Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
25,544,973
<p>If one wants to get the line count cheaply in Python in Linux, I recommend this method:</p> <pre><code>import os print os.popen("wc -l file_path").readline().split()[0] </code></pre> <p>file_path can be both abstract file path or relative path. Hope this may help.</p>
0
2014-08-28T09:09:45Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
26,375,032
<p><a href="http://stackoverflow.com/a/1019572/2698552">Kyle's answer</a> </p> <pre><code>num_lines = sum(1 for line in open('my_file.txt')) </code></pre> <p>is probably best, an alternative for this is</p> <pre><code>num_lines = len(open('my_file.txt').read().splitlines()) </code></pre> <p>Here is the comparision of performance of both </p> <pre><code>In [20]: timeit sum(1 for line in open('Charts.ipynb')) 100000 loops, best of 3: 9.79 µs per loop In [21]: timeit len(open('Charts.ipynb').read().splitlines()) 100000 loops, best of 3: 12 µs per loop </code></pre>
3
2014-10-15T05:22:12Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
26,695,897
<p>You can use the <code>os.path</code> module in the following way:</p> <pre><code>import os import subprocess Number_lines = int( (subprocess.Popen( 'wc -l {0}'.format( Filename ), shell=True, stdout=subprocess.PIPE).stdout).readlines()[0].split()[0] ) </code></pre> <p>, where <code>Filename</code> is the absolute path of the file.</p>
0
2014-11-02T03:58:48Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
27,518,377
<p>I had to post this on a similar question until my reputation score jumped a bit (thanks to whoever bumped me!). </p> <p>All of these solutions ignore one way to make this run considerably faster, namely by using the unbuffered (raw) interface, using bytearrays, and doing your own buffering. (This only applies in Python 3. In Python 2, the raw interface may or may not be used by default, but in Python 3, you'll default into Unicode.)</p> <p>Using a modified version of the timing tool, I believe the following code is faster (and marginally more pythonic) than any of the solutions offered:</p> <pre><code>def rawcount(filename): f = open(filename, 'rb') lines = 0 buf_size = 1024 * 1024 read_f = f.raw.read buf = read_f(buf_size) while buf: lines += buf.count(b'\n') buf = read_f(buf_size) return lines </code></pre> <p>Using a separate generator function, this runs a smidge faster:</p> <pre><code>def _make_gen(reader): b = reader(1024 * 1024) while b: yield b b = reader(1024*1024) def rawgencount(filename): f = open(filename, 'rb') f_gen = _make_gen(f.raw.read) return sum( buf.count(b'\n') for buf in f_gen ) </code></pre> <p>This can be done completely with generators expressions in-line using itertools, but it gets pretty weird looking:</p> <pre><code>from itertools import (takewhile,repeat) def rawincount(filename): f = open(filename, 'rb') bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None))) return sum( buf.count(b'\n') for buf in bufgen ) </code></pre> <p>Here are my timings:</p> <pre><code>function average, s min, s ratio rawincount 0.0043 0.0041 1.00 rawgencount 0.0044 0.0042 1.01 rawcount 0.0048 0.0045 1.09 bufcount 0.008 0.0068 1.64 wccount 0.01 0.0097 2.35 itercount 0.014 0.014 3.41 opcount 0.02 0.02 4.83 kylecount 0.021 0.021 5.05 simplecount 0.022 0.022 5.25 mapcount 0.037 0.031 7.46 </code></pre>
26
2014-12-17T04:32:25Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
28,165,046
<p>Another possibility: </p> <pre><code>import subprocess def num_lines_in_file(fpath): return int(subprocess.check_output('wc -l %s' % fpath, shell=True).strip().split()[0]) </code></pre>
1
2015-01-27T07:08:00Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pre> <p>is it possible to do any better?</p>
470
2009-05-10T10:22:05Z
28,680,922
<p>This code is shorter and clearer. It's probably the best way:</p> <pre><code>num_lines = open('yourfile.ext').read().count('\n') </code></pre>
2
2015-02-23T18:38:13Z
[ "python", "text-files", "line-count" ]
VIM: Use python 2.5 with vim 7.2
845,068
<p>How can use Python2.5 with to write scripts in vim? I'm using vim 7.2 and have Python 2.5. Vim 7.2 seem to be linked with Python 2.4 Do I have to compile from source?</p>
1
2009-05-10T10:27:57Z
845,070
<p><a href="http://www.gooli.org/blog/gvim-72-with-python-2526-support-windows-binaries/" rel="nofollow">Here</a> is a link to VIM 7.2 builds with Python 2.5/2.6 support.</p>
3
2009-05-10T10:30:19Z
[ "python", "vim" ]
Problem when using MemoryDC
845,071
<p>Why does my code print the lines gray instead of black?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self,*args,**kwargs): wx.Frame.__init__(self,*args,**kwargs) self.panel=wx.Panel(self,-1,size=(1000,1000)) self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_SIZE, self.on_size) self.bitmap=wx.EmptyBitmapRGBA(1000,1000,255,255,255,255) dc=wx.MemoryDC() dc.SelectObject(self.bitmap) dc.SetPen(wx.Pen(wx.NamedColor("black"),10,wx.SOLID)) dc.DrawCircle(0,0,30) dc.DrawLine(40,40,70,70) dc.Destroy() self.Show() def on_size(self,e=None): self.Refresh() def on_paint(self,e=None): dc=wx.PaintDC(self.panel) dc.DrawBitmap(self.bitmap,0,0) dc.Destroy() if __name__=="__main__": app=wx.PySimpleApp() my_frame=MyFrame(parent=None,id=-1) app.MainLoop() </code></pre>
1
2009-05-10T10:30:26Z
846,700
<p>Ok I tested with newer version of wx(2.8.9.2) </p> <p>and Now I wonder why it is even working on your side. you are trying to paint Panel but overriding the paint event of Frame</p> <p>instead do this</p> <pre><code>self.panel.Bind(wx.EVT_PAINT, self.on_paint) </code></pre> <p>and all will be fine</p>
0
2009-05-11T04:15:50Z
[ "python", "graphics", "wxpython" ]
Problem when using MemoryDC
845,071
<p>Why does my code print the lines gray instead of black?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self,*args,**kwargs): wx.Frame.__init__(self,*args,**kwargs) self.panel=wx.Panel(self,-1,size=(1000,1000)) self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_SIZE, self.on_size) self.bitmap=wx.EmptyBitmapRGBA(1000,1000,255,255,255,255) dc=wx.MemoryDC() dc.SelectObject(self.bitmap) dc.SetPen(wx.Pen(wx.NamedColor("black"),10,wx.SOLID)) dc.DrawCircle(0,0,30) dc.DrawLine(40,40,70,70) dc.Destroy() self.Show() def on_size(self,e=None): self.Refresh() def on_paint(self,e=None): dc=wx.PaintDC(self.panel) dc.DrawBitmap(self.bitmap,0,0) dc.Destroy() if __name__=="__main__": app=wx.PySimpleApp() my_frame=MyFrame(parent=None,id=-1) app.MainLoop() </code></pre>
1
2009-05-10T10:30:26Z
855,159
<p>Beside the frame/panel paint problem already pointed out the color problem is due to the alpha channel of the 32 bit bitmap.</p> <p>I remember having read to use <code>wx.GCDC</code> instead of <code>wx.DC</code>.</p>
1
2009-05-12T22:20:01Z
[ "python", "graphics", "wxpython" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff </code></pre> <p>is there more efficient or more <em>pythonic</em> way to achieve this goal, making as few assumptions as possible about the object being passed (such as .clone() method)</p> <p><strong>Edit</strong> </p> <p>I'm aware that technically everything in python is passed by value. I was interested in <em>emulating</em> the behaviour, i.e. making sure I don't mess with the data that was passed to the function. I guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy.</p>
33
2009-05-10T11:05:50Z
845,133
<p>I can't figure out any other <em>pythonic</em> option. But personally I'd prefer the more <em>OO</em> way.</p> <pre><code>class TheData(object): def clone(self): """return the cloned""" def f(data): #do stuff def caller(): d = TheData() f(d.clone()) </code></pre>
2
2009-05-10T11:16:43Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff </code></pre> <p>is there more efficient or more <em>pythonic</em> way to achieve this goal, making as few assumptions as possible about the object being passed (such as .clone() method)</p> <p><strong>Edit</strong> </p> <p>I'm aware that technically everything in python is passed by value. I was interested in <em>emulating</em> the behaviour, i.e. making sure I don't mess with the data that was passed to the function. I guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy.</p>
33
2009-05-10T11:05:50Z
845,194
<p>You can make a decorator and put the cloning behaviour in that. </p> <pre><code>&gt;&gt;&gt; def passbyval(func): def new(*args): cargs = [deepcopy(arg) for arg in args] return func(*cargs) return new &gt;&gt;&gt; @passbyval def myfunc(a): print a &gt;&gt;&gt; myfunc(20) 20 </code></pre> <p>This is not the most robust way, and doesn't handle key-value arguments or class methods (lack of self argument), but you get the picture.</p> <p>Note that the following statements are equal:</p> <pre><code>@somedecorator def func1(): pass # ... same as ... def func2(): pass func2 = somedecorator(func2) </code></pre> <p>You could even have the decorator take some kind of function that does the cloning and thus allowing the user of the decorator to decide the cloning strategy. In that case the decorator is probably best implemented as a class with <code>__call__</code> overridden.</p>
24
2009-05-10T11:57:47Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff </code></pre> <p>is there more efficient or more <em>pythonic</em> way to achieve this goal, making as few assumptions as possible about the object being passed (such as .clone() method)</p> <p><strong>Edit</strong> </p> <p>I'm aware that technically everything in python is passed by value. I was interested in <em>emulating</em> the behaviour, i.e. making sure I don't mess with the data that was passed to the function. I guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy.</p>
33
2009-05-10T11:05:50Z
845,691
<p>There is no pythonic way of doing this. </p> <p>Python provides very few facilities for <em>enforcing</em> things such as private or read-only data. The pythonic philosophy is that "we're all consenting adults": in this case this means that "the function shouldn't change the data" is part of the spec but not enforced in the code. </p> <p><hr /></p> <p>If you want to make a copy of the data, the closest you can get is your solution. But <code>copy.deepcopy</code>, besides being inefficient, also has caveats <a href="http://docs.python.org/library/copy.html">such as</a>:</p> <blockquote> <p>Because deep copy copies everything it may copy too much, e.g., administrative data structures that should be shared even between copies.</p> <p>[...]</p> <p>This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types. </p> </blockquote> <p>So i'd only recommend it if you know that you're dealing with built-in Python types or your own objects (where you can customize copying behavior by defining the <code>__copy__</code> / <code>__deepcopy__</code> special methods, there's no need to define your own <code>clone()</code> method).</p>
22
2009-05-10T17:16:08Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff </code></pre> <p>is there more efficient or more <em>pythonic</em> way to achieve this goal, making as few assumptions as possible about the object being passed (such as .clone() method)</p> <p><strong>Edit</strong> </p> <p>I'm aware that technically everything in python is passed by value. I was interested in <em>emulating</em> the behaviour, i.e. making sure I don't mess with the data that was passed to the function. I guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy.</p>
33
2009-05-10T11:05:50Z
1,082,129
<p>usually when passing data to an external API, you can assure the integrity of your data by passing it as an immutable object, for example wrap your data into a tuple. This cannot be modified, if that is what you tried to prevent by your code.</p>
3
2009-07-04T12:30:47Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff </code></pre> <p>is there more efficient or more <em>pythonic</em> way to achieve this goal, making as few assumptions as possible about the object being passed (such as .clone() method)</p> <p><strong>Edit</strong> </p> <p>I'm aware that technically everything in python is passed by value. I was interested in <em>emulating</em> the behaviour, i.e. making sure I don't mess with the data that was passed to the function. I guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy.</p>
33
2009-05-10T11:05:50Z
1,082,972
<p>Though i'm sure there's no really pythonic way to do this, i expect the <code>pickle</code> module will give you copies of everything you have any business treating as a value. </p> <pre><code>import pickle def f(data): data = pickle.loads(pickle.dumps((data))) #do stuff </code></pre>
1
2009-07-04T21:11:20Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff </code></pre> <p>is there more efficient or more <em>pythonic</em> way to achieve this goal, making as few assumptions as possible about the object being passed (such as .clone() method)</p> <p><strong>Edit</strong> </p> <p>I'm aware that technically everything in python is passed by value. I was interested in <em>emulating</em> the behaviour, i.e. making sure I don't mess with the data that was passed to the function. I guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy.</p>
33
2009-05-10T11:05:50Z
9,762,918
<p>There are only a couple of builtin typs that work as references, like <code>list</code>, for example.</p> <p>So, for me the pythonic way for doing a pass-by-value, for list, in this example, would be:</p> <pre><code>list1 = [0,1,2,3,4] list2 = list1[:] </code></pre> <p><code>list1[:]</code> creates a new instance of the list1, and you can assign it to a new variable.</p> <p>Maybe you could write a function that could receive one argument, then check its type, and according that resulta, perform a builtin operation that could return a new instance of the argument passed.</p> <p>As I said earlier, there are only a few builtin types, that their behavior is like references, lists in this example.</p> <p>Any way... hope it helps.</p>
8
2012-03-18T22:32:10Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff </code></pre> <p>is there more efficient or more <em>pythonic</em> way to achieve this goal, making as few assumptions as possible about the object being passed (such as .clone() method)</p> <p><strong>Edit</strong> </p> <p>I'm aware that technically everything in python is passed by value. I was interested in <em>emulating</em> the behaviour, i.e. making sure I don't mess with the data that was passed to the function. I guess the most general way is to clone the object in question either with its own clone mechanism or with deepcopy.</p>
33
2009-05-10T11:05:50Z
28,108,885
<p>Further to <em>user695800's</em> answer, pass by value for lists possible with the [:] operator</p> <pre><code>def listCopy(l): l[1] = 5 for i in l: print i </code></pre> <p>called with </p> <pre><code>In [12]: list1 = [1,2,3,4] In [13]: listCopy(list1[:]) 1 5 3 4 list1 Out[14]: [1, 2, 3, 4] </code></pre>
0
2015-01-23T11:25:36Z
[ "python", "pass-by-value" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
845,116
<p>You could create a function that gets the size of the array, loops through it and creating a return array which it returns.</p>
1
2009-05-10T11:07:15Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
845,120
<p>How about this:</p> <pre><code>a = [x+y for x,y in zip(a,b)] </code></pre>
9
2009-05-10T11:09:52Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
845,123
<p>[a[x] + b[x] for x in range(0,len(a))]</p>
3
2009-05-10T11:11:33Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
845,139
<p>If you need efficient vector arithmetic, try <a href="http://numpy.scipy.org/">Numpy</a>.</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a=numpy.array([0,1,2]) &gt;&gt;&gt; b=numpy.array([3,4,5]) &gt;&gt;&gt; a+b array([3, 5, 7]) &gt;&gt;&gt; </code></pre> <p>Or (thanks, Andrew Jaffe), </p> <pre><code>&gt;&gt;&gt; a += b &gt;&gt;&gt; a array([3, 5, 7]) &gt;&gt;&gt; </code></pre>
27
2009-05-10T11:21:09Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
845,141
<p>Or, if you're willing to use an external library (and fixed-length arrays), use <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a>, which has "+=" and related operations for in-place operations.</p> <pre><code>import numpy as np a = np.array([0, 1, 2]) b = np.array([3, 4, 5]) a += b </code></pre>
4
2009-05-10T11:21:22Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
845,314
<p>While Numeric is excellent, and list-comprehension solutions OK if you actually wanted to create a new list, I'm surprised nobody suggested the "one obvious way to do it" -- a simple <code>for</code> loop! Best:</p> <pre><code>for i, bi in enumerate(b): a[i] += bi </code></pre> <p>Also OK, kinda sorta:</p> <pre><code>for i in xrange(len(a)): a[i] += b[i] </code></pre>
27
2009-05-10T13:15:23Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
845,736
<p>An improvement (less memory consumption) of the comprehension list </p> <p>import itertools a = [x+y for x,y in itertools.izip(a,b)]</p> <p>Actually if you are not sure that a will be consume then I would even go with generator expression:</p> <p>(x+y for x,y in itertools.izip(a,b))</p>
0
2009-05-10T17:43:01Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
845,758
<p>If you think Numpy is overkill, this should be really fast, because this code runs in pure C (<code>map()</code> and <code>__add__()</code> are both directly implemented in C):</p> <pre><code>a = [1.0,2.0,3.0] b = [4.0,5.0,6.0] c = map(float.__add__, a, b) </code></pre> <p>Or alternatively, if you don't know the types in the list:</p> <pre><code>import operator c = map(operator.add, a, b) </code></pre>
12
2009-05-10T17:58:53Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
846,274
<p>I don't think you will find a faster solution than the 3 sums proposed in the question. The advantages of numpy are visible with larger vectors, and also if you need other operators. numpy is specially useful with matrixes, witch are trick to do with python lists.</p> <p>Still, yet another way to do it :D</p> <pre><code>In [1]: a = [1,2,3] In [2]: b = [2,3,4] In [3]: map(sum, zip(a,b)) Out[3]: [3, 5, 7] </code></pre> <p><strong>Edit</strong>: you can also use the izip from itertools, a generator version of zip</p> <pre><code>In [5]: from itertools import izip In [6]: map(sum, izip(a,b)) Out[6]: [3, 5, 7] </code></pre>
20
2009-05-10T22:54:47Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
24,070,053
<p>If you're after concise, try...</p> <pre><code>vectors = [[0.0, 1.0, 2.0],[3.0, 4.0, 5.0]] [sum(col) for col in zip(*vectors)] </code></pre> <p>Though I can't speak for the performance of this.</p>
0
2014-06-05T20:52:01Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
29,979,654
<pre><code>list(map(lambda x:x[0]+x[1], zip(a,b))) </code></pre>
0
2015-04-30T23:50:00Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
32,358,629
<p>For the general case of having a list of lists you could do something like this:</p> <pre><code>In [2]: import numpy as np In [3]: a = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3],[4, 5, 6]]) In [4]: [sum(a[:,i]) for i in xrange(len(a[0]))] Out[4]: [10, 11, 12] </code></pre>
1
2015-09-02T16:41:23Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] += b[1] a[2] += b[2] </code></pre> <p>Is there some efficient, standard way to do this with less typing?</p> <p>UPDATE: It can be assumed that the lists are of length 3 and contain floats.</p>
21
2009-05-10T11:05:59Z
38,861,127
<pre><code>a = map(lambda x, y: x + y, a, b) </code></pre>
0
2016-08-09T22:01:32Z
[ "python" ]
Converting a java System.currentTimeMillis() to date in python
845,153
<p>I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.</p> <p>How should I do that ?</p> <p>The following give <strong>ValueError: timestamp out of range for platform time_t</strong> on Linux 32bit</p> <pre><code>#!/usr/bin/env python from datetime import date print date.fromtimestamp(1241711346274) </code></pre> <p>Thank you, Maxim.</p>
6
2009-05-10T11:33:43Z
845,166
<p>It's in milliseconds divided the timestamp by 1000 to become in seconds.</p> <pre><code>date.fromtimestamp(1241711346274/1000) </code></pre>
1
2009-05-10T11:40:00Z
[ "java", "python", "date", "formatting", "timestamp" ]
Converting a java System.currentTimeMillis() to date in python
845,153
<p>I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.</p> <p>How should I do that ?</p> <p>The following give <strong>ValueError: timestamp out of range for platform time_t</strong> on Linux 32bit</p> <pre><code>#!/usr/bin/env python from datetime import date print date.fromtimestamp(1241711346274) </code></pre> <p>Thank you, Maxim.</p>
6
2009-05-10T11:33:43Z
845,167
<p>Python expects seconds, so divide it by 1000.0 first:</p> <pre><code>&gt;&gt;&gt; print date.fromtimestamp(1241711346274/1000.0) 2009-05-07 </code></pre>
15
2009-05-10T11:40:38Z
[ "java", "python", "date", "formatting", "timestamp" ]
Converting a java System.currentTimeMillis() to date in python
845,153
<p>I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.</p> <p>How should I do that ?</p> <p>The following give <strong>ValueError: timestamp out of range for platform time_t</strong> on Linux 32bit</p> <pre><code>#!/usr/bin/env python from datetime import date print date.fromtimestamp(1241711346274) </code></pre> <p>Thank you, Maxim.</p>
6
2009-05-10T11:33:43Z
845,303
<p>You can preserve the precision, because in Python the timestamp is a float. Here's an example:</p> <pre><code>import datetime java_timestamp = 1241959948938 seconds = java_timestamp / 1000 sub_seconds = (java_timestamp % 1000.0) / 1000.0 date = datetime.datetime.fromtimestamp(seconds + sub_seconds) </code></pre> <p>You can obviously make it more compact than that, but the above is suitable for typing, a line at a time, in the REPL, so see what it does. For example:</p> <pre><code>Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; java_timestamp = 1241959948938 &gt;&gt;&gt; import datetime &gt;&gt;&gt; seconds = java_timestamp / 1000 &gt;&gt;&gt; seconds 1241959948L &gt;&gt;&gt; sub_seconds = (java_timestamp % 1000.0) / 1000.0 &gt;&gt;&gt; sub_seconds 0.93799999999999994 &gt;&gt;&gt; date = datetime.datetime.fromtimestamp(seconds + sub_seconds) &gt;&gt;&gt; date datetime.datetime(2009, 5, 10, 8, 52, 28, 938000) &gt;&gt;&gt; </code></pre>
3
2009-05-10T13:07:12Z
[ "java", "python", "date", "formatting", "timestamp" ]
How to print the comparison of two multiline strings in unified diff format?
845,276
<p>Do you know any library that will help doing that?</p> <p>I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:</p> <pre><code>def print_differences(string1, string2): """ Prints the comparison of string1 to string2 as unified diff format. """ ??? </code></pre> <p>An usage example is the following:</p> <pre><code>string1=""" Usage: trash-empty [days] Purge trashed files. Options: --version show program's version number and exit -h, --help show this help message and exit """ string2=""" Usage: trash-empty [days] Empty the trash can. Options: --version show program's version number and exit -h, --help show this help message and exit Report bugs to http://code.google.com/p/trash-cli/issues """ print_differences(string1, string2) </code></pre> <p>This should print something like that:</p> <pre><code>--- string1 +++ string2 @@ -1,6 +1,6 @@ Usage: trash-empty [days] -Purge trashed files. +Empty the trash can. Options: --version show program's version number and exit </code></pre>
7
2009-05-10T12:51:12Z
845,284
<p>Did you have a look at the built-in python module <a href="http://docs.python.org/library/difflib.html">difflib</a>? Have a look that this <a href="http://docs.python.org/library/difflib.html#differ-example">example</a></p>
17
2009-05-10T12:54:51Z
[ "python", "diff", "unified-diff" ]
How to print the comparison of two multiline strings in unified diff format?
845,276
<p>Do you know any library that will help doing that?</p> <p>I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:</p> <pre><code>def print_differences(string1, string2): """ Prints the comparison of string1 to string2 as unified diff format. """ ??? </code></pre> <p>An usage example is the following:</p> <pre><code>string1=""" Usage: trash-empty [days] Purge trashed files. Options: --version show program's version number and exit -h, --help show this help message and exit """ string2=""" Usage: trash-empty [days] Empty the trash can. Options: --version show program's version number and exit -h, --help show this help message and exit Report bugs to http://code.google.com/p/trash-cli/issues """ print_differences(string1, string2) </code></pre> <p>This should print something like that:</p> <pre><code>--- string1 +++ string2 @@ -1,6 +1,6 @@ Usage: trash-empty [days] -Purge trashed files. +Empty the trash can. Options: --version show program's version number and exit </code></pre>
7
2009-05-10T12:51:12Z
845,432
<p>This is how I solved:</p> <pre><code>def _unidiff_output(expected, actual): """ Helper function. Returns a string containing the unified diff of two multiline strings. """ import difflib expected=expected.splitlines(1) actual=actual.splitlines(1) diff=difflib.unified_diff(expected, actual) return ''.join(diff) </code></pre>
11
2009-05-10T14:25:22Z
[ "python", "diff", "unified-diff" ]
Canonical/Idiomatic "do what I mean" when passed a string that could a filename, URL, or the actual data to work on
845,408
<p>It's not uncommon to see Python libraries that expose a universal "opener" function, that accept as their primary argument a string that could either represent a local filename (which it will open and operate on), a URL(which it will download and operate on), or data(which it will operate on).</p> <p>Here's <a href="http://code.google.com/p/feedparser/source/browse/trunk/feedparser/feedparser.py#2609" rel="nofollow">an example from Feedparser</a>.</p> <p>My question is: is there a standard "right" way to do that? Or, A module that implements that bit of functionality (maybe as a decorator)?</p>
2
2009-05-10T14:11:21Z
845,424
<p>Ultimately, any module implementing this behaviour is going to parse the string. And act according to the result. In feedparser for example they are parsing the url:</p> <pre><code>if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'): # do something with the url else: # This is a file path return open(url_file_stream_or_string) </code></pre> <p>Here is a nice decorator that will do this for you:</p> <pre><code>import urlparse, urllib def opener(fun): def wrapper(url): if urlparse.urlparse(url)[0] in ('http', 'https', 'ftp'): return fun(urllib.urlopen(url)) return fun(open(url)) return wrapper @opener def read(stream): return stream.read() read('myfile') read('http://www.wikipedia.org') </code></pre>
7
2009-05-10T14:18:51Z
[ "python" ]
using Python objects in C#
845,502
<p>Is there an easy way to call Python objects from C#, that is without any COM mess?</p>
4
2009-05-10T15:11:45Z
845,506
<p>Yes, by hosting IronPython.</p>
7
2009-05-10T15:14:10Z
[ "c#", "python", "ironpython" ]
using Python objects in C#
845,502
<p>Is there an easy way to call Python objects from C#, that is without any COM mess?</p>
4
2009-05-10T15:11:45Z
845,511
<p>In the current released version of C# there is no great way to achieve this without using some sort of bridge layer. You can host it IronPython to a degree but its hard to take advantage of the dynamic features of IronPython since C# is a very statically typed language</p> <p>If you're speaking of IronPython though, C# 4.0 will be able to interop with that seemlessly. C# 4.0 is introducing a new feature calldh dynamic which allows it to work with any language running on the DLR. </p> <pre><code>dynamic d = GetSomePythonObject(); d.SomeMethod(); </code></pre>
5
2009-05-10T15:16:31Z
[ "c#", "python", "ironpython" ]
using Python objects in C#
845,502
<p>Is there an easy way to call Python objects from C#, that is without any COM mess?</p>
4
2009-05-10T15:11:45Z
845,515
<p>You may take a look at this <a href="http://stackoverflow.com/questions/736443/ironpython-and-c-script-access-to-c-objects">post</a>.</p>
1
2009-05-10T15:18:24Z
[ "c#", "python", "ironpython" ]
using Python objects in C#
845,502
<p>Is there an easy way to call Python objects from C#, that is without any COM mess?</p>
4
2009-05-10T15:11:45Z
845,516
<p>I know of 3 ways:</p> <p>1) Use Iron Python, and your Python projects can interact freely with projects written in C#.</p> <p>2) Expose your Python functions to COM. You would do this if you need to use Python libraries that you don't want to or can't convert to Iron Python (EG, if you just have a DLL.) The "COM mess" is not really so bad, if your Python code and C# code are running on the same machine. This code from <a href="http://www.devshed.com/c/a/Python/Windows-Programming-in-Python-Creating-COM-Servers/3/" rel="nofollow">this tutorial</a> shows that it's not excessively ugly: </p> <pre><code>class PythonUtilities: _public_methods_ = [ 'SplitString' ] _reg_progid_ = "PythonDemos.Utilities" # NEVER copy the following ID # Use "print pythoncom.CreateGuid()" to make a new one. _reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}" def SplitString(self, val, item=None): import string if item != None: item = str(item) return string.split(str(val), item) # Add code so that when this script is run by # Python.exe, it self-registers. if __name__=='__main__': print "Registering COM server..." import win32com.server.register win32com.server.register.UseCommandLine(PythonUtilities) </code></pre> <p>3) Have C# and Python communicate through sockets. You would do this if you have code you can't convert to Iron Python and you need to access it remotely. This requires the most work because you need to marshall and unmarshall the arguments and return values from bytes or strings, but it is what one team of mine did when we needed to make C# talk to a remote Python process.</p>
4
2009-05-10T15:18:32Z
[ "c#", "python", "ironpython" ]
Background process in GAE
845,620
<p>I am developing a website using Google App Engine and Django 1.0 (app-engine-patch)</p> <p>A major part of my program has to run in the background and change local data and also post to a remote URL</p> <p>Can someone suggest an effective way of doing this?</p>
3
2009-05-10T16:37:19Z
845,624
<p>Without using a third-party system, I think currently your only option is to use the <a href="http://code.google.com/appengine/docs/python/config/cron.html" rel="nofollow">cron functionality</a>.</p> <p>You'd still be bound by the usual GAE script-execution-time limitations, but it wouldn't happen on a page load.</p> <p>There is plans for background processing, see <a href="http://code.google.com/p/googleappengine/issues/detail?id=6" rel="nofollow">this App Engine issue #6</a>, and this <a href="http://googleappengine.blogspot.com/2009/02/roadmap-update.html" rel="nofollow">roadmap update</a></p>
2
2009-05-10T16:41:32Z
[ "python", "django", "google-app-engine", "backgroundworker" ]
Background process in GAE
845,620
<p>I am developing a website using Google App Engine and Django 1.0 (app-engine-patch)</p> <p>A major part of my program has to run in the background and change local data and also post to a remote URL</p> <p>Can someone suggest an effective way of doing this?</p>
3
2009-05-10T16:37:19Z
845,684
<p>I second dbr's recommendation of <a href="http://code.google.com/appengine/docs/python/config/cron.html" rel="nofollow">http://code.google.com/appengine/docs/python/config/cron.html</a> (and hopes for better future approaches, such as the promised "task queues").</p> <p>Nevertheless I suspect that if you do indeed need <em>major</em> (as in <em>CPU heavy</em>) background processing, GAE may not be the most hospitable environment for that. You may want to consider running those heavy background tasks in other environments, and have them communicate with GAE proper e.g. via the "bulk load/download" APIs, see <a href="http://code.google.com/appengine/docs/python/tools/uploadingdata.html" rel="nofollow">http://code.google.com/appengine/docs/python/tools/uploadingdata.html</a> (and <a href="http://code.google.com/appengine/docs/python/tools/uploadingdata.html#Downloading_Data_from_App_Engine" rel="nofollow">http://code.google.com/appengine/docs/python/tools/uploadingdata.html#Downloading_Data_from_App_Engine</a> for the downloading part).</p> <p>Google's documentation only describes the usage of the command-line appcfg.py for these purposes (I can't find a proper documentation of the APIs it uses!), but, if you do need more programmatic usage of these APIs, it's not hard to evince them from appcfg.py's sources.</p>
2
2009-05-10T17:12:46Z
[ "python", "django", "google-app-engine", "backgroundworker" ]
Background process in GAE
845,620
<p>I am developing a website using Google App Engine and Django 1.0 (app-engine-patch)</p> <p>A major part of my program has to run in the background and change local data and also post to a remote URL</p> <p>Can someone suggest an effective way of doing this?</p>
3
2009-05-10T16:37:19Z
1,030,406
<p>Check out <a href="http://code.google.com/appengine/docs/python/taskqueue/" rel="nofollow">The Task Queue Python API</a>.</p>
5
2009-06-23T02:39:40Z
[ "python", "django", "google-app-engine", "backgroundworker" ]
Unable to make an iterable decimal function in Python
845,787
<p>I want to calculate the sum of </p> <pre><code>1/1 + 1/2 + 1/3 + ... + 1/30 </code></pre> <p>I run the code unsuccessfully</p> <pre><code>import decimal import math var=decimal.Decimal(1/i) for i in range(1,31): print(sum(var)) </code></pre> <p>I get the error</p> <pre><code>'Decimal' object is not iterable </code></pre> <p><strong>How can you make the iterable function in Python?</strong> </p>
0
2009-05-10T18:16:02Z
845,800
<p>What you want is this:</p> <pre><code>print(sum(decimal.Decimal(1) / i for i in range(1, 31))) </code></pre> <p>The reason your code doesn't work, is that you try to iterate over <em>one</em> <code>Decimal</code> instance (through the use of <code>sum</code>). Furthermore, your definition of <code>var</code> is invalid. Your intention was probably something like this:</p> <pre><code>var = lambda i: decimal.Decimal(str(1.0 / i)) </code></pre> <p>(Note the use of <code>str</code>, <code>Decimal</code> <a href="http://docs.python.org/3.0/library/decimal.html" rel="nofollow">does not permit</a> a floating point argument). But even then your loop would not work, because the use of <code>sum</code> <em>inside</em> the loop is inherently flawed. <code>sum</code> should be used <em>after</em> the loop has created all fractions that you want to sum. So that would be either of:</p> <pre><code>print(sum(var(i) for i in range(1,31))) print(sum(map(var, range(1, 31)))) </code></pre> <p>For completeness, yet another way to do this is the following:</p> <pre><code>one = decimal.Decimal(1) unitFractions = (one / i for i in itertools.count(1)) print(sum(itertools.islice(unitFractions, 30))) </code></pre> <p>However, as mentioned by <a href="http://stackoverflow.com/questions/845787/unable-to-make-an-iterable-decimal-function-in-python/845826#845826">gs</a>, the <a href="http://docs.python.org/library/fractions.html" rel="nofollow">fractions</a> provides an alternative method that yields a fractional answer:</p> <pre><code>&gt;&gt;&gt; unitFractions = (fractions.Fraction(1, i) for i in itertools.count(1)) &gt;&gt;&gt; print(sum(itertools.islice(unitFractions, 30))) 9304682830147/2329089562800 </code></pre>
11
2009-05-10T18:19:59Z
[ "python", "iteration", "sum" ]
Unable to make an iterable decimal function in Python
845,787
<p>I want to calculate the sum of </p> <pre><code>1/1 + 1/2 + 1/3 + ... + 1/30 </code></pre> <p>I run the code unsuccessfully</p> <pre><code>import decimal import math var=decimal.Decimal(1/i) for i in range(1,31): print(sum(var)) </code></pre> <p>I get the error</p> <pre><code>'Decimal' object is not iterable </code></pre> <p><strong>How can you make the iterable function in Python?</strong> </p>
0
2009-05-10T18:16:02Z
845,807
<p>You write:</p> <pre><code>var=decimal.Decimal(1/i) </code></pre> <p>which is weird since 'i' is not defined at that point. How about:</p> <pre><code>one = decimal.Decimal( "1" ) total = decimal.Decimal( "0" ) for i in range( 1, 31 ): total += one / decimal.Decimal( "%d" % i ) </code></pre>
3
2009-05-10T18:22:50Z
[ "python", "iteration", "sum" ]
Unable to make an iterable decimal function in Python
845,787
<p>I want to calculate the sum of </p> <pre><code>1/1 + 1/2 + 1/3 + ... + 1/30 </code></pre> <p>I run the code unsuccessfully</p> <pre><code>import decimal import math var=decimal.Decimal(1/i) for i in range(1,31): print(sum(var)) </code></pre> <p>I get the error</p> <pre><code>'Decimal' object is not iterable </code></pre> <p><strong>How can you make the iterable function in Python?</strong> </p>
0
2009-05-10T18:16:02Z
845,826
<p>Your mistake is, that <code>decimal.Decimal(4)</code> isn't a function, but an object.</p> <p><hr /></p> <p>BTW: It looks like the <a href="http://docs.python.org/library/fractions.html" rel="nofollow">Fractions</a> (Python 2.6) module is what you really need.</p>
2
2009-05-10T18:31:57Z
[ "python", "iteration", "sum" ]
Unit tests for automatically generated code: automatic or manual?
845,887
<p>I know <a href="http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python">similar questions</a> have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.</p> <p>I've written a module in Python which contains objects representing physical constants and units of measurement. A lot of the units are formed by adding on prefixes to base units - e.g. from <code>m</code> I get <code>cm</code>, <code>dm</code>, <code>mm</code>, <code>hm</code>, <code>um</code>, <code>nm</code>, <code>pm</code>, etc. And the same for <code>s</code>, <code>g</code>, <code>C</code>, etc. Of course I've written a function to do this since the end result is over 1000 individual units and it would be a major pain to write them all out by hand ;-) It works something like this (not the actual code):</p> <pre><code>def add_unit(name, value): globals()[name] = value for pfx, multiplier in prefixes: globals()[pfx + name] = multiplier * value add_unit('m', &lt;definition of a meter&gt;) add_unit('g', &lt;definition of a gram&gt;) add_unit('s', &lt;definition of a second&gt;) # etc. </code></pre> <p>The problem comes in when I want to write unit tests for these units (no pun intended), to make sure they all have the right values. If I write code that automatically generates a test case for every unit individually, any problems that are in the unit generation function are likely to also show up in the test generation function. But given the alternative (writing out all 1000+ tests by hand), should I just go ahead and write a test generation function anyway, check it really carefully and hope it works properly? Or should I only test, say, one series of units (<code>m</code>, <code>cm</code>, <code>dm</code>, <code>km</code>, <code>nm</code>, <code>um</code>, and all other multiples of the meter), just enough to make sure the unit generation function seems to be working? Or something else?</p>
2
2009-05-10T19:06:44Z
845,907
<p>If you auto-generate the tests:</p> <ul> <li><p>You might find it faster to then read all the tests (to inspect them for correctness) that it would have been to write them all by hand.</p></li> <li><p>They might also be more maintainable (easier to edit, if you want to edit them later).</p></li> </ul>
1
2009-05-10T19:16:39Z
[ "python", "unit-testing", "code-generation" ]
Unit tests for automatically generated code: automatic or manual?
845,887
<p>I know <a href="http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python">similar questions</a> have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.</p> <p>I've written a module in Python which contains objects representing physical constants and units of measurement. A lot of the units are formed by adding on prefixes to base units - e.g. from <code>m</code> I get <code>cm</code>, <code>dm</code>, <code>mm</code>, <code>hm</code>, <code>um</code>, <code>nm</code>, <code>pm</code>, etc. And the same for <code>s</code>, <code>g</code>, <code>C</code>, etc. Of course I've written a function to do this since the end result is over 1000 individual units and it would be a major pain to write them all out by hand ;-) It works something like this (not the actual code):</p> <pre><code>def add_unit(name, value): globals()[name] = value for pfx, multiplier in prefixes: globals()[pfx + name] = multiplier * value add_unit('m', &lt;definition of a meter&gt;) add_unit('g', &lt;definition of a gram&gt;) add_unit('s', &lt;definition of a second&gt;) # etc. </code></pre> <p>The problem comes in when I want to write unit tests for these units (no pun intended), to make sure they all have the right values. If I write code that automatically generates a test case for every unit individually, any problems that are in the unit generation function are likely to also show up in the test generation function. But given the alternative (writing out all 1000+ tests by hand), should I just go ahead and write a test generation function anyway, check it really carefully and hope it works properly? Or should I only test, say, one series of units (<code>m</code>, <code>cm</code>, <code>dm</code>, <code>km</code>, <code>nm</code>, <code>um</code>, and all other multiples of the meter), just enough to make sure the unit generation function seems to be working? Or something else?</p>
2
2009-05-10T19:06:44Z
845,908
<p>You're right to identify the weakness of automatically generating test cases. The usefulness of a test comes from taking two different paths (your code, and your own mental reasoning) to come up with what should be the same answer -- if you use the same path both times, nothing is being tested.</p> <p>In summary: <strong>Never write automatically generated tests</strong>, unless the algorithm for generating the test results is dramatically simpler than the algorithm that you are testing. (Testing of a sorting algorithm is an example of when automatically generated tests would be a good idea, since it's easy to verify that a list of numbers is in sorted order. Another good example would be a puzzle-solving program <a href="http://stackoverflow.com/questions/845887/unit-tests-for-automatically-generated-code-automatic-or-manual/845907#845907">as suggested by ChrisW</a> in a comment. In both cases, auto-generation makes sense because it is much easier to verify that a given solution is correct than to generate a correct solution.)</p> <p><strong>My suggestion for your case:</strong> Manually test a small, representative subset of the possibilities.</p> <p>[Clarification: Certain types of automated tests are appropriate and highly useful, e.g. <a href="http://en.wikipedia.org/wiki/Fuzz%5Ftesting" rel="nofollow">fuzzing</a>. I mean that that it is unhelpful to auto-generate unit tests for generated code.]</p>
1
2009-05-10T19:17:28Z
[ "python", "unit-testing", "code-generation" ]
Unit tests for automatically generated code: automatic or manual?
845,887
<p>I know <a href="http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python">similar questions</a> have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.</p> <p>I've written a module in Python which contains objects representing physical constants and units of measurement. A lot of the units are formed by adding on prefixes to base units - e.g. from <code>m</code> I get <code>cm</code>, <code>dm</code>, <code>mm</code>, <code>hm</code>, <code>um</code>, <code>nm</code>, <code>pm</code>, etc. And the same for <code>s</code>, <code>g</code>, <code>C</code>, etc. Of course I've written a function to do this since the end result is over 1000 individual units and it would be a major pain to write them all out by hand ;-) It works something like this (not the actual code):</p> <pre><code>def add_unit(name, value): globals()[name] = value for pfx, multiplier in prefixes: globals()[pfx + name] = multiplier * value add_unit('m', &lt;definition of a meter&gt;) add_unit('g', &lt;definition of a gram&gt;) add_unit('s', &lt;definition of a second&gt;) # etc. </code></pre> <p>The problem comes in when I want to write unit tests for these units (no pun intended), to make sure they all have the right values. If I write code that automatically generates a test case for every unit individually, any problems that are in the unit generation function are likely to also show up in the test generation function. But given the alternative (writing out all 1000+ tests by hand), should I just go ahead and write a test generation function anyway, check it really carefully and hope it works properly? Or should I only test, say, one series of units (<code>m</code>, <code>cm</code>, <code>dm</code>, <code>km</code>, <code>nm</code>, <code>um</code>, and all other multiples of the meter), just enough to make sure the unit generation function seems to be working? Or something else?</p>
2
2009-05-10T19:06:44Z
845,962
<p>I would say the best approach is to unit test the generation, and as part of the unit test, you might take a sample generated result (only enough to where the test tests something that you would consider significantly different over the other scenarios) and put that under a unit test to make sure that the generation is working correctly. Beyond that, there is little unit test value in defining every scenario in an automated way. There may be functional test value in putting together some functional test which exercise the generated code to perform whatever purpose you have in mind, in order to give wider coverage to the various potential units.</p>
1
2009-05-10T19:36:04Z
[ "python", "unit-testing", "code-generation" ]
Unit tests for automatically generated code: automatic or manual?
845,887
<p>I know <a href="http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python">similar questions</a> have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.</p> <p>I've written a module in Python which contains objects representing physical constants and units of measurement. A lot of the units are formed by adding on prefixes to base units - e.g. from <code>m</code> I get <code>cm</code>, <code>dm</code>, <code>mm</code>, <code>hm</code>, <code>um</code>, <code>nm</code>, <code>pm</code>, etc. And the same for <code>s</code>, <code>g</code>, <code>C</code>, etc. Of course I've written a function to do this since the end result is over 1000 individual units and it would be a major pain to write them all out by hand ;-) It works something like this (not the actual code):</p> <pre><code>def add_unit(name, value): globals()[name] = value for pfx, multiplier in prefixes: globals()[pfx + name] = multiplier * value add_unit('m', &lt;definition of a meter&gt;) add_unit('g', &lt;definition of a gram&gt;) add_unit('s', &lt;definition of a second&gt;) # etc. </code></pre> <p>The problem comes in when I want to write unit tests for these units (no pun intended), to make sure they all have the right values. If I write code that automatically generates a test case for every unit individually, any problems that are in the unit generation function are likely to also show up in the test generation function. But given the alternative (writing out all 1000+ tests by hand), should I just go ahead and write a test generation function anyway, check it really carefully and hope it works properly? Or should I only test, say, one series of units (<code>m</code>, <code>cm</code>, <code>dm</code>, <code>km</code>, <code>nm</code>, <code>um</code>, and all other multiples of the meter), just enough to make sure the unit generation function seems to be working? Or something else?</p>
2
2009-05-10T19:06:44Z
846,171
<p>Write only just enough tests to make sure that your code generation works right (just enough to drive the design of the imperative code). Declarative code rarely breaks. You should only test things that can break. Mistakes in declarative code (such as your case and for example user interface layouts) are better found with exploratory testing, so writing extensive automated tests for them is waste of time.</p>
1
2009-05-10T21:38:31Z
[ "python", "unit-testing", "code-generation" ]
Rename invalid filename in XP via Python
845,926
<p>My problem is similar to <a href="http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames">http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames</a></p> <p>however, I don't know the original encoding of the filename I need to rename (unlike the other post he knew it was Hebrew originally).</p> <p>I was doing data recovery for a client and copied over the files to my XP SP3 machine, and some of the file names have "?" replacing/representing invalid characters.</p> <p>I tried to use Python to <code>os.rename</code> the files since I know it has unicode support, however, when I tell python to rename the files, it seems it's unable to pass a valid file name back to the windows API.</p> <p>i.e.:</p> <pre><code>&gt;&gt;&gt; os.chdir(r'F:\recovery\My Music') &gt;&gt;&gt; os.listdir(u'.') [u'Don?t Be Them.mp3', u'That?s A Soldier.mp3'] &gt;&gt;&gt; blah=os.listdir(u'.') &gt;&gt;&gt; blah[0] Don?t Be Them.mp3 &gt;&gt;&gt; os.rename(blah[0],'dont be them.mp3') Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; os.rename(blah[0],'dont be them.mp3') WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect </code></pre> <p>I'm using Python 2.6, on Win XP SP3, with whatever encoding is standard XP behavior for US/English.</p> <p>Is there a way to handle these renames without knowing the original language?</p>
4
2009-05-10T19:22:09Z
847,793
<p>Try passing a unicode string:</p> <pre><code>os.rename(blah[0], u'dont be them.mp3') </code></pre>
0
2009-05-11T12:04:20Z
[ "python", "unicode", "windows-xp" ]
Rename invalid filename in XP via Python
845,926
<p>My problem is similar to <a href="http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames">http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames</a></p> <p>however, I don't know the original encoding of the filename I need to rename (unlike the other post he knew it was Hebrew originally).</p> <p>I was doing data recovery for a client and copied over the files to my XP SP3 machine, and some of the file names have "?" replacing/representing invalid characters.</p> <p>I tried to use Python to <code>os.rename</code> the files since I know it has unicode support, however, when I tell python to rename the files, it seems it's unable to pass a valid file name back to the windows API.</p> <p>i.e.:</p> <pre><code>&gt;&gt;&gt; os.chdir(r'F:\recovery\My Music') &gt;&gt;&gt; os.listdir(u'.') [u'Don?t Be Them.mp3', u'That?s A Soldier.mp3'] &gt;&gt;&gt; blah=os.listdir(u'.') &gt;&gt;&gt; blah[0] Don?t Be Them.mp3 &gt;&gt;&gt; os.rename(blah[0],'dont be them.mp3') Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; os.rename(blah[0],'dont be them.mp3') WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect </code></pre> <p>I'm using Python 2.6, on Win XP SP3, with whatever encoding is standard XP behavior for US/English.</p> <p>Is there a way to handle these renames without knowing the original language?</p>
4
2009-05-10T19:22:09Z
848,611
<p><strong>'?'</strong> is not valid character for filenames. That is the reason while your approach failed. You may try to use DOS short filenames:</p> <pre><code>import win32api filelist = win32api.FindFiles(r'F:/recovery/My Music/*.*') # this will extract "short names" from WIN32_FIND_DATA structure filelist = [i[9] if i[9] else i[8] for i in filelist] # EXAMPLE: # this should rename all files in 'filelist' to 1.mp3, 2.mp3, 3.mp3, ... for (number, filename) in enumerate(filelist): os.rename(filaname, '%d.mp3' % (number)) </code></pre>
2
2009-05-11T15:21:55Z
[ "python", "unicode", "windows-xp" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like <a href="http://img512.imageshack.us/my.php?image=46854652.png">this</a>.</p> <p>At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?</p>
15
2009-05-10T19:38:22Z
845,984
<p>We follow the following principles when designing classes:</p> <ul> <li><a href="http://www.google.co.za/url?sa=t&amp;source=web&amp;ct=res&amp;cd=2&amp;url=http%3A%2F%2Fwww.objectmentor.com%2Fresources%2Farticles%2Fsrp.pdf&amp;ei=1C4HSu3uEODJtgfs8uWeBw&amp;usg=AFQjCNHQQ1Aw-2yCciEbERpJn3VdHBCmQw&amp;sig2=Pf7Z4GNwRnAiaar%5FyCk%5Fdg">The Single Responsibility Principle</a>: A class (or method) should have only one reason to change.</li> <li><a href="http://www.google.co.za/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fwww.objectmentor.com%2Fresources%2Farticles%2Focp.pdf&amp;ei=9i4HStWBH5XhtgfSltWNBw&amp;usg=AFQjCNGzBuNcaA1IXUx0tijZoTW7rlzcRQ&amp;sig2=K-zyAaPRTp0CG28mtuO9jg">The Open Closed Principle</a>: A class (or method) should be open for extension and closed for modification.</li> <li><a href="http://www.google.co.za/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fwww.objectmentor.com%2Fresources%2Farticles%2Flsp.pdf&amp;ei=By8HSoDJJd6ptger2uSdBw&amp;usg=AFQjCNFnNI0DmzofjWDQEGILAT-W1L8Mtw&amp;sig2=ozd86zYF9ZMqLfBS2tQJdg">The Liskov Substitution Principle</a>: Subtypes must be substitutable for their base types.</li> <li><a href="http://www.google.co.za/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fwww.objectmentor.com%2Fresources%2Farticles%2Fisp.pdf&amp;ei=Gy8HSpH-CqK%5Ftwfv6OCXBw&amp;usg=AFQjCNHuKx3fPObvzYaQDZ2etcZHYtg57g&amp;sig2=aWFqTuyl%5FiCAsGk8SnwljQ">The Interface Segregation Principle</a>: Clients should not be forced to depend upon methods that they do not use. Interfaces should belong to clients.</li> <li><a href="http://www.google.co.za/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fwww.objectmentor.com%2Fresources%2Farticles%2Fdip.pdf&amp;ei=Mi8HSsbyLdKJtgemroCfBw&amp;usg=AFQjCNEpBGziZw6APHj0rMG9pp1LJt9FHA&amp;sig2=y4EFfBIw-cC6hocfVEeTJg">The Dependency Inversion Principle</a>: Abstractions should not depend on details. Details should depend on abstractions.</li> </ul> <p>Edit: Design patterns are helpful in getting your code to comply with these principles. I have found it very helpful to understand the principles first and then to look at the patterns and understand how the patterns bring your code in line with the principles.</p>
28
2009-05-10T19:47:10Z
[ "python", "language-agnostic", "oop" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like <a href="http://img512.imageshack.us/my.php?image=46854652.png">this</a>.</p> <p>At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?</p>
15
2009-05-10T19:38:22Z
845,986
<p>It's often not possible to say whats 'correct' or 'wrong' when it comes to class design. There are many guidelines, patterns, recommendation etc. about this topic, but at the end of the day, imho, it's a lot about experience with past projects. My experience is that it's best to not worry to much about it, and gradually improve your code/structure in small steps. Experiment and see how some ideas/changes feel/look like. And it's of course always a good idea to learn from others. read a lot of code and analyse it, try to understand :). </p> <p>If you wanna read about the theory I can recommend Craig Larmanns 'Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development' <a href="http://rads.stackoverflow.com/amzn/click/0131489062" rel="nofollow">Amazon</a>. He covers several parts of your question, gives some rough guidlines and shows them using an example application. I liked the book. </p> <p>Could you upload your app somewhere? Perhaps on github or so, perhaps you could ask for some concrete advices.</p>
3
2009-05-10T19:48:30Z
[ "python", "language-agnostic", "oop" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like <a href="http://img512.imageshack.us/my.php?image=46854652.png">this</a>.</p> <p>At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?</p>
15
2009-05-10T19:38:22Z
845,988
<p><a href="http://en.wikipedia.org/wiki/Design%5Fpattern%5F%28computer%5Fscience%29" rel="nofollow">Design Patterns</a> has become the defacto standard for good class design. Generally, each pattern has a particular use case, or scenario, which it applies to. If you can identify this in your code, you can use the pattern to create something that makes more sense, and usually has less dependencies.</p> <p>Refactoring is the tool that you would use to accomplish these sweeping changes. A good IDE will help you to refactor.</p>
1
2009-05-10T19:49:04Z
[ "python", "language-agnostic", "oop" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like <a href="http://img512.imageshack.us/my.php?image=46854652.png">this</a>.</p> <p>At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?</p>
15
2009-05-10T19:38:22Z
845,991
<p>Try making each method easily unit-testable. I find this always drives my designs towards more readability/understandability. There are numerous OOAD rules -- <a href="http://stackoverflow.com/questions/399656/are-there-any-rules-for-oop">SRP, DRY, etc.</a> Try to keep those in mind as you refactor.</p>
0
2009-05-10T19:52:05Z
[ "python", "language-agnostic", "oop" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My script generated an input file for graphviz, which was used to generate a dependency graph that looks like <a href="http://img512.imageshack.us/my.php?image=46854652.png">this</a>.</p> <p>At this point I've got stuck. I've realized that I have no idea how to refactor the class to make it less complicated. I simply don't know what should I aim to. For example, in theory of relational databases there are a couple of simple rules that are used to bring a database to a normal form. What about some similar theory concerning the good class design (in terms of dependencies between its methods)? Is this topic covered somewhere so I could study it?</p>
15
2009-05-10T19:38:22Z
848,671
<p>I recommend the book "Refactoring" by Martin Fowler for tons of practical examples of iteratively converting poor design to good design.</p>
0
2009-05-11T15:34:06Z
[ "python", "language-agnostic", "oop" ]
How do I represent a void pointer in a PyObjC selector?
845,970
<p>I'm wanting to use an NSOpenPanel for an application I'm designing. Here's what I have so far:</p> <pre><code>@objc.IBAction def ShowOpenPanel_(self, sender): self.panel = NSOpenPanel.openPanel() self.panel.setCanChooseFiles_(False) self.panel.setCanChooseDirectories_(True) NSLog(u'Starting OpenPanel') self.panel.beginForDirectory_file_types_modelessDelegate_didEndSelector_contextInfo_( self.defaults.objectForKey_(u'projpath'), objc.nil, objc.nil, self, objc.selector(self.OpenPanelDidEnd_returnCode_contextInfo_, signature='v:@ii'), objc.nil) NSLog(u'OpenPanel was started.') def OpenPanelDidEnd_returnCode_contextInfo_(self, panel, returnCode, context): NSLog('Panel ended.') if (returnCode == NSOKButton): NSLog(u'User selected OK') path = self.panel.filenames()[0] self.defaults.setObject_forKey_(path, u'projpath') del self.panel </code></pre> <p>The main two lines I'm concerned about are:</p> <pre><code> objc.selector(self.OpenPanelDidEnd_returnCode_contextInfo_, signature='v:@ii'), objc.nil) #this is the argument that gets passed as the void pointer </code></pre> <p>The third argument is supposed to be a void pointer. Since I don't intend to use that data, I'd rather just leave it empty. I've tried making the signature <code>'v:@iv'</code> and tried using <code>objc.NULL</code> and python's <code>None</code>, and just about every combination of all these things. What is the best way to handle this?</p>
3
2009-05-10T19:39:38Z
872,792
<p>I think you don't need to use <code>objc.selector</code> at all; try this instead:</p> <pre><code>@objc.IBAction def ShowOpenPanel_(self, sender): self.panel = NSOpenPanel.openPanel() self.panel.setCanChooseFiles_(False) self.panel.setCanChooseDirectories_(True) NSLog(u'Starting OpenPanel') self.panel.beginForDirectory_file_types_modelessDelegate_didEndSelector_contextInfo_( self.defaults.objectForKey_(u'projpath'), objc.nil, objc.nil, self, self.OpenPanelDidEnd_returnCode_contextInfo_, objc.nil) NSLog(u'OpenPanel was started.') </code></pre> <p>I've also found that I need to decorate the end-of-panel function with <code>PyObjCTools.AppHelper.endSheetMethod</code>:</p> <pre><code>@PyObjCTools.AppHelper.endSheetMethod def OpenPanelDidEnd_returnCode_contextInfo_(self, panel, returnCode, context): NSLog('Panel ended.') if (returnCode == NSOKButton): NSLog(u'User selected OK') path = self.panel.filenames()[0] self.defaults.setObject_forKey_(path, u'projpath') del self.panel </code></pre> <p>Here's how I would write what you have:</p> <pre><code>@objc.IBAction def showOpenPanel_(self, sender): panel = NSOpenPanel.openPanel() panel.setCanChooseFiles_(False) panel.setCanChooseDirectories_(True) NSLog(u'Starting openPanel') panel.beginForDirectory_file_types_modelessDelegate_didEndSelector_contextInfo_( self.defaults.objectForKey_(u'projpath'), #forDirectory None, #file None, #types self, #modelessDelegate self.openPanelDidEnd_returnCode_contextInfo_, #didEndSelector None) #contextInfo NSLog(u'openPanel started') @PyObjCTools.AppHelper.endSheetMethod def openPanelDidEnd_returnCode_contextInfo_(self, panel, returnCode, context): NSLog(u'Panel ended') if returnCode != NSOKButton: return NSLog(u'User selected OK') path = panel.filenames()[0] self.defaults.setObject_forKey_(path, u'projpath') </code></pre> <p>Explanation of changes: I always use <code>None</code> rather than <code>objc.nil</code> and it hasn't messed me up yet; I don't think your panel needs to be a property of <code>self</code> since you get it in your return function; objc convention is to have the first letter of your function in lower case.</p>
1
2009-05-16T16:50:17Z
[ "python", "objective-c", "osx", "pyobjc", "void-pointers" ]
How do I represent a void pointer in a PyObjC selector?
845,970
<p>I'm wanting to use an NSOpenPanel for an application I'm designing. Here's what I have so far:</p> <pre><code>@objc.IBAction def ShowOpenPanel_(self, sender): self.panel = NSOpenPanel.openPanel() self.panel.setCanChooseFiles_(False) self.panel.setCanChooseDirectories_(True) NSLog(u'Starting OpenPanel') self.panel.beginForDirectory_file_types_modelessDelegate_didEndSelector_contextInfo_( self.defaults.objectForKey_(u'projpath'), objc.nil, objc.nil, self, objc.selector(self.OpenPanelDidEnd_returnCode_contextInfo_, signature='v:@ii'), objc.nil) NSLog(u'OpenPanel was started.') def OpenPanelDidEnd_returnCode_contextInfo_(self, panel, returnCode, context): NSLog('Panel ended.') if (returnCode == NSOKButton): NSLog(u'User selected OK') path = self.panel.filenames()[0] self.defaults.setObject_forKey_(path, u'projpath') del self.panel </code></pre> <p>The main two lines I'm concerned about are:</p> <pre><code> objc.selector(self.OpenPanelDidEnd_returnCode_contextInfo_, signature='v:@ii'), objc.nil) #this is the argument that gets passed as the void pointer </code></pre> <p>The third argument is supposed to be a void pointer. Since I don't intend to use that data, I'd rather just leave it empty. I've tried making the signature <code>'v:@iv'</code> and tried using <code>objc.NULL</code> and python's <code>None</code>, and just about every combination of all these things. What is the best way to handle this?</p>
3
2009-05-10T19:39:38Z
903,319
<p>The right way to open the panel is:</p> <pre><code>@objc.IBAction def showOpenPanel_(self, sender): panel = NSOpenPanel.openPanel() panel.setCanChooseFiles_(False) panel.setCanChooseDirectories_(True) NSLog(u'Starting openPanel') panel.beginForDirectory_file_types_modelessDelegate_didEndSelector_contextInfo_( self.defaults.objectForKey_(u'projpath'), #forDirectory None, #file None, #types self, #modelessDelegate 'openPanelDidEnd:returnCode:contextInfo:', #didEndSelector None) #contextInfo NSLog(u'openPanel started') </code></pre> <p>Dan's code works as well, but IMHO my variant is slighly clearer: you don't pass the actual method but the name of the method that should be called.</p>
1
2009-05-24T08:16:35Z
[ "python", "objective-c", "osx", "pyobjc", "void-pointers" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 (base-10) digits.</p> <p>How do I do this? </p>
41
2009-05-10T20:24:01Z
846,045
<p>You can use the <a href="http://docs.python.org/library/struct.html">struct</a> module:</p> <pre><code>import struct print struct.pack('&gt;I', your_int) </code></pre> <p><code>'&gt;I'</code> is a format string. <code>&gt;</code> means big endian and <code>I</code> means unsigned int. Check the documentation for more format chars.</p>
32
2009-05-10T20:27:59Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 (base-10) digits.</p> <p>How do I do this? </p>
41
2009-05-10T20:24:01Z
846,063
<p>Probably the best way is via the built-in <a href="http://docs.python.org/library/struct.html">struct module</a>:</p> <pre><code>&gt;&gt;&gt; import struct &gt;&gt;&gt; x = 1245427 &gt;&gt;&gt; struct.pack('&gt;BH', x &gt;&gt; 16, x &amp; 0xFFFF) '\x13\x00\xf3' &gt;&gt;&gt; struct.pack('&gt;L', x)[1:] # could do it this way too '\x13\x00\xf3' </code></pre> <p>Alternatively -- and I wouldn't usually recommend this, because it's mistake-prone -- you can do it "manually" by shifting and the <code>chr()</code> function:</p> <pre><code>&gt;&gt;&gt; x = 1245427 &gt;&gt;&gt; chr((x &gt;&gt; 16) &amp; 0xFF) + chr((x &gt;&gt; 8) &amp; 0xFF) + chr(x &amp; 0xFF) '\x13\x00\xf3' </code></pre> <p>Out of curiosity, why do you only want three bytes? Usually you'd pack such an integer into a full 32 bits (a C <code>unsigned long</code>), and use <code>struct.pack('&gt;L', 1245427)</code> but skip the <code>[1:]</code> step?</p>
7
2009-05-10T20:42:47Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 (base-10) digits.</p> <p>How do I do this? </p>
41
2009-05-10T20:24:01Z
846,064
<pre><code>def tost(i): result = [] while i: result.append(chr(i&amp;0xFF)) i &gt;&gt;= 8 result.reverse() return ''.join(result) </code></pre>
4
2009-05-10T20:43:23Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 (base-10) digits.</p> <p>How do I do this? </p>
41
2009-05-10T20:24:01Z
846,067
<p>This is fast and works for small and (arbitrary) large ints:</p> <pre><code>def Dump(n): s = '%x' % n if len(s) &amp; 1: s = '0' + s return s.decode('hex') print repr(Dump(1245427)) #: '\x13\x00\xf3' </code></pre>
12
2009-05-10T20:44:32Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 (base-10) digits.</p> <p>How do I do this? </p>
41
2009-05-10T20:24:01Z
1,776,698
<p>Using the <a href="http://code.google.com/p/python-bitstring/" rel="nofollow">bitstring</a> module:</p> <pre><code>&gt;&gt;&gt; bitstring.BitArray(uint=1245427, length=24).bytes '\x13\x00\xf3' </code></pre> <p>Note though that for this method you need to specify the length in bits of the bitstring you are creating.</p> <p>Internally this is pretty much the same as Alex's answer, but the module has a lot of extra functionality available if you want to do more with your data.</p>
3
2009-11-21T20:37:12Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 (base-10) digits.</p> <p>How do I do this? </p>
41
2009-05-10T20:24:01Z
9,356,262
<p>The shortest way, I think, is the following:</p> <pre><code>import struct val = 0x11223344 val = struct.unpack("&lt;I", struct.pack("&gt;I", val))[0] print "%08x" % val </code></pre> <p>This converts an integer to a byte-swapped integer.</p>
3
2012-02-20T04:39:56Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 (base-10) digits.</p> <p>How do I do this? </p>
41
2009-05-10T20:24:01Z
12,859,903
<p>In Python 3.2+, you can use <a href="http://docs.python.org/py3k/library/stdtypes.html#int.to_bytes">int.to_bytes</a>:</p> <h2>If you don't want to specify the size</h2> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; n = 1245427 &gt;&gt;&gt; n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0' b'\x13\x00\xf3' </code></pre> <h2>If you don't mind specifying the size</h2> <pre><code>&gt;&gt;&gt; (1245427).to_bytes(3, byteorder='big') b'\x13\x00\xf3' </code></pre>
23
2012-10-12T13:15:51Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 (base-10) digits.</p> <p>How do I do this? </p>
41
2009-05-10T20:24:01Z
28,524,760
<p>Single-source Python 2/3 compatible version based on <a href="http://stackoverflow.com/a/846067/4279">@pts' answer</a>:</p> <pre><code>#!/usr/bin/env python import binascii def int2bytes(i): hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n &amp; 1))) print(int2bytes(1245427)) # -&gt; b'\x13\x00\xf3' </code></pre>
5
2015-02-15T09:33:07Z
[ "python" ]
What's the quickest way for a Ruby programmer to pick up Python?
846,139
<p>I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical language, or should I just "Dive into Python"?</p> <p>Thanks!</p>
10
2009-05-10T21:25:18Z
846,151
<p>A safe bet is to just dive into python (skim through some tutorials that explain the syntax), and then get coding. The best way to learn any new language is to write code, <a href="http://projecteuler.net/index.php?section=problems">lots of it</a>. Your experience in Ruby will make it easy to pick up python's dynamic concepts (which might be harder to get used to for say a Java programmer).</p> <p>Try a <a href="http://docs.python.org/tutorial/">python tutorial</a> or <a href="http://www.diveintopython.org/">book on learning python</a>.</p>
9
2009-05-10T21:30:45Z
[ "python", "ruby" ]
What's the quickest way for a Ruby programmer to pick up Python?
846,139
<p>I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical language, or should I just "Dive into Python"?</p> <p>Thanks!</p>
10
2009-05-10T21:25:18Z
846,152
<p>I started learning from the <a href="http://docs.python.org/tutorial/" rel="nofollow">python tutorial</a>. It is well written and easy to follow. Then I started to solve problems in <a href="http://www.pythonchallenge.com/" rel="nofollow">python challenge</a>. It was a really fun way to start :) </p>
2
2009-05-10T21:31:11Z
[ "python", "ruby" ]
What's the quickest way for a Ruby programmer to pick up Python?
846,139
<p>I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical language, or should I just "Dive into Python"?</p> <p>Thanks!</p>
10
2009-05-10T21:25:18Z
846,154
<p>I suggest just diving into Python, it's similar to Ruby so you should have no problems:</p> <p><a href="http://www.diveintopython.net/" rel="nofollow">http://www.diveintopython.net/</a></p>
3
2009-05-10T21:31:38Z
[ "python", "ruby" ]