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 |
---|---|---|---|---|---|---|---|---|---|
What are the benefits of using Python for web programming?
| 452,305 |
<p>What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web?</p>
| 9 |
2009-01-16T22:38:56Z
| 27,014,289 |
<p>Furthermore, </p>
<p>Python is both strong in web and in data analytics and machine learning. For example scikit, sci-py and numpy are very strong. In some cases, it can be very interesting to have the both elements on the same server.</p>
<p>For example <a href="http://rankmytweet.com" rel="nofollow">http://rankmytweet.com</a> uses this a lot.</p>
| 2 |
2014-11-19T10:18:39Z
|
[
"python",
"programming-languages"
] |
How can I test that I have a Python module successfully installed?
| 452,430 |
<p>I tried to install beautifulsoup. I get such an error:<br>
<-- snip --></p>
<pre><code>raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /Users/Sam/.pydistutils.cfg, line: 1
'install_lib = ~/Library/Python/$py_version_short/site-packages\n'
</code></pre>
<p>I get an similar error as I run my Python code in vim by:
:!python %</p>
| 2 |
2009-01-16T23:36:04Z
| 452,438 |
<p>You can test if a module is installed like so:</p>
<pre><code>$ python
>>> import modulename
</code></pre>
| 6 |
2009-01-16T23:40:46Z
|
[
"python",
"installation",
"module"
] |
How can I test that I have a Python module successfully installed?
| 452,430 |
<p>I tried to install beautifulsoup. I get such an error:<br>
<-- snip --></p>
<pre><code>raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /Users/Sam/.pydistutils.cfg, line: 1
'install_lib = ~/Library/Python/$py_version_short/site-packages\n'
</code></pre>
<p>I get an similar error as I run my Python code in vim by:
:!python %</p>
| 2 |
2009-01-16T23:36:04Z
| 452,441 |
<p>I'd try the following: </p>
<ol>
<li>Open Python shell </li>
<li>Type <code>import <moduleName></code></li>
<li>Parse the results (no error, ImportError or some module loading error) </li>
<li>Try to invoke any function from imported module (to see if module is correctly initialized).</li>
</ol>
<p>Do you need something more sophisticated?</p>
| 1 |
2009-01-16T23:41:29Z
|
[
"python",
"installation",
"module"
] |
How can I test that I have a Python module successfully installed?
| 452,430 |
<p>I tried to install beautifulsoup. I get such an error:<br>
<-- snip --></p>
<pre><code>raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /Users/Sam/.pydistutils.cfg, line: 1
'install_lib = ~/Library/Python/$py_version_short/site-packages\n'
</code></pre>
<p>I get an similar error as I run my Python code in vim by:
:!python %</p>
| 2 |
2009-01-16T23:36:04Z
| 18,761,681 |
<p>try:
from prettytable import <strong>PrettyTable</strong>
except:
try:
print "\033[31mPython-prettytable Module [Not Available]\033[0m"
os.system('sudo apt-get install python-setuptools')
os.system('sudo easy_install prettyTable')
print "\033[33mPython-prettytable Module [Installed]\033[0m"
except:
print "PrettyTable Python Module Installation failed."
print "\033[32mPython-prettytable Module [Available]\033[0m"</p>
| 0 |
2013-09-12T10:24:02Z
|
[
"python",
"installation",
"module"
] |
A SuggestBox for wxPython?
| 452,520 |
<p>Is there a widget for wxPython like the <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html" rel="nofollow">SuggestBox</a> in Google Web Toolkit? It is basically a magic text box that can invoke some code to come up with suggestions relevant to whatever the user has entered so far. Like the search box on Google's web page.</p>
<p>If such a widget isn't already floating out there, I'd appreciate a sketch of how I might implement it with the existing widgets.</p>
| 4 |
2009-01-17T00:14:24Z
| 455,144 |
<p>You might want to look at <a href="http://wiki.wxpython.org/Combo%20Box%20that%20Suggests%20Options" rel="nofollow">Combo Box that Suggests Options</a>.</p>
<p>I hope this is what you were thinking of.</p>
| 4 |
2009-01-18T13:42:08Z
|
[
"python",
"search",
"wxpython",
"suggestbox"
] |
A SuggestBox for wxPython?
| 452,520 |
<p>Is there a widget for wxPython like the <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html" rel="nofollow">SuggestBox</a> in Google Web Toolkit? It is basically a magic text box that can invoke some code to come up with suggestions relevant to whatever the user has entered so far. Like the search box on Google's web page.</p>
<p>If such a widget isn't already floating out there, I'd appreciate a sketch of how I might implement it with the existing widgets.</p>
| 4 |
2009-01-17T00:14:24Z
| 4,052,860 |
<p>Few years ago I made a control like this by subclassing TextCtrl. It supports HTML formating for suggestions. <a href="http://bitbucket.org/raz/wxautocompletectrl" rel="nofollow">Here you go.</a></p>
| 1 |
2010-10-29T14:38:40Z
|
[
"python",
"search",
"wxpython",
"suggestbox"
] |
What does this Python message mean?
| 452,532 |
<pre><code>ho-fe3fdd00-12:~ Sam$ easy_install BeautifulSoup
Traceback (most recent call last):
File "/usr/bin/easy_install", line 8, in <module>
load_entry_point('setuptools==0.6c7', 'console_scripts', 'easy_install')()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1670, in main
with_ei_usage(lambda:
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1659, in with_ei_usage
return f()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1674, in <lambda>
distclass=DistributionWithoutHelpCommands, **kw
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/core.py", line 125, in setup
dist.parse_config_files()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py", line 373, in parse_config_files
parser.read(filename)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", line 267, in read
self._read(fp, filename)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", line 462, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /Users/Sam/.pydistutils.cfg, line: 1
'install_lib = ~/Library/Python/$py_version_short/site-packages\n'
</code></pre>
<p>I am trying to install beautifulsoup.
The first two lines in ~/.pydistutils.cfg:</p>
<pre><code>install_lib = ~/Library/Python/$py_version_short/site-packages
install_scripts = ~/bin
</code></pre>
| -1 |
2009-01-17T00:22:25Z
| 452,536 |
<p>The configuration file .pydstutils.cfg has a syntax error.</p>
| 2 |
2009-01-17T00:26:07Z
|
[
"python",
"osx",
"installation",
"beautifulsoup",
"easy-install"
] |
What does this Python message mean?
| 452,532 |
<pre><code>ho-fe3fdd00-12:~ Sam$ easy_install BeautifulSoup
Traceback (most recent call last):
File "/usr/bin/easy_install", line 8, in <module>
load_entry_point('setuptools==0.6c7', 'console_scripts', 'easy_install')()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1670, in main
with_ei_usage(lambda:
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1659, in with_ei_usage
return f()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1674, in <lambda>
distclass=DistributionWithoutHelpCommands, **kw
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/core.py", line 125, in setup
dist.parse_config_files()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py", line 373, in parse_config_files
parser.read(filename)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", line 267, in read
self._read(fp, filename)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", line 462, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /Users/Sam/.pydistutils.cfg, line: 1
'install_lib = ~/Library/Python/$py_version_short/site-packages\n'
</code></pre>
<p>I am trying to install beautifulsoup.
The first two lines in ~/.pydistutils.cfg:</p>
<pre><code>install_lib = ~/Library/Python/$py_version_short/site-packages
install_scripts = ~/bin
</code></pre>
| -1 |
2009-01-17T00:22:25Z
| 452,597 |
<p>Try to add the line at the top of <code>~/.pydistutils.cfg</code>:</p>
<pre><code>[easy_install]
</code></pre>
| 2 |
2009-01-17T01:10:25Z
|
[
"python",
"osx",
"installation",
"beautifulsoup",
"easy-install"
] |
What does this Python message mean?
| 452,532 |
<pre><code>ho-fe3fdd00-12:~ Sam$ easy_install BeautifulSoup
Traceback (most recent call last):
File "/usr/bin/easy_install", line 8, in <module>
load_entry_point('setuptools==0.6c7', 'console_scripts', 'easy_install')()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1670, in main
with_ei_usage(lambda:
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1659, in with_ei_usage
return f()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/setuptools/command/easy_install.py", line 1674, in <lambda>
distclass=DistributionWithoutHelpCommands, **kw
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/core.py", line 125, in setup
dist.parse_config_files()
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py", line 373, in parse_config_files
parser.read(filename)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", line 267, in read
self._read(fp, filename)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", line 462, in _read
raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: /Users/Sam/.pydistutils.cfg, line: 1
'install_lib = ~/Library/Python/$py_version_short/site-packages\n'
</code></pre>
<p>I am trying to install beautifulsoup.
The first two lines in ~/.pydistutils.cfg:</p>
<pre><code>install_lib = ~/Library/Python/$py_version_short/site-packages
install_scripts = ~/bin
</code></pre>
| -1 |
2009-01-17T00:22:25Z
| 452,606 |
<p>BeautifulSoup is a pure Python module which you can install by grabbing the BeautifulSoup.py file (eg. from inside the standard .tar.gz distribution) and putting it somewhere on your PythonPath - eg. inside /Users/Sam/Library/Python/2.5/site-packages, if the paths mentioned in the error message are accurate.</p>
<p>No need for fussy and error-prone installers which just overcomplicate the issue.</p>
| 3 |
2009-01-17T01:17:03Z
|
[
"python",
"osx",
"installation",
"beautifulsoup",
"easy-install"
] |
How do I create a list of Python lambdas (in a list comprehension/for loop)?
| 452,610 |
<p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p>
<pre><code>listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
</code></pre>
<p>This will create a list of lambda objects, however, when I run them:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>I would expect that it would print</p>
<pre><code>1 4 9 16 25
</code></pre>
<p>Instead, it prints:</p>
<pre><code>25 25 25 25 25
</code></pre>
<p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p>
<p>EDIT: a bit more of trying things and such came up with this:</p>
<pre><code>listOfLambdas = []
for num in listOfNumbers:
action = lambda: square(num)
listOfLambdas.append(action)
print action()
</code></pre>
<p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p>
<p>Related question: <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>
| 16 |
2009-01-17T01:19:13Z
| 452,639 |
<p>I'm guessing that the lambda you're creating in the list comprehension is bound to the variable i which eventually ends up at 5. Thus, when you evaluate the lambdas after the fact, they're all bound to 5 and end up calculating 25. The same thing is happening with num in your second example. When you evaluate the lambda inside the loop it's num hasn't changed so you get the right value. After the loop, num is 5...</p>
<p>I'm not quite sure what you're going for, so I'm not sure how to suggest a solution. How about this?</p>
<pre><code>def square(x): return lambda : x*x
listOfLambdas = [square(i) for i in [1,2,3,4,5]]
for f in listOfLambdas: print f()
</code></pre>
<p>This gives me the expected output:</p>
<pre><code>1
4
9
16
25
</code></pre>
<p>Another way to think of this is that a lambda "captures" its lexical environment at the point where it is created. So, if you give it <strong>num</strong> it doesn't actually resolve that value until its invoked. This is both confusing and powerful.</p>
| 11 |
2009-01-17T01:37:51Z
|
[
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] |
How do I create a list of Python lambdas (in a list comprehension/for loop)?
| 452,610 |
<p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p>
<pre><code>listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
</code></pre>
<p>This will create a list of lambda objects, however, when I run them:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>I would expect that it would print</p>
<pre><code>1 4 9 16 25
</code></pre>
<p>Instead, it prints:</p>
<pre><code>25 25 25 25 25
</code></pre>
<p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p>
<p>EDIT: a bit more of trying things and such came up with this:</p>
<pre><code>listOfLambdas = []
for num in listOfNumbers:
action = lambda: square(num)
listOfLambdas.append(action)
print action()
</code></pre>
<p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p>
<p>Related question: <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>
| 16 |
2009-01-17T01:19:13Z
| 452,653 |
<p>I sometimes find that defining actual classes for function objects makes it easier to understand what's going on:</p>
<pre><code>>>> class square(object):
... def __init__(self, val):
... self.val = val
... def __call__(self):
... return self.val * self.val
...
>>> l = [1,2,3,4,5]
>>> funcs = [square(i) for i in l]
>>> for f in funcs:
... print f()
...
1
4
9
16
25
>>>
</code></pre>
<p>Granted, it's a bit more verbose than using lambdas or closures, but I find this easier to understand when I'm trying to do non-obvious things with functions.</p>
| 0 |
2009-01-17T01:46:37Z
|
[
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] |
How do I create a list of Python lambdas (in a list comprehension/for loop)?
| 452,610 |
<p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p>
<pre><code>listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
</code></pre>
<p>This will create a list of lambda objects, however, when I run them:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>I would expect that it would print</p>
<pre><code>1 4 9 16 25
</code></pre>
<p>Instead, it prints:</p>
<pre><code>25 25 25 25 25
</code></pre>
<p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p>
<p>EDIT: a bit more of trying things and such came up with this:</p>
<pre><code>listOfLambdas = []
for num in listOfNumbers:
action = lambda: square(num)
listOfLambdas.append(action)
print action()
</code></pre>
<p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p>
<p>Related question: <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>
| 16 |
2009-01-17T01:19:13Z
| 452,659 |
<p>You have:</p>
<pre><code>listOfLambdas = [lambda: i*i for i in range(6)]
for f in listOfLambdas:
print f()
</code></pre>
<p>Output:</p>
<pre><code>25
25
25
25
25
25
</code></pre>
<p>You need currying! Aside from being delicious, use this default value "hack".</p>
<pre><code>listOfLambdas = [lambda i=i: i*i for i in range(6)]
for f in listOfLambdas:
print f()
</code></pre>
<p>Output:</p>
<pre><code>0
1
4
9
16
25
</code></pre>
<p>Note the <code>i=i</code>. That's where the magic happens. </p>
| 17 |
2009-01-17T01:51:59Z
|
[
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] |
How do I create a list of Python lambdas (in a list comprehension/for loop)?
| 452,610 |
<p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p>
<pre><code>listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
</code></pre>
<p>This will create a list of lambda objects, however, when I run them:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>I would expect that it would print</p>
<pre><code>1 4 9 16 25
</code></pre>
<p>Instead, it prints:</p>
<pre><code>25 25 25 25 25
</code></pre>
<p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p>
<p>EDIT: a bit more of trying things and such came up with this:</p>
<pre><code>listOfLambdas = []
for num in listOfNumbers:
action = lambda: square(num)
listOfLambdas.append(action)
print action()
</code></pre>
<p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p>
<p>Related question: <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>
| 16 |
2009-01-17T01:19:13Z
| 452,660 |
<pre><code>listOfLambdas = [lambda i=i: square(i) for i in listOfNumbers]
</code></pre>
<p>Or</p>
<pre><code>listOfLambdas = map(lambda i: lambda: square(i), listOfNumbers)
</code></pre>
| 2 |
2009-01-17T01:52:49Z
|
[
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] |
How do I create a list of Python lambdas (in a list comprehension/for loop)?
| 452,610 |
<p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p>
<pre><code>listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
</code></pre>
<p>This will create a list of lambda objects, however, when I run them:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>I would expect that it would print</p>
<pre><code>1 4 9 16 25
</code></pre>
<p>Instead, it prints:</p>
<pre><code>25 25 25 25 25
</code></pre>
<p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p>
<p>EDIT: a bit more of trying things and such came up with this:</p>
<pre><code>listOfLambdas = []
for num in listOfNumbers:
action = lambda: square(num)
listOfLambdas.append(action)
print action()
</code></pre>
<p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p>
<p>Related question: <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>
| 16 |
2009-01-17T01:19:13Z
| 453,152 |
<p>When function statements are executed they are bound to their (lexically) enclosing scope.</p>
<p>In your snippet, the lambdas are bound to the global scope, because <code>for</code> suites are not executed as an independently scoped unit in Python. At the end of the <code>for</code> loop, the <code>num</code> is bound in the enclosing scope. Demo:</p>
<pre><code>for num in range(1, 6):
pass
assert num == 5 # num is now bound in the enclosing scope
</code></pre>
<p>So when you bind identifiers in the <code>for</code> loop you're actually manipulating the enclosing scope.</p>
<pre><code>for num in range(1, 6):
spam = 12
assert num == 5 # num is now bound in the enclosing scope
assert spam == 12 # spam is also bound in the enclosing scope
</code></pre>
<p>Same deal for list comprehensions:</p>
<pre><code>[num for num in range(1, 6)]
assert num == 5
</code></pre>
<p>Mind blowing, I know. Anywho, with our newfound knowledge, we can determine that the lambdas you are creating are referring to the (single) <code>num</code> identifier bound in the enclosing scope. That should make this make more sense:</p>
<pre><code>functions = []
for number in range(1, 6):
def fun():
return number
functions.append(fun)
assert all(fun() == 5 for fun in functions)
assert all(fun() is number for fun in functions)
</code></pre>
<p>And here's the coolest part that demonstrates it even more:</p>
<pre><code># Same as above -- commented out for emphasis.
#functions = []
#for number in range(1, 6):
# def fun():
# return number
# functions.append(fun)
#assert all(fun() == 5 for fun in functions)
#assert all(fun() is number for fun in functions)
number = 6 # Rebind 6 in the scope and see how it affects the results.
assert all(fun() == 6 for fun in functions)
</code></pre>
<p>So the solution to this, of course, is to make a new enclosing scope for each <code>number</code> you want to bind. In Python, you can create new enclosing scopes with modules, classes, and functions. It's common to use a function just to create new enclosing scope for another function.</p>
<p>In Python, a <em>closure</em> is a function that <strong>returns another function</strong>. Kind of like a function constructor. Check out <code>get_fun</code> in the following example:</p>
<pre><code>def get_fun(value):
""":return: A function that returns :param:`value`."""
def fun(): # Bound to get_fun's scope
return value
return fun
functions = []
for number in range(1, 6):
functions.append(get_fun(number))
assert [fun() for fun in functions] == range(1, 6)
</code></pre>
<p>Since <code>get_fun</code> is a function, it gets to have its own internal scope. Every time you call <code>get_fun</code> with a value, a little table is created to keep track of bindings within it; i.e. it says, "Within this scope, the <code>value</code> identifier points to the thing that was passed." That scope goes away at the end of the function execution, unless there's a reason for it to hang around.</p>
<p>If you're returning a function from within a scope, that's a good reason for parts of the "scope table" to hang around -- that function you're returning could reference things from that scope table when you call it later on. For that reason, when <code>fun</code> is created within <code>get_fun</code> Python tells <code>fun</code> about <code>get_fun</code>'s scope table, which <code>fun</code> keeps handy for when it's needed.</p>
<p>You can read more about the details and technical terminology (which I softened a bit) in the <a href="http://docs.python.org/reference/executionmodel.html" rel="nofollow">Python docs on the execution model</a>. You can also look at the parts of the enclosing scope that a function refers to with <code>print fun.__closure__</code>. In the above, we see the reference to the <code>value</code>, which happens to be an int:</p>
<pre><code># Same as before, commented out for emphasis.
#functions = []
#for number in range(1, 6):
# functions.append(get_fun(number))
#assert [fun() for fun in functions] == range(1, 6)
print functions[0].__closure__
# Produces: (<cell at 0x8dc30: int object at 0x1004188>,)
</code></pre>
| 3 |
2009-01-17T11:13:42Z
|
[
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] |
How do I create a list of Python lambdas (in a list comprehension/for loop)?
| 452,610 |
<p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p>
<pre><code>listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
</code></pre>
<p>This will create a list of lambda objects, however, when I run them:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>I would expect that it would print</p>
<pre><code>1 4 9 16 25
</code></pre>
<p>Instead, it prints:</p>
<pre><code>25 25 25 25 25
</code></pre>
<p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p>
<p>EDIT: a bit more of trying things and such came up with this:</p>
<pre><code>listOfLambdas = []
for num in listOfNumbers:
action = lambda: square(num)
listOfLambdas.append(action)
print action()
</code></pre>
<p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p>
<p>Related question: <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>
| 16 |
2009-01-17T01:19:13Z
| 23,686,541 |
<p>Try to use () instead of []:</p>
<pre><code>listOfLambdas = (lambda: square(i) for i in listOfNumbers)
</code></pre>
<p>And you will get:</p>
<pre><code>1
4
9
16
25
</code></pre>
| 1 |
2014-05-15T18:58:02Z
|
[
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] |
How do I create a list of Python lambdas (in a list comprehension/for loop)?
| 452,610 |
<p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p>
<pre><code>listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
</code></pre>
<p>This will create a list of lambda objects, however, when I run them:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>I would expect that it would print</p>
<pre><code>1 4 9 16 25
</code></pre>
<p>Instead, it prints:</p>
<pre><code>25 25 25 25 25
</code></pre>
<p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p>
<p>EDIT: a bit more of trying things and such came up with this:</p>
<pre><code>listOfLambdas = []
for num in listOfNumbers:
action = lambda: square(num)
listOfLambdas.append(action)
print action()
</code></pre>
<p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p>
<pre><code>for f in listOfLambdas:
print f(),
</code></pre>
<p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p>
<p>Related question: <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>
| 16 |
2009-01-17T01:19:13Z
| 31,397,531 |
<p>You could also do:</p>
<pre><code>>>> def squares():
... for i in [1,2,3,4,5]:
... yield lambda:i*i
...
>>> print [square() for square in squares()]
[1, 4, 9, 16, 25]
</code></pre>
| 0 |
2015-07-14T04:15:05Z
|
[
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] |
What is the best way to handle a bad link given to BeautifulSoup?
| 452,884 |
<p>I'm working on something that pulls in urls from delicious and then uses those urls to discover associated feeds. </p>
<p>However, some of the bookmarks in delicious are not html links and cause BS to barf. Basically, I want to throw away a link if BS fetches it and it does not look like html.</p>
<p>Right now, this is what I'm getting. </p>
<pre><code>trillian:Documents jauderho$ ./d2o.py "green data center"
processing http://www.greenm3.com/
processing http://www.eweek.com/c/a/Green-IT/How-to-Create-an-EnergyEfficient-Green-Data-Center/?kc=rss
Traceback (most recent call last):
File "./d2o.py", line 53, in <module>
get_feed_links(d_links)
File "./d2o.py", line 43, in get_feed_links
soup = BeautifulSoup(html)
File "/Library/Python/2.5/site-packages/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/Library/Python/2.5/site-packages/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/Library/Python/2.5/site-packages/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/HTMLParser.py", line 150, in goahead
k = self.parse_endtag(i)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/HTMLParser.py", line 314, in parse_endtag
self.error("bad end tag: %r" % (rawdata[i:j],))
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: bad end tag: u'</b />', at line 739, column 1
</code></pre>
<p><strong>Update:</strong></p>
<p>Jehiah's answer does the trick. For reference, here's some code to get the content type:</p>
<pre><code>def check_for_html(link):
out = urllib.urlopen(link)
return out.info().getheader('Content-Type')
</code></pre>
| 1 |
2009-01-17T06:10:41Z
| 452,896 |
<p>I simply wrap my BeautifulSoup processing and look for the <code>HTMLParser.HTMLParseError</code> exception</p>
<pre><code>import HTMLParser,BeautifulSoup
try:
soup = BeautifulSoup.BeautifulSoup(raw_html)
for a in soup.findAll('a'):
href = a.['href']
....
except HTMLParser.HTMLParseError:
print "failed to parse",url
</code></pre>
<p>but further than that, you can check the content type of the responses when you crawl a page and make sure that it's something like <code>text/html</code> or <code>application/xml+xhtml</code> or something like that before you even try to parse it. That should head off most errors.</p>
| 3 |
2009-01-17T06:20:54Z
|
[
"python",
"parsing",
"beautifulsoup"
] |
Does python have an equivalent to Java Class.forName()?
| 452,969 |
<p>I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use <code>Class.forName().newInstance()</code>. Is there an equivalent in Python?</p>
<hr>
<p>Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as the class name, and instantiate it. I'm actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. <code>getattr()</code> works great. Thanks much.</p>
| 76 |
2009-01-17T08:10:48Z
| 452,971 |
<p>Assuming the class is in your scope:</p>
<pre><code>globals()['classname'](args, to, constructor)
</code></pre>
<p>Otherwise:</p>
<pre><code>getattr(someModule, 'classname')(args, to, constructor)
</code></pre>
<p>Edit: Note, you can't give a name like 'foo.bar' to getattr. You'll need to split it by . and call getattr() on each piece left-to-right. This will handle that:</p>
<pre><code>module, rest = 'foo.bar.baz'.split('.', 1)
fooBar = reduce(lambda a, b: getattr(a, b), rest.split('.'), globals()[module])
someVar = fooBar(args, to, constructor)
</code></pre>
| 20 |
2009-01-17T08:13:05Z
|
[
"java",
"python",
"class",
"instantiation"
] |
Does python have an equivalent to Java Class.forName()?
| 452,969 |
<p>I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use <code>Class.forName().newInstance()</code>. Is there an equivalent in Python?</p>
<hr>
<p>Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as the class name, and instantiate it. I'm actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. <code>getattr()</code> works great. Thanks much.</p>
| 76 |
2009-01-17T08:10:48Z
| 452,981 |
<p>Reflection in python is a lot easier and far more flexible than it is in Java.</p>
<p>I recommend reading this <a href="http://www.diveintopython.net/power_of_introspection/index.html">tutorial</a></p>
<p>There's no direct function (that I know of) which takes a fully qualified class name and returns the class, however you have all the pieces needed to build that, and you can connect them together.</p>
<p>One bit of advice though: don't try to program in Java style when you're in python.</p>
<p>If you can explain what is it that you're trying to do, maybe we can help you find a more pythonic way of doing it.</p>
<p>Here's a function that does what you want:</p>
<pre><code>def get_class( kls ):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m
</code></pre>
<p>You can use the return value of this function as if it were the class itself.</p>
<p>Here's a usage example:</p>
<pre><code>>>> D = get_class("datetime.datetime")
>>> D
<type 'datetime.datetime'>
>>> D.now()
datetime.datetime(2009, 1, 17, 2, 15, 58, 883000)
>>> a = D( 2010, 4, 22 )
>>> a
datetime.datetime(2010, 4, 22, 0, 0)
>>>
</code></pre>
<p><strong>How does that work?</strong></p>
<p>We're using <code>__import__</code> to import the module that holds the class, which required that we first extract the module name from the fully qualified name. Then we import the module:</p>
<pre><code>m = __import__( module )
</code></pre>
<p>In this case, <code>m</code> will only refer to the top level module, </p>
<p>For example, if your class lives in <code>foo.baz</code> module, then <code>m</code> will be the module <code>foo</code><br>
We can easily obtain a reference to <code>foo.baz</code> using <code>getattr( m, 'baz' )</code></p>
<p>To get from the top level module to the class, have to recursively use <code>gettatr</code> on the parts of the class name</p>
<p>Say for example, if you class name is <code>foo.baz.bar.Model</code> then we do this:</p>
<pre><code>m = __import__( "foo.baz.bar" ) #m is package foo
m = getattr( m, "baz" ) #m is package baz
m = getattr( m, "bar" ) #m is module bar
m = getattr( m, "Model" ) #m is class Model
</code></pre>
<p>This is what's happening in this loop:</p>
<pre><code>for comp in parts[1:]:
m = getattr(m, comp)
</code></pre>
<p>At the end of the loop, <code>m</code> will be a reference to the class. This means that <code>m</code> is actually the class itslef, you can do for instance:</p>
<pre><code>a = m() #instantiate a new instance of the class
b = m( arg1, arg2 ) # pass arguments to the constructor
</code></pre>
| 135 |
2009-01-17T08:25:39Z
|
[
"java",
"python",
"class",
"instantiation"
] |
Does python have an equivalent to Java Class.forName()?
| 452,969 |
<p>I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use <code>Class.forName().newInstance()</code>. Is there an equivalent in Python?</p>
<hr>
<p>Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as the class name, and instantiate it. I'm actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. <code>getattr()</code> works great. Thanks much.</p>
| 76 |
2009-01-17T08:10:48Z
| 453,459 |
<p>It seems you're approaching this from the middle instead of the beginning. What are you really trying to do? Finding the class associated with a given string is a means to an end.</p>
<p>If you clarify your problem, which might require your own mental refactoring, a better solution may present itself.</p>
<p>For instance: Are you trying to load a saved object based on its type name and a set of parameters? Python spells this unpickling and you should look at the <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle module</a>. And even though the unpickling process does exactly what you describe, you don't have to worry about how it works internally:</p>
<pre><code>>>> class A(object):
... def __init__(self, v):
... self.v = v
... def __reduce__(self):
... return (self.__class__, (self.v,))
>>> a = A("example")
>>> import pickle
>>> b = pickle.loads(pickle.dumps(a))
>>> a.v, b.v
('example', 'example')
>>> a is b
False
</code></pre>
| 3 |
2009-01-17T15:37:40Z
|
[
"java",
"python",
"class",
"instantiation"
] |
Does python have an equivalent to Java Class.forName()?
| 452,969 |
<p>I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use <code>Class.forName().newInstance()</code>. Is there an equivalent in Python?</p>
<hr>
<p>Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as the class name, and instantiate it. I'm actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. <code>getattr()</code> works great. Thanks much.</p>
| 76 |
2009-01-17T08:10:48Z
| 3,610,097 |
<p>Yet another implementation.</p>
<pre><code>def import_class(class_string):
"""Returns class object specified by a string.
Args:
class_string: The string representing a class.
Raises:
ValueError if module part of the class is not specified.
"""
module_name, _, class_name = class_string.rpartition('.')
if module_name == '':
raise ValueError('Class name must contain module part.')
return getattr(
__import__(module_name, globals(), locals(), [class_name], -1),
class_name)
</code></pre>
| 4 |
2010-08-31T14:41:58Z
|
[
"java",
"python",
"class",
"instantiation"
] |
Does python have an equivalent to Java Class.forName()?
| 452,969 |
<p>I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use <code>Class.forName().newInstance()</code>. Is there an equivalent in Python?</p>
<hr>
<p>Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as the class name, and instantiate it. I'm actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. <code>getattr()</code> works great. Thanks much.</p>
| 76 |
2009-01-17T08:10:48Z
| 20,507,847 |
<p>This is found in the python standard library, as unittest.TestLoader.loadTestsFromName. Unfortunately the method goes on to do additional test-related activities, but this first ha looks re-usable. I've edited it to remove the test-related functionality:</p>
<pre><code>def get_object(name):
"""Retrieve a python object, given its dotted.name."""
parts = name.split('.')
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy: raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
return obj
</code></pre>
| 1 |
2013-12-10T23:54:55Z
|
[
"java",
"python",
"class",
"instantiation"
] |
Does python have an equivalent to Java Class.forName()?
| 452,969 |
<p>I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use <code>Class.forName().newInstance()</code>. Is there an equivalent in Python?</p>
<hr>
<p>Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as the class name, and instantiate it. I'm actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. <code>getattr()</code> works great. Thanks much.</p>
| 76 |
2009-01-17T08:10:48Z
| 30,042,585 |
<pre><code>def import_class_from_string(path):
from importlib import import_module
module_path, _, class_name = path.rpartition('.')
mod = import_module(module_path)
klass = getattr(mod, class_name)
return klass
</code></pre>
<h2>Usage</h2>
<pre><code>In [59]: raise import_class_from_string('google.appengine.runtime.apiproxy_errors.DeadlineExceededError')()
---------------------------------------------------------------------------
DeadlineExceededError Traceback (most recent call last)
<ipython-input-59-b4e59d809b2f> in <module>()
----> 1 raise import_class_from_string('google.appengine.runtime.apiproxy_errors.DeadlineExceededError')()
DeadlineExceededError:
</code></pre>
| 2 |
2015-05-05T01:00:38Z
|
[
"java",
"python",
"class",
"instantiation"
] |
What is the practical difference between xml, json, rss and atom when interfacing with Twitter?
| 453,158 |
<p>I'm new to web services and as an introduction I'm playing around with the Twitter API using the Twisted framework in python. I've read up on the different formats they offer, but it's still not clear to me which one I should use in my fairly simple project.
Specifically the practical difference between using JSON or XML is something I'd like guidance on. All I'm doing is requesting the public timeline and caching it locally.</p>
<p>Thanks.</p>
| 5 |
2009-01-17T11:19:36Z
| 453,160 |
<p>RSS and Atom are XML formats.</p>
<p>JSON is a string which can be evaluated as Javascript code.</p>
| 4 |
2009-01-17T11:21:38Z
|
[
"python",
"xml",
"json",
"twitter",
"twisted"
] |
What is the practical difference between xml, json, rss and atom when interfacing with Twitter?
| 453,158 |
<p>I'm new to web services and as an introduction I'm playing around with the Twitter API using the Twisted framework in python. I've read up on the different formats they offer, but it's still not clear to me which one I should use in my fairly simple project.
Specifically the practical difference between using JSON or XML is something I'd like guidance on. All I'm doing is requesting the public timeline and caching it locally.</p>
<p>Thanks.</p>
| 5 |
2009-01-17T11:19:36Z
| 453,164 |
<p>I would say the amount of data being sent over the wire is one factor. XML datastream will be bigger than JSON for the same data. But you can use whatever you know more/have more experiance.
I would reccoment JSON, as it's more "pythonic" than XML.</p>
| 1 |
2009-01-17T11:24:46Z
|
[
"python",
"xml",
"json",
"twitter",
"twisted"
] |
What is the practical difference between xml, json, rss and atom when interfacing with Twitter?
| 453,158 |
<p>I'm new to web services and as an introduction I'm playing around with the Twitter API using the Twisted framework in python. I've read up on the different formats they offer, but it's still not clear to me which one I should use in my fairly simple project.
Specifically the practical difference between using JSON or XML is something I'd like guidance on. All I'm doing is requesting the public timeline and caching it locally.</p>
<p>Thanks.</p>
| 5 |
2009-01-17T11:19:36Z
| 453,389 |
<p>For me it boils down to convenience. Using XML, I have to parse the response in to a DOM (or more usually an ElementTree). Using JSON, one call to simplejson.loads(json_string) and I have a native Python data structure (lists, dictionaries, strings etc) which I can start iterating over and processing. Anything that means writing a few less lines of code is usually a good idea in my opinion.</p>
<p>I often use JSON to move data structures between PHP, Python and JavaScript - again, because it saves me having to figure out an XML serialization and then parse it at the other end.</p>
<p>And like jinzo said, JSON ends up being slightly fewer bytes on the wire.</p>
<p>You might find my blog entry on JSON from a couple of years ago useful: <a href="http://simonwillison.net/2006/Dec/20/json/">http://simonwillison.net/2006/Dec/20/json/</a></p>
| 7 |
2009-01-17T14:45:23Z
|
[
"python",
"xml",
"json",
"twitter",
"twisted"
] |
Advice regarding IPython + MacVim Workflow
| 453,329 |
<p>I've just found <a href="http://ipython.scipy.org/">IPython</a> and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like <a href="http://stackoverflow.com/questions/431521/run-a-command-in-a-shell-and-keep-running-the-command-when-you-close-the-session#431570">the one I have with screen</a>. Ipython and screen happen to be the best of friends too so it's a triangular drama. Purely platonic, mind you.</p>
<p>The reason IPython hits the soft spots with me are very much because I generally like command prompts, and especially *nix-inspired prompts with inspiration from ksh, csh (yes, chs is a monster, but as a prompt it sport lots of really good features), bash and zsh. And IPython does sure feel like home for a *nix prompt rider. Mixing the system shell and python is also a really good idea. Plus, of course, IPython helps a lot when solving <a href="http://www.pythonchallenge.com/">the Python Challenge</a> riddles. Invaluable even.</p>
<p>Now, I love Vim too. Since I learnt vi back in the days there's no turning back. And I'm on Mac when I have a choice. Now I'd like to glue together my IPython + MacVim workflow. What I've done so far is that I start Ipython using:</p>
<pre><code>ipython -e "open -a MacVim"
</code></pre>
<p>Thus when I edit from IPython it starts MacVim with the file/module loaded. Could look a bit like so:</p>
<pre><code>In [4]: %run foo #This also "imports" foo anew
hello world
In [5]: edit foo
Editing... done. Executing edited code... #This happens immediately
hello world
In [6]: %run foo
hello SO World
</code></pre>
<p>OK. I think this can be improved. Maybe there's a way to tie IPython into MacVim too? Please share your experiences. Of course if you use TextMate or some other fav editor I'm interested too. Maybe some of the lessons are general.</p>
| 18 |
2009-01-17T13:46:27Z
| 453,378 |
<p>In the ipythonrc.ini file in you home directory change the editor to MacVim.</p>
| 1 |
2009-01-17T14:38:20Z
|
[
"python",
"vim",
"ipython"
] |
Advice regarding IPython + MacVim Workflow
| 453,329 |
<p>I've just found <a href="http://ipython.scipy.org/">IPython</a> and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like <a href="http://stackoverflow.com/questions/431521/run-a-command-in-a-shell-and-keep-running-the-command-when-you-close-the-session#431570">the one I have with screen</a>. Ipython and screen happen to be the best of friends too so it's a triangular drama. Purely platonic, mind you.</p>
<p>The reason IPython hits the soft spots with me are very much because I generally like command prompts, and especially *nix-inspired prompts with inspiration from ksh, csh (yes, chs is a monster, but as a prompt it sport lots of really good features), bash and zsh. And IPython does sure feel like home for a *nix prompt rider. Mixing the system shell and python is also a really good idea. Plus, of course, IPython helps a lot when solving <a href="http://www.pythonchallenge.com/">the Python Challenge</a> riddles. Invaluable even.</p>
<p>Now, I love Vim too. Since I learnt vi back in the days there's no turning back. And I'm on Mac when I have a choice. Now I'd like to glue together my IPython + MacVim workflow. What I've done so far is that I start Ipython using:</p>
<pre><code>ipython -e "open -a MacVim"
</code></pre>
<p>Thus when I edit from IPython it starts MacVim with the file/module loaded. Could look a bit like so:</p>
<pre><code>In [4]: %run foo #This also "imports" foo anew
hello world
In [5]: edit foo
Editing... done. Executing edited code... #This happens immediately
hello world
In [6]: %run foo
hello SO World
</code></pre>
<p>OK. I think this can be improved. Maybe there's a way to tie IPython into MacVim too? Please share your experiences. Of course if you use TextMate or some other fav editor I'm interested too. Maybe some of the lessons are general.</p>
| 18 |
2009-01-17T13:46:27Z
| 453,837 |
<p>I use Linux, but I believe this tip can be used in OS X too. I use <a href="http://www.gnu.org/software/screen/">GNU Screen</a> to send IPython commands from Vim as recommended by <a href="http://vim.wikia.com/wiki/IPython_integration">this tip</a>. This is how I do it:</p>
<p>First, you should open a terminal and start a screen session called 'ipython' or whatever you want, and then start IPython:</p>
<pre><code>$ screen -S ipython
$ ipython
</code></pre>
<p>Then you should put this in your .vimrc:</p>
<pre><code>autocmd FileType python map F5 :w<CR>:!screen -x ipython -X stuff $'\%run %:p:h\n'<CR><CR>
</code></pre>
<p>Then when you hit F5, it will tell Screen to execute the command '%run file' inside the 'ipython' created previously, where file is your current buffer in Vim.</p>
<p>You can tweak this to execute the command you want inside IPython from Vim. For example I use this: </p>
<pre><code>autocmd FileType python map <F5> :w<CR>:!screen -x ipython -X stuff $'\%reset\ny\n\%cd %:p:h\n\%run %:t\n'<CR><CR>
</code></pre>
<p>This executes %reset (answering yes to the prompt), then change to the directory where the current buffer in vim is located and then %run the file. This is specially useful if you have the %pdb active in IPython.</p>
<p>Don't forget that you need an active Screen session called 'ipython' with IPython running inside.</p>
<p>If you like Emacs. There is <a href="http://ipython.scipy.org/dist/ipython.el">good support</a> for IPython.</p>
| 14 |
2009-01-17T19:13:43Z
|
[
"python",
"vim",
"ipython"
] |
Advice regarding IPython + MacVim Workflow
| 453,329 |
<p>I've just found <a href="http://ipython.scipy.org/">IPython</a> and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like <a href="http://stackoverflow.com/questions/431521/run-a-command-in-a-shell-and-keep-running-the-command-when-you-close-the-session#431570">the one I have with screen</a>. Ipython and screen happen to be the best of friends too so it's a triangular drama. Purely platonic, mind you.</p>
<p>The reason IPython hits the soft spots with me are very much because I generally like command prompts, and especially *nix-inspired prompts with inspiration from ksh, csh (yes, chs is a monster, but as a prompt it sport lots of really good features), bash and zsh. And IPython does sure feel like home for a *nix prompt rider. Mixing the system shell and python is also a really good idea. Plus, of course, IPython helps a lot when solving <a href="http://www.pythonchallenge.com/">the Python Challenge</a> riddles. Invaluable even.</p>
<p>Now, I love Vim too. Since I learnt vi back in the days there's no turning back. And I'm on Mac when I have a choice. Now I'd like to glue together my IPython + MacVim workflow. What I've done so far is that I start Ipython using:</p>
<pre><code>ipython -e "open -a MacVim"
</code></pre>
<p>Thus when I edit from IPython it starts MacVim with the file/module loaded. Could look a bit like so:</p>
<pre><code>In [4]: %run foo #This also "imports" foo anew
hello world
In [5]: edit foo
Editing... done. Executing edited code... #This happens immediately
hello world
In [6]: %run foo
hello SO World
</code></pre>
<p>OK. I think this can be improved. Maybe there's a way to tie IPython into MacVim too? Please share your experiences. Of course if you use TextMate or some other fav editor I'm interested too. Maybe some of the lessons are general.</p>
| 18 |
2009-01-17T13:46:27Z
| 478,897 |
<p>I've had the same issue. After experimenting this is my solution: if you placed MacVim.app in /Applications and mvim is in your path, in ~/.ipython/ipythonrc change the line</p>
<pre><code>editor 0
</code></pre>
<p>to</p>
<pre><code>editor mvim --remote-tab-wait-silent
</code></pre>
<p>I think you need to keep MacVim open in the background. You could also use the -f flag. Look at this thread from the <a href="http://groups.google.com/group/vim_mac/browse_thread/thread/2070d56fad8a7ee9/4cc4ebd1696e9fa5?lnk=gst&q=server+%22--remote%22#4cc4ebd1696e9fa5" rel="nofollow" title="MacVim google group">MacVim google group</a>.</p>
| 1 |
2009-01-26T05:10:40Z
|
[
"python",
"vim",
"ipython"
] |
Advice regarding IPython + MacVim Workflow
| 453,329 |
<p>I've just found <a href="http://ipython.scipy.org/">IPython</a> and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like <a href="http://stackoverflow.com/questions/431521/run-a-command-in-a-shell-and-keep-running-the-command-when-you-close-the-session#431570">the one I have with screen</a>. Ipython and screen happen to be the best of friends too so it's a triangular drama. Purely platonic, mind you.</p>
<p>The reason IPython hits the soft spots with me are very much because I generally like command prompts, and especially *nix-inspired prompts with inspiration from ksh, csh (yes, chs is a monster, but as a prompt it sport lots of really good features), bash and zsh. And IPython does sure feel like home for a *nix prompt rider. Mixing the system shell and python is also a really good idea. Plus, of course, IPython helps a lot when solving <a href="http://www.pythonchallenge.com/">the Python Challenge</a> riddles. Invaluable even.</p>
<p>Now, I love Vim too. Since I learnt vi back in the days there's no turning back. And I'm on Mac when I have a choice. Now I'd like to glue together my IPython + MacVim workflow. What I've done so far is that I start Ipython using:</p>
<pre><code>ipython -e "open -a MacVim"
</code></pre>
<p>Thus when I edit from IPython it starts MacVim with the file/module loaded. Could look a bit like so:</p>
<pre><code>In [4]: %run foo #This also "imports" foo anew
hello world
In [5]: edit foo
Editing... done. Executing edited code... #This happens immediately
hello world
In [6]: %run foo
hello SO World
</code></pre>
<p>OK. I think this can be improved. Maybe there's a way to tie IPython into MacVim too? Please share your experiences. Of course if you use TextMate or some other fav editor I'm interested too. Maybe some of the lessons are general.</p>
| 18 |
2009-01-17T13:46:27Z
| 8,077,462 |
<p>This questions is stale now, but just for reference - if you're using IPython 0.11 with ZeroMQ enabled, take a look at <a href="https://github.com/ivanov/vim-ipython">vim-ipython</a> (an older version of which shipped with 0.11).</p>
<p>Using this plugin, you can send lines or whole files for IPython to execute, and also get back object introspection and word completions
in Vim, like what you get with: <code>object?<enter></code> and <code>object.<tab></code> in IPython.</p>
<p>Take a look at two screencasts of this plugin in action on <a href="http://pirsquared.org/blog/2011/07/28/vim-ipython/">this post</a>.</p>
| 5 |
2011-11-10T09:35:52Z
|
[
"python",
"vim",
"ipython"
] |
Writing a simple "Rock Paper Scissors" game bot
| 453,396 |
<p>I need help with a python game im working on (I just started learning Python about 3 days ago, so I'm still a nOob =)</p>
<p>This is what I came up with:</p>
<pre><code>import random
from time import sleep
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = input ("Choose from 1-3: ")
if player == 1:
print "You choose Rock"
sleep (2)
print "CPU chooses Paper"
sleep (.5)
print "You lose, and you will never win!"
elif player == 2:
print "You choose Paper"
sleep (2)
print "CPU chooses Scissors"
sleep (.5)
print "You lose, and you will never win!"
else:
print "You choose Scissors"
sleep (2)
print "CPU chooses Rock"
sleep (.5)
print "You lose, and you will never win!"
</code></pre>
<p>and what I want the program to do is to RANDOMLY choose 1 out of the three options (rock paper scissors) no matter what the user inputs!</p>
| 7 |
2009-01-17T14:50:12Z
| 453,400 |
<p>Well, you've already imported the random module, that's a start.</p>
<p>Try the random.choice function.</p>
<pre><code>>>> from random import choice
>>> cpu_choice = choice(('rock', 'paper', 'scissors'))
</code></pre>
| 29 |
2009-01-17T14:53:03Z
|
[
"python"
] |
Writing a simple "Rock Paper Scissors" game bot
| 453,396 |
<p>I need help with a python game im working on (I just started learning Python about 3 days ago, so I'm still a nOob =)</p>
<p>This is what I came up with:</p>
<pre><code>import random
from time import sleep
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = input ("Choose from 1-3: ")
if player == 1:
print "You choose Rock"
sleep (2)
print "CPU chooses Paper"
sleep (.5)
print "You lose, and you will never win!"
elif player == 2:
print "You choose Paper"
sleep (2)
print "CPU chooses Scissors"
sleep (.5)
print "You lose, and you will never win!"
else:
print "You choose Scissors"
sleep (2)
print "CPU chooses Rock"
sleep (.5)
print "You lose, and you will never win!"
</code></pre>
<p>and what I want the program to do is to RANDOMLY choose 1 out of the three options (rock paper scissors) no matter what the user inputs!</p>
| 7 |
2009-01-17T14:50:12Z
| 453,502 |
<pre><code>import random
ROCK, PAPER, SCISSORS = 1, 2, 3
names = 'ROCK', 'PAPER', 'SCISSORS'
def beats(a, b):
if (a,b) in ((ROCK, PAPER), (PAPER, SCISSORS), (SCISSORS, ROCK)):
return False
return True
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = int(input ("Choose from 1-3: "))
cpu = random.choice((ROCK, PAPER, SCISSORS))
if cpu != player:
if beats(player, cpu):
print "player won"
else:
print "cpu won"
else:
print "tie!"
print names[player-1], "vs", names[cpu-1]
</code></pre>
| 7 |
2009-01-17T16:05:47Z
|
[
"python"
] |
Writing a simple "Rock Paper Scissors" game bot
| 453,396 |
<p>I need help with a python game im working on (I just started learning Python about 3 days ago, so I'm still a nOob =)</p>
<p>This is what I came up with:</p>
<pre><code>import random
from time import sleep
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = input ("Choose from 1-3: ")
if player == 1:
print "You choose Rock"
sleep (2)
print "CPU chooses Paper"
sleep (.5)
print "You lose, and you will never win!"
elif player == 2:
print "You choose Paper"
sleep (2)
print "CPU chooses Scissors"
sleep (.5)
print "You lose, and you will never win!"
else:
print "You choose Scissors"
sleep (2)
print "CPU chooses Rock"
sleep (.5)
print "You lose, and you will never win!"
</code></pre>
<p>and what I want the program to do is to RANDOMLY choose 1 out of the three options (rock paper scissors) no matter what the user inputs!</p>
| 7 |
2009-01-17T14:50:12Z
| 453,804 |
<p>Inspired by gumuz:</p>
<pre><code>import random
WEAPONS = 'Rock', 'Paper', 'Scissors'
for i in range(0, 3):
print "%d %s" % (i + 1, WEAPONS[i])
player = int(input ("Choose from 1-3: ")) - 1
cpu = random.choice(range(0, 3))
print "%s vs %s" % (WEAPONS[player], WEAPONS[cpu])
if cpu != player:
if (player - cpu) % 3 < (cpu - player) % 3:
print "Player wins"
else:
print "CPU wins"
else:
print "tie!"
</code></pre>
| 4 |
2009-01-17T18:48:38Z
|
[
"python"
] |
Writing a simple "Rock Paper Scissors" game bot
| 453,396 |
<p>I need help with a python game im working on (I just started learning Python about 3 days ago, so I'm still a nOob =)</p>
<p>This is what I came up with:</p>
<pre><code>import random
from time import sleep
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = input ("Choose from 1-3: ")
if player == 1:
print "You choose Rock"
sleep (2)
print "CPU chooses Paper"
sleep (.5)
print "You lose, and you will never win!"
elif player == 2:
print "You choose Paper"
sleep (2)
print "CPU chooses Scissors"
sleep (.5)
print "You lose, and you will never win!"
else:
print "You choose Scissors"
sleep (2)
print "CPU chooses Rock"
sleep (.5)
print "You lose, and you will never win!"
</code></pre>
<p>and what I want the program to do is to RANDOMLY choose 1 out of the three options (rock paper scissors) no matter what the user inputs!</p>
| 7 |
2009-01-17T14:50:12Z
| 7,410,938 |
<p>use dictionaries</p>
<pre><code>loseDic = { 'rock' : 'paper',
'paper' : 'scissors',
'scissors' : 'rock',
}
## Get the human move, chose a random move, bla bla bla...
if robotMove == humanMove:
tie()
elif humanMove == loseDic[robotMove]:
lose()
else:
win()
</code></pre>
| 4 |
2011-09-14T03:28:11Z
|
[
"python"
] |
Writing a simple "Rock Paper Scissors" game bot
| 453,396 |
<p>I need help with a python game im working on (I just started learning Python about 3 days ago, so I'm still a nOob =)</p>
<p>This is what I came up with:</p>
<pre><code>import random
from time import sleep
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = input ("Choose from 1-3: ")
if player == 1:
print "You choose Rock"
sleep (2)
print "CPU chooses Paper"
sleep (.5)
print "You lose, and you will never win!"
elif player == 2:
print "You choose Paper"
sleep (2)
print "CPU chooses Scissors"
sleep (.5)
print "You lose, and you will never win!"
else:
print "You choose Scissors"
sleep (2)
print "CPU chooses Rock"
sleep (.5)
print "You lose, and you will never win!"
</code></pre>
<p>and what I want the program to do is to RANDOMLY choose 1 out of the three options (rock paper scissors) no matter what the user inputs!</p>
| 7 |
2009-01-17T14:50:12Z
| 9,917,204 |
<p>Not an expert, but here is what I have thus far, using a <code>__name__ == '__main__'</code> statement may be helpful if you need the computer to generate an answer and keep it clean and concise.</p>
<p>No solution given.</p>
<pre><code>import random
def is_tie(move1, move2):
'''FIX! (parameter types) -> return type
Return True if move1 and move2 are the same.'''
if move1 == move2:
return True
def is_win(move1, move2):
'''FIX! (parameter types) -> return type
Return True iff move1 beats move2 in rock-paper-scissors.'''
choice1 = scissor > paper,
choice2 = paper > rock,
choice3 = rock > scissor
return choice1 or choice2 or choice3
if move1 > move2:
return True
if __name__ == '__main__':
# Get a move from the user.
print "Rock, Paper, Scissor",
move1 = raw_input("What is your move? ")
# Now, to generate a random move for the computer. Tricky... Here are some examples and suggestions, no solution given.
if move2(random.randint(1,3)) == 1:
print "paper"
elif move2(random.randint(1,3)) == 2:
print "rock"
else:
print "scissor"
# Evaluate who wins and then print out an appropriate message.
#if solution(move1, move2):
# print
#if move2 > move1:
# usr_fail = (raw_input('I win!!'))
# print usr_fail
#if move2 < move1:
# usr_win = (raw_input('Damn it!'))
# print usr_win
#if move2 == move1
#usr_draw = (raw_input('Draw!!!')
# print usr_draw
</code></pre>
| 1 |
2012-03-28T23:39:33Z
|
[
"python"
] |
Queryset API distinct() does not work?
| 453,477 |
<pre><code>class Message(models.Model):
subject = models.CharField(max_length=100)
pub_date = models.DateTimeField(default=datetime.now())
class Topic(models.Model):
title = models.CharField(max_length=100)
message = models.ManyToManyField(Message, verbose_name='Discussion')
</code></pre>
<p>I want to get order all the topics according to the latest message object attached to that topic.
I executed this query but this does not give the distinct queryset.</p>
<pre><code>>> Topic.objects.order_by('-message__pub_date').distinct()
</code></pre>
| 5 |
2009-01-17T15:49:11Z
| 460,702 |
<p>You'll find the explanation in the <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct" rel="nofollow">documentation for <code>.distinct()</code></a>.</p>
<p>I would de-normalize by adding a <code>modified_date</code> field to the <code>Topic</code> model and updating it whenever a Message is saved or deleted.</p>
| 3 |
2009-01-20T10:14:16Z
|
[
"python",
"django"
] |
Queryset API distinct() does not work?
| 453,477 |
<pre><code>class Message(models.Model):
subject = models.CharField(max_length=100)
pub_date = models.DateTimeField(default=datetime.now())
class Topic(models.Model):
title = models.CharField(max_length=100)
message = models.ManyToManyField(Message, verbose_name='Discussion')
</code></pre>
<p>I want to get order all the topics according to the latest message object attached to that topic.
I executed this query but this does not give the distinct queryset.</p>
<pre><code>>> Topic.objects.order_by('-message__pub_date').distinct()
</code></pre>
| 5 |
2009-01-17T15:49:11Z
| 476,232 |
<p>You don't need distinct() here, what you need is <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation">aggregation</a>. This query will do what you want:</p>
<pre><code>from django.db.models import Max
Topic.objects.annotate(Max('message__pub_date')).order_by('-message__pub_date__max')
</code></pre>
<p>Though if this is production code, you'll probably want to follow akaihola's advice and denormalize "last_message_posted" onto the Topic model directly.</p>
<p>Also, there's an error in your default value for Message.pub_date. As you have it now, whenever you first run the server and this code is loaded, datetime.now() will be executed once and that value will be used as the pub_date for all Messages. Use this instead to pass the callable itself so it isn't called until each Message is created:</p>
<pre><code>pub_date = models.DateTimeField(default=datetime.now)
</code></pre>
| 7 |
2009-01-24T16:16:07Z
|
[
"python",
"django"
] |
Is there a fast way to generate a dict of the alphabet in Python?
| 453,576 |
<p>I want to generate a dict with the letters of the alphabet as the keys, something like </p>
<pre><code>letter_count = {'a': 0, 'b': 0, 'c': 0}
</code></pre>
<p>what would be a fast way of generating that dict, rather than me having to type it in?</p>
<p>Thanks for your help.</p>
<p><b>EDIT</b><br>
Thanks everyone for your solutions :)</p>
<p><a href="http://stackoverflow.com/users/17160/nosklo">nosklo's</a>
<a href="http://stackoverflow.com/questions/453576/simple-python-question-is-there-a-fast-way-to-generate-a-dict-of-the-alphabet#453785">solution</a> is probably the shortest</p>
<p>Also, thanks for reminding me about the Python <a href="http://docs.python.org/library/string.html">string</a> module.</p>
| 24 |
2009-01-17T16:51:34Z
| 453,592 |
<p>There's this too:</p>
<pre><code>import string
letter_count = dict((letter, 0) for letter in string.ascii_lowercase)
</code></pre>
| 3 |
2009-01-17T16:59:54Z
|
[
"python",
"dictionary",
"alphabet"
] |
Is there a fast way to generate a dict of the alphabet in Python?
| 453,576 |
<p>I want to generate a dict with the letters of the alphabet as the keys, something like </p>
<pre><code>letter_count = {'a': 0, 'b': 0, 'c': 0}
</code></pre>
<p>what would be a fast way of generating that dict, rather than me having to type it in?</p>
<p>Thanks for your help.</p>
<p><b>EDIT</b><br>
Thanks everyone for your solutions :)</p>
<p><a href="http://stackoverflow.com/users/17160/nosklo">nosklo's</a>
<a href="http://stackoverflow.com/questions/453576/simple-python-question-is-there-a-fast-way-to-generate-a-dict-of-the-alphabet#453785">solution</a> is probably the shortest</p>
<p>Also, thanks for reminding me about the Python <a href="http://docs.python.org/library/string.html">string</a> module.</p>
| 24 |
2009-01-17T16:51:34Z
| 453,596 |
<p>Here's a compact version, using a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>
<pre><code>>>> import string
>>> letter_count = dict( (key, 0) for key in string.ascii_lowercase )
>>> letter_count
{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0,
'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0,
't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
</code></pre>
| 7 |
2009-01-17T17:01:01Z
|
[
"python",
"dictionary",
"alphabet"
] |
Is there a fast way to generate a dict of the alphabet in Python?
| 453,576 |
<p>I want to generate a dict with the letters of the alphabet as the keys, something like </p>
<pre><code>letter_count = {'a': 0, 'b': 0, 'c': 0}
</code></pre>
<p>what would be a fast way of generating that dict, rather than me having to type it in?</p>
<p>Thanks for your help.</p>
<p><b>EDIT</b><br>
Thanks everyone for your solutions :)</p>
<p><a href="http://stackoverflow.com/users/17160/nosklo">nosklo's</a>
<a href="http://stackoverflow.com/questions/453576/simple-python-question-is-there-a-fast-way-to-generate-a-dict-of-the-alphabet#453785">solution</a> is probably the shortest</p>
<p>Also, thanks for reminding me about the Python <a href="http://docs.python.org/library/string.html">string</a> module.</p>
| 24 |
2009-01-17T16:51:34Z
| 453,603 |
<pre><code>import string
letter_count = dict(zip(string.ascii_lowercase, [0]*26))
</code></pre>
<p>or maybe:</p>
<pre><code>import string
import itertools
letter_count = dict(zip(string.lowercase, itertools.repeat(0)))
</code></pre>
<p>or even:</p>
<pre><code>import string
letter_count = dict.fromkeys(string.ascii_lowercase, 0)
</code></pre>
<p>The preferred solution might be a different one, depending on the actual values you want in the dict.</p>
<hr>
<p>I'll take a guess here: do you want to count occurences of letters in a text (or something similar)? There is a better way to do this than starting with an initialized dictionary.</p>
<p>Use <code>Counter</code> from the <code>collections</code> module:</p>
<pre><code>>>> import collections
>>> the_text = 'the quick brown fox jumps over the lazy dog'
>>> letter_counts = collections.Counter(the_text)
>>> letter_counts
Counter({' ': 8, 'o': 4, 'e': 3, ... 'n': 1, 'x': 1, 'k': 1, 'b': 1})
</code></pre>
| 10 |
2009-01-17T17:03:27Z
|
[
"python",
"dictionary",
"alphabet"
] |
Is there a fast way to generate a dict of the alphabet in Python?
| 453,576 |
<p>I want to generate a dict with the letters of the alphabet as the keys, something like </p>
<pre><code>letter_count = {'a': 0, 'b': 0, 'c': 0}
</code></pre>
<p>what would be a fast way of generating that dict, rather than me having to type it in?</p>
<p>Thanks for your help.</p>
<p><b>EDIT</b><br>
Thanks everyone for your solutions :)</p>
<p><a href="http://stackoverflow.com/users/17160/nosklo">nosklo's</a>
<a href="http://stackoverflow.com/questions/453576/simple-python-question-is-there-a-fast-way-to-generate-a-dict-of-the-alphabet#453785">solution</a> is probably the shortest</p>
<p>Also, thanks for reminding me about the Python <a href="http://docs.python.org/library/string.html">string</a> module.</p>
| 24 |
2009-01-17T16:51:34Z
| 453,605 |
<pre><code>import string
letters = string.ascii_lowercase
d = dict(zip(letters, [0]*len(letters))
</code></pre>
| 2 |
2009-01-17T17:05:46Z
|
[
"python",
"dictionary",
"alphabet"
] |
Is there a fast way to generate a dict of the alphabet in Python?
| 453,576 |
<p>I want to generate a dict with the letters of the alphabet as the keys, something like </p>
<pre><code>letter_count = {'a': 0, 'b': 0, 'c': 0}
</code></pre>
<p>what would be a fast way of generating that dict, rather than me having to type it in?</p>
<p>Thanks for your help.</p>
<p><b>EDIT</b><br>
Thanks everyone for your solutions :)</p>
<p><a href="http://stackoverflow.com/users/17160/nosklo">nosklo's</a>
<a href="http://stackoverflow.com/questions/453576/simple-python-question-is-there-a-fast-way-to-generate-a-dict-of-the-alphabet#453785">solution</a> is probably the shortest</p>
<p>Also, thanks for reminding me about the Python <a href="http://docs.python.org/library/string.html">string</a> module.</p>
| 24 |
2009-01-17T16:51:34Z
| 453,761 |
<p>Yet another 1-liner Python hack:</p>
<pre><code>letter_count = dict([(chr(i),0) for i in range(97,123)])
</code></pre>
| 4 |
2009-01-17T18:17:54Z
|
[
"python",
"dictionary",
"alphabet"
] |
Is there a fast way to generate a dict of the alphabet in Python?
| 453,576 |
<p>I want to generate a dict with the letters of the alphabet as the keys, something like </p>
<pre><code>letter_count = {'a': 0, 'b': 0, 'c': 0}
</code></pre>
<p>what would be a fast way of generating that dict, rather than me having to type it in?</p>
<p>Thanks for your help.</p>
<p><b>EDIT</b><br>
Thanks everyone for your solutions :)</p>
<p><a href="http://stackoverflow.com/users/17160/nosklo">nosklo's</a>
<a href="http://stackoverflow.com/questions/453576/simple-python-question-is-there-a-fast-way-to-generate-a-dict-of-the-alphabet#453785">solution</a> is probably the shortest</p>
<p>Also, thanks for reminding me about the Python <a href="http://docs.python.org/library/string.html">string</a> module.</p>
| 24 |
2009-01-17T16:51:34Z
| 453,766 |
<p>If you plan to use it for counting, I suggest the following:</p>
<pre><code>import collections
d = collections.defaultdict(int)
</code></pre>
| 8 |
2009-01-17T18:19:27Z
|
[
"python",
"dictionary",
"alphabet"
] |
Is there a fast way to generate a dict of the alphabet in Python?
| 453,576 |
<p>I want to generate a dict with the letters of the alphabet as the keys, something like </p>
<pre><code>letter_count = {'a': 0, 'b': 0, 'c': 0}
</code></pre>
<p>what would be a fast way of generating that dict, rather than me having to type it in?</p>
<p>Thanks for your help.</p>
<p><b>EDIT</b><br>
Thanks everyone for your solutions :)</p>
<p><a href="http://stackoverflow.com/users/17160/nosklo">nosklo's</a>
<a href="http://stackoverflow.com/questions/453576/simple-python-question-is-there-a-fast-way-to-generate-a-dict-of-the-alphabet#453785">solution</a> is probably the shortest</p>
<p>Also, thanks for reminding me about the Python <a href="http://docs.python.org/library/string.html">string</a> module.</p>
| 24 |
2009-01-17T16:51:34Z
| 453,785 |
<p>I find this solution more elegant:</p>
<pre><code>import string
d = dict.fromkeys(string.ascii_lowercase, 0)
</code></pre>
| 43 |
2009-01-17T18:36:15Z
|
[
"python",
"dictionary",
"alphabet"
] |
Is there a Python news site that's the near equivalent of RubyFlow?
| 453,673 |
<p>I really like the format and type of links from <a href="http://rubyflow.com">RubyFlow</a> for Ruby related topics. Is there an equivalent for Python that's active? There is a <a href="http://pythonflow.com">PythonFlow</a>, but I think it's pretty much dead.</p>
<p>I don't really like <a href="http://planet.python.org/">http://planet.python.org/</a> because there's lots of non-Python stuff on there and there's very little summarization of posts.</p>
| 5 |
2009-01-17T17:41:14Z
| 453,680 |
<p>Possibly <a href="http://www.planetpython.org/" rel="nofollow">http://www.planetpython.org/</a> or <a href="http://planet.python.org/" rel="nofollow">http://planet.python.org/</a>.</p>
| 1 |
2009-01-17T17:44:13Z
|
[
"python",
"news"
] |
Is there a Python news site that's the near equivalent of RubyFlow?
| 453,673 |
<p>I really like the format and type of links from <a href="http://rubyflow.com">RubyFlow</a> for Ruby related topics. Is there an equivalent for Python that's active? There is a <a href="http://pythonflow.com">PythonFlow</a>, but I think it's pretty much dead.</p>
<p>I don't really like <a href="http://planet.python.org/">http://planet.python.org/</a> because there's lots of non-Python stuff on there and there's very little summarization of posts.</p>
| 5 |
2009-01-17T17:41:14Z
| 453,704 |
<p><a href="http://www.reddit.com/r/Python">http://www.reddit.com/r/Python</a> is my favorite source for Python news.</p>
| 5 |
2009-01-17T17:54:20Z
|
[
"python",
"news"
] |
Is there a Python news site that's the near equivalent of RubyFlow?
| 453,673 |
<p>I really like the format and type of links from <a href="http://rubyflow.com">RubyFlow</a> for Ruby related topics. Is there an equivalent for Python that's active? There is a <a href="http://pythonflow.com">PythonFlow</a>, but I think it's pretty much dead.</p>
<p>I don't really like <a href="http://planet.python.org/">http://planet.python.org/</a> because there's lots of non-Python stuff on there and there's very little summarization of posts.</p>
| 5 |
2009-01-17T17:41:14Z
| 453,705 |
<p><a href="http://planetpython.org/" rel="nofollow">http://planetpython.org/</a> (the unofficial planet) is generally better than <a href="http://planet.python.org/" rel="nofollow">http://planet.python.org/</a> (the official one) - I think the maintainers of the unofficial one are a bit more active in trimming feeds and maybe more careful about subscribing to Python category feeds if available (they certainly subscribe to the python tag on my blog rather than the whole feed).</p>
| 1 |
2009-01-17T17:54:29Z
|
[
"python",
"news"
] |
PYTHONSTARTUP doesn't seem to work
| 453,808 |
<p>I'm trying to use the PYTHONSTARTUP environmental variable. I set it to be "c:\python25\pythonstartup.py" in My Computer --> Advanced etc., and it doesn't seem to work.</p>
<p>Opening IDLE doesn't run the script, although it recognized the variable:</p>
<pre><code>>>> import os
>>> os.environ['PYTHONSTARTUP']
'c:\\python25\\pythonstartup.py'
>>>
</code></pre>
<p>I'm using XP and Python 2.5.2. I do not wish to upgrade to 3.0 yet.</p>
<p>Thanks</p>
| 5 |
2009-01-17T18:51:06Z
| 453,819 |
<p><a href="http://docs.python.org/using/cmdline.html">The documentation</a> says that PYTHONSTARTUP is only run for interactive sessions. I'm not sure how IDLE runs the Python interpreter, but it could be interfering.</p>
<p>Instead, try running <code>python</code> directly from a command prompt, rather than from clicking on an icon.</p>
| 5 |
2009-01-17T18:56:11Z
|
[
"python",
"startup"
] |
PYTHONSTARTUP doesn't seem to work
| 453,808 |
<p>I'm trying to use the PYTHONSTARTUP environmental variable. I set it to be "c:\python25\pythonstartup.py" in My Computer --> Advanced etc., and it doesn't seem to work.</p>
<p>Opening IDLE doesn't run the script, although it recognized the variable:</p>
<pre><code>>>> import os
>>> os.environ['PYTHONSTARTUP']
'c:\\python25\\pythonstartup.py'
>>>
</code></pre>
<p>I'm using XP and Python 2.5.2. I do not wish to upgrade to 3.0 yet.</p>
<p>Thanks</p>
| 5 |
2009-01-17T18:51:06Z
| 454,217 |
<p>To add to Greg Hewgill's correct answer: If IDLE doesn't have a startup file of its own, you can put a file called <a href="http://docs.python.org/dev/library/site.html" rel="nofollow"><code>sitecustomize.py</code></a> in your path which will be executed for both command prompt and scripts / IDLE sessions.</p>
| 2 |
2009-01-17T22:39:05Z
|
[
"python",
"startup"
] |
Invoke Python modules from Java
| 454,182 |
<p>I have a Python interface of a graph library written in C - igraph (the name of library). My need is to invoke the python modules pertaining to this graph library from Java code. It goes like this, the core of library is in c. This core has been imported into Python and interfaces to the functions embedded in core are available in Python. My project's rest of the code is in Java and hence I would like to call the graph functions by Java as well.
Jython - which lets you invoke python modules with in Java was an option.I went on trying Jython to discover that it will not work in my case as the core code is in C and Jython wont support anything that is imported as a c dll in python code.I also thought of opting for the approach of calling graph routines directly in c. That is without passing through Python code. I am assuming there must be something which lets you call c code from Java, how ever I am not good in C hence I did not go for it.
My last resort seems to execute Python interpreter from command line using Java. But that is a dirty and shameless. Also to deal with the results produced by Python code I will have to write the results in a file and read it back in java. Again dirty way.
Is there something that any one can suggest me? Thanks to every one giving time. </p>
<hr>
<p>Thanks Igal for answering. I had a look at it. At first glance it appears as if it is simply calling the python script. </p>
<pre><code>Jep jep = new Jep(false, SCRIPT_PATH, cl);
jep.set("query", query);
jep.runScript(SCRIPT_PATH + file);
jep.close();
</code></pre>
<p>Isnt it very similar to what we would do if called the python interpreter from command line through a Java code.</p>
<pre><code>Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("python test.py");
</code></pre>
<p>Concern is how do I use the results generated by Python script. The naive way is to write them to file and read it back in Java. I am searching for a smarter approach.Thanks for suggestion anyway.</p>
| 4 |
2009-01-17T22:22:30Z
| 454,211 |
<p>Never tried it. But I recently <a href="http://www.miketec.org/serendipity/index.php?/archives/9-Sure,-Change-Jobs!.html" rel="nofollow">stumbled</a> on a <a href="http://jepp.sourceforge.net/" rel="nofollow">project named Jepp</a> that may be of interest to you.</p>
<blockquote>
<p>Jepp embeds CPython in Java. It is safe to use in a heavily threaded environment, it is quite fast and its stability is a main feature and goal. </p>
</blockquote>
| 3 |
2009-01-17T22:36:17Z
|
[
"java",
"python",
"ipc"
] |
Invoke Python modules from Java
| 454,182 |
<p>I have a Python interface of a graph library written in C - igraph (the name of library). My need is to invoke the python modules pertaining to this graph library from Java code. It goes like this, the core of library is in c. This core has been imported into Python and interfaces to the functions embedded in core are available in Python. My project's rest of the code is in Java and hence I would like to call the graph functions by Java as well.
Jython - which lets you invoke python modules with in Java was an option.I went on trying Jython to discover that it will not work in my case as the core code is in C and Jython wont support anything that is imported as a c dll in python code.I also thought of opting for the approach of calling graph routines directly in c. That is without passing through Python code. I am assuming there must be something which lets you call c code from Java, how ever I am not good in C hence I did not go for it.
My last resort seems to execute Python interpreter from command line using Java. But that is a dirty and shameless. Also to deal with the results produced by Python code I will have to write the results in a file and read it back in java. Again dirty way.
Is there something that any one can suggest me? Thanks to every one giving time. </p>
<hr>
<p>Thanks Igal for answering. I had a look at it. At first glance it appears as if it is simply calling the python script. </p>
<pre><code>Jep jep = new Jep(false, SCRIPT_PATH, cl);
jep.set("query", query);
jep.runScript(SCRIPT_PATH + file);
jep.close();
</code></pre>
<p>Isnt it very similar to what we would do if called the python interpreter from command line through a Java code.</p>
<pre><code>Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("python test.py");
</code></pre>
<p>Concern is how do I use the results generated by Python script. The naive way is to write them to file and read it back in Java. I am searching for a smarter approach.Thanks for suggestion anyway.</p>
| 4 |
2009-01-17T22:22:30Z
| 2,512,480 |
<p>If you want to call C functions from Java, <a href="https://github.com/twall/jna/" rel="nofollow">JNA</a> (Java Native Access) is probably the way to go. JNA allows you to call functions in native libraries without having to write the C glue code (as you would have to when using JNI), and automatically maps between primitive data types in Java and C. A simple example might look like this:</p>
<pre><code>import com.sun.jna.Native;
import com.sun.jna.Library;
public class PrintfWrapper {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary)Native.loadLibrary("c", CLibrary.class);
void printf(String formatString, Object... args);
}
public static void main(String[] args) {
CLibrary.INSTANCE.printf("Hello, world\n");
}
}
</code></pre>
<p>However, things will get complicated with igraph because igraph uses many data structures that cannot be mapped directly into their Java counterparts. There is a project called <a href="http://jnaerator.googlecode.com/" rel="nofollow">JNAerator</a> which should be able to generate the JNA source from igraph's header files, but I have never tried it and chances are that the results will still need some manual tweaking.</p>
<p>Also note that a <a href="https://code.launchpad.net/~ntamas/igraph/0.6-java" rel="nofollow">Java interface for igraph</a> is being developed slowly but steadily and it might become useful in a few months or so.</p>
| 2 |
2010-03-25T00:54:15Z
|
[
"java",
"python",
"ipc"
] |
Invoke Python modules from Java
| 454,182 |
<p>I have a Python interface of a graph library written in C - igraph (the name of library). My need is to invoke the python modules pertaining to this graph library from Java code. It goes like this, the core of library is in c. This core has been imported into Python and interfaces to the functions embedded in core are available in Python. My project's rest of the code is in Java and hence I would like to call the graph functions by Java as well.
Jython - which lets you invoke python modules with in Java was an option.I went on trying Jython to discover that it will not work in my case as the core code is in C and Jython wont support anything that is imported as a c dll in python code.I also thought of opting for the approach of calling graph routines directly in c. That is without passing through Python code. I am assuming there must be something which lets you call c code from Java, how ever I am not good in C hence I did not go for it.
My last resort seems to execute Python interpreter from command line using Java. But that is a dirty and shameless. Also to deal with the results produced by Python code I will have to write the results in a file and read it back in java. Again dirty way.
Is there something that any one can suggest me? Thanks to every one giving time. </p>
<hr>
<p>Thanks Igal for answering. I had a look at it. At first glance it appears as if it is simply calling the python script. </p>
<pre><code>Jep jep = new Jep(false, SCRIPT_PATH, cl);
jep.set("query", query);
jep.runScript(SCRIPT_PATH + file);
jep.close();
</code></pre>
<p>Isnt it very similar to what we would do if called the python interpreter from command line through a Java code.</p>
<pre><code>Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("python test.py");
</code></pre>
<p>Concern is how do I use the results generated by Python script. The naive way is to write them to file and read it back in Java. I am searching for a smarter approach.Thanks for suggestion anyway.</p>
| 4 |
2009-01-17T22:22:30Z
| 12,167,871 |
<p>You can use jep.getValue() to retrieve a value from script's global dictionary.</p>
<p>There are caveats to that concerning scope levels in Python, so most people find it clearer to pass a Java class to python and set the return value in that instance in Python. After the script completes, the Java code will then have the result.</p>
<p>For example:</p>
<p>==> Java</p>
<pre><code>class ReturnValueClass {
public int scriptResult;
};
ReturnValueClass value = new ReturnValueClass();
jep.set("retval", value);
</code></pre>
<p>==> Python</p>
<pre><code># do something
pass
# write the return value
retval.scriptResult = some_python_value
</code></pre>
<p>==> Java</p>
<pre><code>System.out.println(value.scriptResult);
</code></pre>
<p>Hope that helps,</p>
<p>Mike (I wrote Jep)</p>
| 0 |
2012-08-28T21:37:21Z
|
[
"java",
"python",
"ipc"
] |
How to create a controller method in Turbogears that can be called from within the controller, or rendered with a template
| 454,223 |
<p>If you have a controller method like so:</p>
<pre><code>@expose("json")
def artists(self, action="view",artist_id=None):
artists=session.query(model.Artist).all()
return dict(artists=artists)
</code></pre>
<p>How can you call that method from within your controller class, and get the python dict back - rather than the json-encoded string of the dict (which requires you to decode it from json back into a python dict). Is it really necessary to write one function to get the data out of your model, and another to pack that data for use by the templates (KID, JSON)? Why is it that when you call this method from in the same class, e.g.:</p>
<pre><code>artists = self.artists()
</code></pre>
<p>You get a json string, when that's only appropriate if the method is called as part of a HTML request.
What have I missed?</p>
| 1 |
2009-01-17T22:43:53Z
| 454,380 |
<p>I normally approach this by having a 'worker' method, which queries the database, transforms results, etc., and a separate exposing method, with all the required decorators. E.g.:</p>
<pre><code># The _artists method can be used from any other method
def _artists(self, action, artist_id):
artists = session.query(model.Artist).all()
return dict(artists=artists)
@expose("json")
#@identity.require(identity.non_anonymous())
# error handlers, etc.
def artists(self, action="view", artist_id=None):
return self._artists(action=action, artist_id=artist_id)
</code></pre>
| 1 |
2009-01-18T00:28:06Z
|
[
"python",
"json",
"turbogears"
] |
How do cursors work in Python's DB-API?
| 454,337 |
<p>I have been using python with RDBMS' (MySQL and PostgreSQL), and I have noticed that I really do not understand how to use a cursor.</p>
<p>Usually, one have his script connect to the DB via a client DB-API (like psycopg2 or MySQLdb):</p>
<pre><code>connection = psycopg2.connect(host='otherhost', etc)
</code></pre>
<p>And then one creates a cursor:</p>
<pre><code>cursor = connection.cursor()
</code></pre>
<p>And then one can issue queries and commands:</p>
<pre><code>cursor.execute("SELECT * FROM etc")
</code></pre>
<p>Now where is the result of the query, I wonder? is it on the server? or a little on my client and a little on my server? And then, if we need to access some results, we fetch 'em:</p>
<pre><code>rows = cursor.fetchone()
</code></pre>
<p>or</p>
<pre><code>rows = cursor.fetchmany()
</code></pre>
<p>Now lets say, I do not retrieve all the rows, and decide to execute another query, what will happen to the previous results? Is their an overhead.</p>
<p>Also, should I create a cursor for every form of command and continuously reuse it for those same commands somehow; I head psycopg2 can somehow optimize commands that are executed many times but with different values, how and is it worth it?</p>
<p>Thx</p>
| 13 |
2009-01-17T23:58:21Z
| 454,350 |
<p>Assuming you're using PostgreSQL, the cursors probably are just implemented using the database's native cursor API. You may want to look at the source code for <a href="http://pybrary.net/pg8000/" rel="nofollow">pg8000</a>, a pure Python PostgreSQL DB-API module, to see how it handles cursors. You might also like to look at <a href="http://www.postgresql.org/docs/current/static/sql-declare.html" rel="nofollow">the PostgreSQL documentation for cursors</a>.</p>
| 1 |
2009-01-18T00:09:48Z
|
[
"python",
"performance",
"rdbms",
"cursors",
"psycopg2"
] |
How do cursors work in Python's DB-API?
| 454,337 |
<p>I have been using python with RDBMS' (MySQL and PostgreSQL), and I have noticed that I really do not understand how to use a cursor.</p>
<p>Usually, one have his script connect to the DB via a client DB-API (like psycopg2 or MySQLdb):</p>
<pre><code>connection = psycopg2.connect(host='otherhost', etc)
</code></pre>
<p>And then one creates a cursor:</p>
<pre><code>cursor = connection.cursor()
</code></pre>
<p>And then one can issue queries and commands:</p>
<pre><code>cursor.execute("SELECT * FROM etc")
</code></pre>
<p>Now where is the result of the query, I wonder? is it on the server? or a little on my client and a little on my server? And then, if we need to access some results, we fetch 'em:</p>
<pre><code>rows = cursor.fetchone()
</code></pre>
<p>or</p>
<pre><code>rows = cursor.fetchmany()
</code></pre>
<p>Now lets say, I do not retrieve all the rows, and decide to execute another query, what will happen to the previous results? Is their an overhead.</p>
<p>Also, should I create a cursor for every form of command and continuously reuse it for those same commands somehow; I head psycopg2 can somehow optimize commands that are executed many times but with different values, how and is it worth it?</p>
<p>Thx</p>
| 13 |
2009-01-17T23:58:21Z
| 454,825 |
<p>When you look here at the <a href="http://mysql-python.sourceforge.net/MySQLdb.html#cursor-objects" rel="nofollow">mysqldb documentation</a> you can see that they implemented different strategies for cursors. So the general answer is: it depends.</p>
<p>Edit: Here is the <a href="http://mysql-python.sourceforge.net/MySQLdb-1.2.2/" rel="nofollow">mysqldb API documentation</a>. There is some info how each cursor type is behaving. The standard cursor is storing the result set in the client. So I assume there is a overhead if you don't retrieve all result rows, because even the rows you don't fetch have to be transfered to the client (potentially over the network). My guess is that it is not that different from postgresql.</p>
<p>When you want to optimize SQL statements that you call repeatedly with many values, you should look at cursor.executemany(). It prepares a SQL statement so that it doesn't need to be parsed every time you call it:</p>
<pre><code>cur.executemany('INSERT INTO mytable (col1, col2) VALUES (%s, %s)',
[('val1', 1), ('val2', 2)])
</code></pre>
| 1 |
2009-01-18T08:38:08Z
|
[
"python",
"performance",
"rdbms",
"cursors",
"psycopg2"
] |
How do cursors work in Python's DB-API?
| 454,337 |
<p>I have been using python with RDBMS' (MySQL and PostgreSQL), and I have noticed that I really do not understand how to use a cursor.</p>
<p>Usually, one have his script connect to the DB via a client DB-API (like psycopg2 or MySQLdb):</p>
<pre><code>connection = psycopg2.connect(host='otherhost', etc)
</code></pre>
<p>And then one creates a cursor:</p>
<pre><code>cursor = connection.cursor()
</code></pre>
<p>And then one can issue queries and commands:</p>
<pre><code>cursor.execute("SELECT * FROM etc")
</code></pre>
<p>Now where is the result of the query, I wonder? is it on the server? or a little on my client and a little on my server? And then, if we need to access some results, we fetch 'em:</p>
<pre><code>rows = cursor.fetchone()
</code></pre>
<p>or</p>
<pre><code>rows = cursor.fetchmany()
</code></pre>
<p>Now lets say, I do not retrieve all the rows, and decide to execute another query, what will happen to the previous results? Is their an overhead.</p>
<p>Also, should I create a cursor for every form of command and continuously reuse it for those same commands somehow; I head psycopg2 can somehow optimize commands that are executed many times but with different values, how and is it worth it?</p>
<p>Thx</p>
| 13 |
2009-01-17T23:58:21Z
| 967,713 |
<p>ya, i know it's months old :P</p>
<p>DB-API's cursor appears to be closely modeled after SQL cursors. AFA resource(rows) management is concerned, <em>DB-API does not specify whether the client must retrieve all the rows or DECLARE an actual SQL cursor</em>. As long as the fetchXXX interfaces do what they're supposed to, DB-API is happy.</p>
<p>AFA psycopg2 cursors are concerned(as you may well know), "unnamed DB-API cursors" will fetch the entire result set--AFAIK buffered in memory by libpq. "named DB-API cursors"(a psycopg2 concept that may not be portable), will request the rows on demand(fetchXXX methods).</p>
<p>As cited by "unbeknown", executemany can be used to optimize multiple runs of the same command. However, it doesn't accommodate for the need of prepared statements; when repeat executions of a statement with different parameter sets is not directly sequential, executemany() will perform just as well as execute(). DB-API does "provide" driver authors with the ability to cache executed statements, but its implementation(what's the scope/lifetime of the statement?) is undefined, so it's impossible to set expectations across DB-API implementations.</p>
<p>If you are loading lots of data into PostgreSQL, I would strongly recommend trying to find a way to use COPY.</p>
| 3 |
2009-06-09T00:57:50Z
|
[
"python",
"performance",
"rdbms",
"cursors",
"psycopg2"
] |
Does Django development provide a truly flexible 3 layer architecture?
| 454,443 |
<p>A few weeks ago I asked the question <em>"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"</em> <a href="http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application">http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application</a></p>
<p>A lot of the answers recommended skipping the <strong>PHP</strong> piece and using <strong>Django</strong> to build the application. As I've explored Django, I've started to question one specific aspect of my goals and how Django comes into play for <strong>a non-web business application</strong>.</p>
<p>Based on my understanding, Django would manage both the view and controller pieces and <strong>PostgreSQL</strong> or <strong>MySQL</strong> would handle the data. But my goal was to clearly separate the layers so that the database, domain logic, and presentation could each be changed without significantly affecting the others. It seems like I'm only separating the M from the VC layers with the Django solution.</p>
<p>So, is it counterproductive for me to build the domain layer in <strong>Python</strong> with an <strong>SQL Alchemy/Elixir ORM tool</strong>, <strong>PostgreSQL</strong> for the database layer, and then still use <strong>Django</strong> or <strong>PHP</strong> for the presentation layer? Is this possible or pure insanity?</p>
<p>Basically, I'd be looking at an architecture of <strong>Django/PHP > Python/SQLAlchemy > PostgreSQL/MySQL</strong>.</p>
<p><em>Edit: Before the fanboys get mad at me for asking a question about Django, just realize: It's a question, not an accusation. If I knew the answer or had my own opinion, I wouldn't have asked!</em></p>
| 3 |
2009-01-18T01:20:33Z
| 454,458 |
<p>You've effectively got a 3 layer architecture whether you use Django's ORM or SQLAlchemy, though your forgo some of the Django's benefits if you choose the latter.</p>
| 3 |
2009-01-18T01:29:36Z
|
[
"python",
"django",
"model-view-controller",
"orm"
] |
Does Django development provide a truly flexible 3 layer architecture?
| 454,443 |
<p>A few weeks ago I asked the question <em>"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"</em> <a href="http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application">http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application</a></p>
<p>A lot of the answers recommended skipping the <strong>PHP</strong> piece and using <strong>Django</strong> to build the application. As I've explored Django, I've started to question one specific aspect of my goals and how Django comes into play for <strong>a non-web business application</strong>.</p>
<p>Based on my understanding, Django would manage both the view and controller pieces and <strong>PostgreSQL</strong> or <strong>MySQL</strong> would handle the data. But my goal was to clearly separate the layers so that the database, domain logic, and presentation could each be changed without significantly affecting the others. It seems like I'm only separating the M from the VC layers with the Django solution.</p>
<p>So, is it counterproductive for me to build the domain layer in <strong>Python</strong> with an <strong>SQL Alchemy/Elixir ORM tool</strong>, <strong>PostgreSQL</strong> for the database layer, and then still use <strong>Django</strong> or <strong>PHP</strong> for the presentation layer? Is this possible or pure insanity?</p>
<p>Basically, I'd be looking at an architecture of <strong>Django/PHP > Python/SQLAlchemy > PostgreSQL/MySQL</strong>.</p>
<p><em>Edit: Before the fanboys get mad at me for asking a question about Django, just realize: It's a question, not an accusation. If I knew the answer or had my own opinion, I wouldn't have asked!</em></p>
| 3 |
2009-01-18T01:20:33Z
| 454,539 |
<p>You seem to be saying that choosing Django would prevent you from using a more heterogenous solution later. This isn't the case. Django provides a number of interesting connections between the layers, and using Django for all the layers lets you take advantage of those connections. For example, using the Django ORM means that you get the great Django admin app almost for free.</p>
<p>You can choose to use a different ORM within Django, you just won't get the admin app (or generic views, for example) along with it. So a different ORM takes you a step backward from full Django top-to-bottom, but it isn't a step backward from other heterogenous solutions, because those solutions didn't give you intra-layer goodness the admin app in the first place.</p>
<p>Django shouldn't be criticized for not providing a flexible architecture: it's as flexible as any other solution, you just forgo some of the Django benefits if you choose to swap out a layer.</p>
<p>If you choose to start with Django, you can use the Django ORM now, and then later, if you need to switch, you can change over to SQLalchemy. That will be no more difficult than starting with SQLalchemy now and later moving to some other ORM solution.</p>
<p>You haven't said why you anticipate needing to swap out layers. It will be a painful process no matter what, because there is necessarily much code that relies on the behavior of whichever toolset and library you're currently using.</p>
| 9 |
2009-01-18T02:41:38Z
|
[
"python",
"django",
"model-view-controller",
"orm"
] |
Does Django development provide a truly flexible 3 layer architecture?
| 454,443 |
<p>A few weeks ago I asked the question <em>"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"</em> <a href="http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application">http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application</a></p>
<p>A lot of the answers recommended skipping the <strong>PHP</strong> piece and using <strong>Django</strong> to build the application. As I've explored Django, I've started to question one specific aspect of my goals and how Django comes into play for <strong>a non-web business application</strong>.</p>
<p>Based on my understanding, Django would manage both the view and controller pieces and <strong>PostgreSQL</strong> or <strong>MySQL</strong> would handle the data. But my goal was to clearly separate the layers so that the database, domain logic, and presentation could each be changed without significantly affecting the others. It seems like I'm only separating the M from the VC layers with the Django solution.</p>
<p>So, is it counterproductive for me to build the domain layer in <strong>Python</strong> with an <strong>SQL Alchemy/Elixir ORM tool</strong>, <strong>PostgreSQL</strong> for the database layer, and then still use <strong>Django</strong> or <strong>PHP</strong> for the presentation layer? Is this possible or pure insanity?</p>
<p>Basically, I'd be looking at an architecture of <strong>Django/PHP > Python/SQLAlchemy > PostgreSQL/MySQL</strong>.</p>
<p><em>Edit: Before the fanboys get mad at me for asking a question about Django, just realize: It's a question, not an accusation. If I knew the answer or had my own opinion, I wouldn't have asked!</em></p>
| 3 |
2009-01-18T01:20:33Z
| 454,551 |
<blockquote>
<p>Based on my understanding, Django would manage both the view and controller pieces and PostgreSQL or MySQL would handle the data.</p>
</blockquote>
<p>Not really, Django has its own ORM, so it does separate data from view/controller.</p>
<p>here's an <a href="http://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names" rel="nofollow">entry from the official FAQ</a> about MVC:</p>
<blockquote>
<p>Where does the âcontrollerâ fit in, then? In Djangoâs case, itâs probably the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration.</p>
<p>If youâre hungry for acronyms, you might say that Django is a âMTVâ framework â that is, âmodelâ, âtemplateâ, and âview.â That breakdown makes much more sense.</p>
<p>At the end of the day, of course, it comes down to getting stuff done. And, regardless of how things are named, Django gets stuff done in a way thatâs most logical to us.</p>
</blockquote>
| 3 |
2009-01-18T02:52:58Z
|
[
"python",
"django",
"model-view-controller",
"orm"
] |
Does Django development provide a truly flexible 3 layer architecture?
| 454,443 |
<p>A few weeks ago I asked the question <em>"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"</em> <a href="http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application">http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application</a></p>
<p>A lot of the answers recommended skipping the <strong>PHP</strong> piece and using <strong>Django</strong> to build the application. As I've explored Django, I've started to question one specific aspect of my goals and how Django comes into play for <strong>a non-web business application</strong>.</p>
<p>Based on my understanding, Django would manage both the view and controller pieces and <strong>PostgreSQL</strong> or <strong>MySQL</strong> would handle the data. But my goal was to clearly separate the layers so that the database, domain logic, and presentation could each be changed without significantly affecting the others. It seems like I'm only separating the M from the VC layers with the Django solution.</p>
<p>So, is it counterproductive for me to build the domain layer in <strong>Python</strong> with an <strong>SQL Alchemy/Elixir ORM tool</strong>, <strong>PostgreSQL</strong> for the database layer, and then still use <strong>Django</strong> or <strong>PHP</strong> for the presentation layer? Is this possible or pure insanity?</p>
<p>Basically, I'd be looking at an architecture of <strong>Django/PHP > Python/SQLAlchemy > PostgreSQL/MySQL</strong>.</p>
<p><em>Edit: Before the fanboys get mad at me for asking a question about Django, just realize: It's a question, not an accusation. If I knew the answer or had my own opinion, I wouldn't have asked!</em></p>
| 3 |
2009-01-18T01:20:33Z
| 454,608 |
<p>Django will happily let you use whatever libraries you want for whatever you want to use them for -- you want a different ORM, use it, you want a different template engine, use it, and so on -- but is designed to provide a common default stack used by many interoperable applications. In other words, if you swap out an ORM or a template system, you'll lose compatibility with a lot of applications, but the ability to take advantage of a large base of applications typically outweighs this.</p>
<p>In broader terms, however, I'd advise you to spend a bit more time reading up on architectural patterns for web applications, since you seem to have some major conceptual confusion going on. One might just as easily say that, for example, Rails doesn't have a "view" layer since you could use different file systems as the storage location for the view code (in other words: being able to change where and how the data is stored by your model layer doesn't mean you don't <em>have</em> a model layer).</p>
<p>(and it goes without saying that it's also important to know why "strict" or "pure" MVC is an absolutely <em>horrid</em> fit for web applications; MVC in its pure form is useful for applications with many independent ways to initiate interaction, like a word processor with lots of toolbars and input panes, but its benefits quickly start to disappear when you move to the web and have only one way -- an HTTP request -- to interact with the application. This is why there are no "true" MVC web frameworks; they all borrow certain ideas about separation of concerns, but none of them implement the pattern strictly)</p>
| 7 |
2009-01-18T03:48:18Z
|
[
"python",
"django",
"model-view-controller",
"orm"
] |
Does Django development provide a truly flexible 3 layer architecture?
| 454,443 |
<p>A few weeks ago I asked the question <em>"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"</em> <a href="http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application">http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application</a></p>
<p>A lot of the answers recommended skipping the <strong>PHP</strong> piece and using <strong>Django</strong> to build the application. As I've explored Django, I've started to question one specific aspect of my goals and how Django comes into play for <strong>a non-web business application</strong>.</p>
<p>Based on my understanding, Django would manage both the view and controller pieces and <strong>PostgreSQL</strong> or <strong>MySQL</strong> would handle the data. But my goal was to clearly separate the layers so that the database, domain logic, and presentation could each be changed without significantly affecting the others. It seems like I'm only separating the M from the VC layers with the Django solution.</p>
<p>So, is it counterproductive for me to build the domain layer in <strong>Python</strong> with an <strong>SQL Alchemy/Elixir ORM tool</strong>, <strong>PostgreSQL</strong> for the database layer, and then still use <strong>Django</strong> or <strong>PHP</strong> for the presentation layer? Is this possible or pure insanity?</p>
<p>Basically, I'd be looking at an architecture of <strong>Django/PHP > Python/SQLAlchemy > PostgreSQL/MySQL</strong>.</p>
<p><em>Edit: Before the fanboys get mad at me for asking a question about Django, just realize: It's a question, not an accusation. If I knew the answer or had my own opinion, I wouldn't have asked!</em></p>
| 3 |
2009-01-18T01:20:33Z
| 455,086 |
<p>There's change and there's change. Django utterly seperates domain model, business rules and presentation. You can change (almost) anything with near zero breakage. And by change I am talking about meaningful end-user focused business change.</p>
<p>The technology mix-n-match in this (and the previous) question isn't really very helpful. </p>
<p>Who -- specifically -- benefits from replacing Django templates with PHP. It's not more productive. It's more complex for no benefit. Who benefits from changing ORM's. The users won't and can't tell. </p>
| -1 |
2009-01-18T12:58:43Z
|
[
"python",
"django",
"model-view-controller",
"orm"
] |
Does Django development provide a truly flexible 3 layer architecture?
| 454,443 |
<p>A few weeks ago I asked the question <em>"Is a PHP, Python, PostgreSQL design suitable for a non-web business application?"</em> <a href="http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application">http://stackoverflow.com/questions/439759/is-a-php-python-postgresql-design-suitable-for-a-business-application</a></p>
<p>A lot of the answers recommended skipping the <strong>PHP</strong> piece and using <strong>Django</strong> to build the application. As I've explored Django, I've started to question one specific aspect of my goals and how Django comes into play for <strong>a non-web business application</strong>.</p>
<p>Based on my understanding, Django would manage both the view and controller pieces and <strong>PostgreSQL</strong> or <strong>MySQL</strong> would handle the data. But my goal was to clearly separate the layers so that the database, domain logic, and presentation could each be changed without significantly affecting the others. It seems like I'm only separating the M from the VC layers with the Django solution.</p>
<p>So, is it counterproductive for me to build the domain layer in <strong>Python</strong> with an <strong>SQL Alchemy/Elixir ORM tool</strong>, <strong>PostgreSQL</strong> for the database layer, and then still use <strong>Django</strong> or <strong>PHP</strong> for the presentation layer? Is this possible or pure insanity?</p>
<p>Basically, I'd be looking at an architecture of <strong>Django/PHP > Python/SQLAlchemy > PostgreSQL/MySQL</strong>.</p>
<p><em>Edit: Before the fanboys get mad at me for asking a question about Django, just realize: It's a question, not an accusation. If I knew the answer or had my own opinion, I wouldn't have asked!</em></p>
| 3 |
2009-01-18T01:20:33Z
| 456,085 |
<p>You seem to be confusing "separate layers" with "separate languages/technologies." There is no reason you can't separate your concerns appropriately within a single programming language, or within an appropriately modular framework (such as Django). Needlessly multiplying programming languages / frameworks is just needlessly multiplying complexity, which is likely to slow down your initial efforts so much that your project will never reach the point where it needs a technology switch.</p>
| 4 |
2009-01-18T23:06:07Z
|
[
"python",
"django",
"model-view-controller",
"orm"
] |
How do I re.search or re.match on a whole file without reading it all into memory?
| 454,456 |
<p>I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks!</p>
<p><strong>Clarification:</strong> I cannot read line-by-line because it can span multiple lines.</p>
| 19 |
2009-01-18T01:27:16Z
| 454,468 |
<p>This depends on the file and the regex. The best thing you could do would be to read the file in line by line but if that does not work for your situation then might get stuck with pulling the whole file into memory.</p>
<p>Lets say for example that this is your file:</p>
<pre><code>Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Ut fringilla pede blandit
eros sagittis viverra. Curabitur facilisis
urna ABC elementum lacus molestie aliquet.
Vestibulum lobortis semper risus. Etiam
sollicitudin. Vivamus posuere mauris eu
nulla. Nunc nisi. Curabitur fringilla fringilla
elit. Nullam feugiat, metus et suscipit
fermentum, mauris ipsum blandit purus,
non vehicula purus felis sit amet tortor.
Vestibulum odio. Mauris dapibus ultricies
metus. Cras XYZ eu lectus. Cras elit turpis,
ultrices nec, commodo eu, sodales non, erat.
Quisque accumsan, nunc nec porttitor vulputate,
erat dolor suscipit quam, a tristique justo
turpis at erat.
</code></pre>
<p>And this was your regex:</p>
<pre><code>consectetur(?=\sadipiscing)
</code></pre>
<p>Now this regex uses <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">positive lookahead</a> and will only match a string of "consectetur" if it is immediately followed by any whitepace character and then a string of "adipiscing".</p>
<p>So in this example you would have to read the whole file into memory because your regex is depending on the entire file being parsed as a single string. This is one of many examples that would require you to have your entire string in memory for a particular regex to work.</p>
<p>I guess the unfortunate answer is that it all depends on your situation.</p>
| 4 |
2009-01-18T01:42:26Z
|
[
"python",
"regex",
"performance",
"file"
] |
How do I re.search or re.match on a whole file without reading it all into memory?
| 454,456 |
<p>I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks!</p>
<p><strong>Clarification:</strong> I cannot read line-by-line because it can span multiple lines.</p>
| 19 |
2009-01-18T01:27:16Z
| 454,471 |
<p>For single line patterns you can iterate over the lines of the file, but for multi-line patterns, You will have to read all (or part, but that'll be hard to keep track of) of the file into memory.</p>
| 0 |
2009-01-18T01:44:49Z
|
[
"python",
"regex",
"performance",
"file"
] |
How do I re.search or re.match on a whole file without reading it all into memory?
| 454,456 |
<p>I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks!</p>
<p><strong>Clarification:</strong> I cannot read line-by-line because it can span multiple lines.</p>
| 19 |
2009-01-18T01:27:16Z
| 454,474 |
<p>Open the file and iterate over the lines.</p>
<pre><code>fd = open('myfile')
for line in fd:
if re.match(...,line)
print line
</code></pre>
| 0 |
2009-01-18T01:46:43Z
|
[
"python",
"regex",
"performance",
"file"
] |
How do I re.search or re.match on a whole file without reading it all into memory?
| 454,456 |
<p>I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks!</p>
<p><strong>Clarification:</strong> I cannot read line-by-line because it can span multiple lines.</p>
| 19 |
2009-01-18T01:27:16Z
| 454,490 |
<p>This is one way:</p>
<pre><code>import re
REGEX = '\d+'
with open('/tmp/workfile', 'r') as f:
for line in f:
print re.match(REGEX,line)
</code></pre>
<ol>
<li>with operator in python 2.5 takes of automatic file closure. Hence you need not worry about it.</li>
<li>iterator over the file object is memory efficient. that is it wont read more than a line of memory at a given time.</li>
<li>But the draw back of this approach is that it would take a lot of time for huge files.</li>
</ol>
<p>Another approach which comes to my mind is to use read(size) and file.seek(offset) method, which will read a portion of the file size at a time.</p>
<pre><code>import re
REGEX = '\d+'
with open('/tmp/workfile', 'r') as f:
filesize = f.size()
part = filesize / 10 # a suitable size that you can determine ahead or in the prog.
position = 0
while position <= filesize:
content = f.read(part)
print re.match(REGEX,content)
position = position + part
f.seek(position)
</code></pre>
<p>You can also combine these two there you can create generator that would return contents a certain bytes at the time and iterate through that content to check your regex. This IMO would be a good approach.</p>
| 0 |
2009-01-18T02:00:41Z
|
[
"python",
"regex",
"performance",
"file"
] |
How do I re.search or re.match on a whole file without reading it all into memory?
| 454,456 |
<p>I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks!</p>
<p><strong>Clarification:</strong> I cannot read line-by-line because it can span multiple lines.</p>
| 19 |
2009-01-18T01:27:16Z
| 454,535 |
<p>If this is a big deal and worth some effort, you can convert the regular expression into a finite state machine which reads the file. The FSM can be of O(n) complexity which means it will be a lot faster as the file size gets big.</p>
<p>You will be able to efficiently match patterns that span lines in files too large to fit in memory.</p>
<p>Here are two places that describe the algorithm for converting a regular expression to a FSM:</p>
<ul>
<li><a href="http://swtch.com/~rsc/regexp/regexp1.html" rel="nofollow">http://swtch.com/~rsc/regexp/regexp1.html</a></li>
<li><a href="http://www.math.grin.edu/~rebelsky/Courses/CS362/98F/Outlines/outline.07.html" rel="nofollow">http://www.math.grin.edu/~rebelsky/Courses/CS362/98F/Outlines/outline.07.html</a></li>
</ul>
| 1 |
2009-01-18T02:39:06Z
|
[
"python",
"regex",
"performance",
"file"
] |
How do I re.search or re.match on a whole file without reading it all into memory?
| 454,456 |
<p>I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks!</p>
<p><strong>Clarification:</strong> I cannot read line-by-line because it can span multiple lines.</p>
| 19 |
2009-01-18T01:27:16Z
| 454,589 |
<p>You can use mmap to map the file to memory. The file contents can then be accessed like a normal string:</p>
<pre><code>import re, mmap
with open('/var/log/error.log', 'r+') as f:
data = mmap.mmap(f.fileno(), 0)
mo = re.search('error: (.*)', data)
if mo:
print "found error", mo.group(1)
</code></pre>
<p>This also works for big files, the file content is internally loaded from disk as needed.</p>
| 39 |
2009-01-18T03:24:46Z
|
[
"python",
"regex",
"performance",
"file"
] |
How do I re.search or re.match on a whole file without reading it all into memory?
| 454,456 |
<p>I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks!</p>
<p><strong>Clarification:</strong> I cannot read line-by-line because it can span multiple lines.</p>
| 19 |
2009-01-18T01:27:16Z
| 28,010,463 |
<pre><code>f = open(filename,'r')
for eachline in f:
string=re.search("(<tr align=\"right\"><td>)([0-9]*)(</td><td>)([a-zA-Z]*)(</td><td>)([a-zA-Z]*)(</td>)",eachline)
if string:
for i in range (2,8,2):
add = string.group(i)
l.append(add)
</code></pre>
| 0 |
2015-01-18T13:56:39Z
|
[
"python",
"regex",
"performance",
"file"
] |
Find an Image within an Image
| 454,498 |
<p>I am looking for the best way to detect an image within another image. I have a small image and would like to find the location that it appears within a larger image - which will actually be screen captures. Conceptually, it is like a 'Where's Waldo?' sort of search in the larger image. </p>
<p>Are there any efficient/quick ways to accomplish this? Speed is more important than memory.</p>
<p>Edit: </p>
<p>The 'inner' image may not always have the same scale but will have the same rotation. </p>
<p>It is not safe to assume that the image will be perfectly contained within the other, pixel for pixel.</p>
| 4 |
2009-01-18T02:07:16Z
| 454,505 |
<p>You can treat this as a substring problem, where characters in the alphabet are pixels and your string is the image. You would need also to use a special character in a similar vein to a linebreak, to denote the image boundary.</p>
<p>The algorithm you want is on wikipedia: <a href="http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm</a></p>
<p><strong>Update:</strong> If you cannot assume that the image is perfectly contained within the other, pixel for pixel, then this approach will not work. </p>
<p>There are other, more complicated algorithms based on the same dynamic programming concept as the above, but I won't go into them unless it's necessary.</p>
| 0 |
2009-01-18T02:11:56Z
|
[
"java",
"python",
"image"
] |
Find an Image within an Image
| 454,498 |
<p>I am looking for the best way to detect an image within another image. I have a small image and would like to find the location that it appears within a larger image - which will actually be screen captures. Conceptually, it is like a 'Where's Waldo?' sort of search in the larger image. </p>
<p>Are there any efficient/quick ways to accomplish this? Speed is more important than memory.</p>
<p>Edit: </p>
<p>The 'inner' image may not always have the same scale but will have the same rotation. </p>
<p>It is not safe to assume that the image will be perfectly contained within the other, pixel for pixel.</p>
| 4 |
2009-01-18T02:07:16Z
| 454,536 |
<p>Wikipedia has an article on <a href="http://en.wikipedia.org/wiki/Template_matching">Template Matching</a>, with sample code.</p>
<p>(While that page doesn't handle changed scales, it has links to other styles of matching, for example <a href="http://en.wikipedia.org/wiki/Scale-invariant_feature_transform">Scale invariant feature transform</a>)</p>
| 7 |
2009-01-18T02:40:21Z
|
[
"java",
"python",
"image"
] |
Find an Image within an Image
| 454,498 |
<p>I am looking for the best way to detect an image within another image. I have a small image and would like to find the location that it appears within a larger image - which will actually be screen captures. Conceptually, it is like a 'Where's Waldo?' sort of search in the larger image. </p>
<p>Are there any efficient/quick ways to accomplish this? Speed is more important than memory.</p>
<p>Edit: </p>
<p>The 'inner' image may not always have the same scale but will have the same rotation. </p>
<p>It is not safe to assume that the image will be perfectly contained within the other, pixel for pixel.</p>
| 4 |
2009-01-18T02:07:16Z
| 454,548 |
<p>If rotation also had to be catered for, the <a href="http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm" rel="nofollow">Generalised Hough Transform</a> can be used.</p>
| 1 |
2009-01-18T02:50:12Z
|
[
"java",
"python",
"image"
] |
How can I make a list in Python like (0,6,12, .. 144)?
| 454,566 |
<p>I am not sure, whether I should use for -loop. Perhaps, like </p>
<pre><code>for i in range(145):
by 6: //mistake here?
print i
</code></pre>
| 3 |
2009-01-18T03:04:43Z
| 454,569 |
<p>I would prefer:</p>
<pre><code>for i in xrange(25): # from 0 to 24
print 6*i
</code></pre>
<p>You can easily build a list containing the same numbers with a similar construct named <em>list comprehension</em>:</p>
<pre><code>numbers = [6*i for i in xrange(25)]
print numbers
</code></pre>
<p>If you already have a list of (unknown) numbers, say <code>someNumbers</code>, but you want to print only those which are multiples of 6:</p>
<pre><code>for i in someNumbers:
if i%6 == 0:
print i
</code></pre>
| 6 |
2009-01-18T03:06:20Z
|
[
"python",
"list"
] |
How can I make a list in Python like (0,6,12, .. 144)?
| 454,566 |
<p>I am not sure, whether I should use for -loop. Perhaps, like </p>
<pre><code>for i in range(145):
by 6: //mistake here?
print i
</code></pre>
| 3 |
2009-01-18T03:04:43Z
| 454,578 |
<pre><code>for i in range(0,150,6):
print i
</code></pre>
<p>if you are stepping by a constant</p>
| 20 |
2009-01-18T03:11:14Z
|
[
"python",
"list"
] |
How can I make a list in Python like (0,6,12, .. 144)?
| 454,566 |
<p>I am not sure, whether I should use for -loop. Perhaps, like </p>
<pre><code>for i in range(145):
by 6: //mistake here?
print i
</code></pre>
| 3 |
2009-01-18T03:04:43Z
| 454,580 |
<pre><code>i = 1
while i * 6 < 144:
i = i + 1
print i * 6
</code></pre>
<p>There are plenty of ways to do this</p>
| -5 |
2009-01-18T03:12:32Z
|
[
"python",
"list"
] |
How can I make a list in Python like (0,6,12, .. 144)?
| 454,566 |
<p>I am not sure, whether I should use for -loop. Perhaps, like </p>
<pre><code>for i in range(145):
by 6: //mistake here?
print i
</code></pre>
| 3 |
2009-01-18T03:04:43Z
| 454,584 |
<p>reqlist = [i for i in range(0,150,6)]</p>
| -2 |
2009-01-18T03:16:11Z
|
[
"python",
"list"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 460,594 |
<p>This is the current mechanism for defining syntax by use of a standard Python class.</p>
<p>Print macro:</p>
<pre><code>class PrintMacro(Macro):
syntax = 'print', Var
def handle(self, stmts):
if not isinstance(stmts, list):
stmts = [stmts]
return Printnl(stmts, None)
</code></pre>
<p>If/elif/else macro class:</p>
<pre><code>class IfMacro(MLMacro):
syntax = (
('if', Var, Var),
ZeroOrMore('elif', Var, Var),
Optional('else', Var)
)
def handle(self, if_, elifs, elseBody):
return If(
[(cond, Stmt(body)) for cond, body in [if_] + elifs],
elseBody != None and Stmt(elseBody) or None
)
</code></pre>
<p>X to Y [inclusive] [step Z] macro class:</p>
<pre><code>class ToMacro(PartialMacro):
syntax = Var, 'to', Var, Optional('inclusive'), Optional('step', Var)
def handle(self, start, end, inclusive, step):
if inclusive:
end = ['(', end, '+', Number(1), ')']
if step == None: step = Number(1)
return ['xrange', ['(', start, end, step, ')']]
</code></pre>
<p>My issues with this design is that things are very verbose and don't feel pythonic in the least. In addition, the lack of quotation ability makes complex macros difficult.</p>
| 0 |
2009-01-20T09:37:13Z
|
[
"python",
"syntax",
"macros"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 460,598 |
<p>This is the macro syntax I've come up with for my Python superset.</p>
<p>Print macro:</p>
<pre><code>macro PrintMacro:
syntax:
stmts = 'print', Var
if not isinstance(stmts, list):
stmts = [stmts]
return Printnl(stmts, None)
</code></pre>
<p>If macro:</p>
<pre><code>@MultiLine
macro IfMacro:
syntax:
if_ = 'if', Var, Var
elifs = ZeroOrMore('elif', Var, Var)
else_ = Optional('else', Var)
return If(
[(cond, Stmt(body)) for cond, body in [if_] + elifs],
elseBody != None and Stmt(elseBody) or None
)
</code></pre>
<p>X to Y [inclusive] [step Z] macro:</p>
<pre><code>@Partial
macro ToMacro:
syntax:
start = Var
'to'
end = Var
inclusive = Optional('inclusive')
step = Optional('step', Var)
if step == None:
step = quote 1
if inclusive:
return quote:
xrange($start, $end+1, $step)
else:
return quote:
xrange($start, $end, $step)
</code></pre>
<p>My primary issue with this is that the syntax block is unclear, particularly the 'to' line in the last example. I'm also not a big fan of using decorators to differentiate macro types.</p>
| 0 |
2009-01-20T09:38:34Z
|
[
"python",
"syntax",
"macros"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 460,670 |
<p>I'm posting a bit of floating ideas to see if it inspires.
I don't know much python, and I'm not using real python syntax, but it beats nothing :p</p>
<pre><code>macro PrintMacro:
syntax:
print $a
rules:
a: list(String), as vars
handle:
# do something with 'vars'
macro IfMacro:
syntax:
if $a :
$b
$c
rules:
a: 1 boolean as if_cond
b: 1 coderef as if_code
c: optional macro(ElseIf) as else_if_block
if( if_cond ):
if_code();
elsif( defined else_if_block ):
else_if_block();
</code></pre>
<p>More ideas: </p>
<p>Implementing Perl quote style, but in Python! ( its a very bad implementation, and note: whitespace is significant in the rule ) </p>
<pre><code>macro stringQuote:
syntax:
q$open$content$close
rules:
open: anyOf('[{(/_') or anyRange('a','z') or anyRange('0','9');
content: string
close: anyOf(']})/_') or anyRange('a','z') or anyRange('0','9');
detect:
return 1 if open == '[' and close == ']'
return 1 if open == '{' and close == '}'
return 1 if open == '(' and close == ')'
return 1 if open == close
return 0
handle:
return content;
</code></pre>
| 1 |
2009-01-20T10:05:14Z
|
[
"python",
"syntax",
"macros"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 460,728 |
<p>This is a new macro syntax I've come up with based on Kent Fredric's ideas. It parses the syntax into a list just like the code is parsed.</p>
<p>Print macro:</p>
<pre><code>macro PrintMacro:
syntax:
print $stmts
if not isinstance(stmts, list):
stmts = [stmts]
return Printnl(stmts, None)
</code></pre>
<p>If macro:</p>
<pre><code>@MultiLine
macro IfMacro:
syntax:
@if_ = if $cond: $body
@elifs = ZeroOrMore(elif $cond: $body)
Optional(else: $elseBody)
return If(
[(cond, Stmt(body)) for cond, body in [if_] + elifs],
elseBody != None and Stmt(elseBody) or None
)
</code></pre>
<p>X to Y [inclusive] [step Z] macro:</p>
<pre><code>@Partial
macro ToMacro:
syntax:
$start to $end Optional(inclusive) Optional(step $step)
if step == None:
step = quote 1
if inclusive:
return quote:
xrange($start, $end+1, $step)
else:
return quote:
xrange($start, $end, $step)
</code></pre>
<p>Aside from the minor issue of using decorators to identify macro type, my only real issue with this is the way you can name groups, e.g. in the if case.
I'm using @name = ..., but this just reeks of Perl. I don't want to just use name = ... because that could conflict with a macro pattern to match. Any ideas?</p>
| 1 |
2009-01-20T10:24:32Z
|
[
"python",
"syntax",
"macros"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 483,447 |
<p>After thinking about it a while a few days ago, and coming up with nothing worth posting, I came back to it now and came up with some syntax I rather like, because it nearly looks like python:</p>
<pre><code>macro PrintMacro:
syntax:
"print", OneOrMore(Var(), name='vars')
return Printnl(vars, None)
</code></pre>
<ul>
<li>Make all the macro "keywords" look like creating python objects (<code>Var()</code> instead of simple <code>Var</code>)</li>
<li><p>Pass the name of elements as a "keyword parameter" to items we want a name for.
It should still be easy to find all the names in the parser, since this syntax definition anyway needs to be interpreted in some way to fill the macro classes syntax variable.</p>
<p>needs to be converted to fill the syntax variable of the resulting macro class.</p></li>
</ul>
<p>The internal syntax representation could also look the same:</p>
<pre><code>class PrintMacro(Macro):
syntax = 'print', OneOrMore(Var(), name='vars')
...
</code></pre>
<p>The internal syntax classes like <code>OneOrMore</code> would follow this pattern to allow subitems and an optional name:</p>
<pre><code>class MacroSyntaxElement(object):
def __init__(self, *p, name=None):
self.subelements = p
self.name = name
</code></pre>
<p>When the macro matches, you just collect all items that have a name and pass them as keyword parameters to the handler function:</p>
<pre><code>class Macro():
...
def parse(self, ...):
syntaxtree = []
nameditems = {}
# parse, however this is done
# store all elements that have a name as
# nameditems[name] = parsed_element
self.handle(syntaxtree, **nameditems)
</code></pre>
<p>The handler function would then be defined like this:</p>
<pre><code>class PrintMacro(Macro):
...
def handle(self, syntaxtree, vars):
return Printnl(vars, None)
</code></pre>
<p>I added the syntaxtree as a first parameter that is always passed, so you wouldn't need to have any named items if you just want to do very basic stuff on the syntax tree.</p>
<p>Also, if you don't like the decorators, why not add the macro type like a "base class"? <code>IfMacro</code> would then look like this:</p>
<pre><code>macro IfMacro(MultiLine):
syntax:
Group("if", Var(), ":", Var(), name='if_')
ZeroOrMore("elif", Var(), ":", Var(), name='elifs')
Optional("else", Var(name='elseBody'))
return If(
[(cond, Stmt(body)) for keyword, cond, colon, body in [if_] + elifs],
None if elseBody is None else Stmt(elseBody)
)
</code></pre>
<p>And in the internal representation:</p>
<pre><code>class IfMacro(MultiLineMacro):
syntax = (
Group("if", Var(), ":", Var(), name='if_'),
ZeroOrMore("elif", Var(), ":", Var(), name='elifs'),
Optional("else", Var(name='elseBody'))
)
def handle(self, syntaxtree, if_=None, elifs=None, elseBody=None):
# Default parameters in case there is no such named item.
# In this case this can only happen for 'elseBody'.
return If(
[(cond, Stmt(body)) for keyword, cond, body in [if_] + elifs],
None if elseNody is None else Stmt(elseBody)
)
</code></pre>
<p>I think this would give a quite flexible system. Main advantages:</p>
<ul>
<li>Easy to learn (looks like standard python)</li>
<li>Easy to parse (parses like standard python)</li>
<li>Optional items can be easily handled, since you can have a default parameter <code>None</code> in the handler</li>
<li>Flexible use of named items:
<ul>
<li>You don't need to name any items if you don't want, because the syntax tree is always passed in.</li>
<li>You can name any subexpressions in a big macro definition, so it's easy to pick out specific stuff you're interested in</li>
</ul></li>
<li>Easily extensible if you want to add more features to the macro constructs. For example <code>Several("abc", min=3, max=5, name="a")</code>. I think this could also be used to add default values to optional elements like <code>Optional("step", Var(), name="step", default=1)</code>.</li>
</ul>
<p>I'm not sure about the quote/unquote syntax with "quote:" and "$", but some syntax for this is needed, since it makes life much easier if you don't have to manually write syntax trees. Probably its a good idea to require (or just permit?) parenthesis for "$", so that you can insert more complicated syntax parts, if you want. Like <code>$(Stmt(a, b, c))</code>.</p>
<p>The ToMacro would look something like this:</p>
<pre><code># macro definition
macro ToMacro(Partial):
syntax:
Var(name='start'), "to", Var(name='end'), Optional("inclusive", name='inc'), Optional("step", Var(name='step'))
if step == None:
step = quote(1)
if inclusive:
return quote:
xrange($(start), $(end)+1, $(step))
else:
return quote:
xrange($(start), $(end), $(step))
# resulting macro class
class ToMacro(PartialMacro):
syntax = Var(name='start'), "to", Var(name='end'), Optional("inclusive", name='inc'), Optional("step", Var(name='step'))
def handle(syntaxtree, start=None, end=None, inc=None, step=None):
if step is None:
step = Number(1)
if inclusive:
return ['xrange', ['(', start, [end, '+', Number(1)], step, ')']]
return ['xrange', ['(', start, end, step, ')']]
</code></pre>
| 10 |
2009-01-27T13:48:47Z
|
[
"python",
"syntax",
"macros"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 484,884 |
<p>Incorporating <a href="http://en.wikipedia.org/wiki/Backus-Naur_form" rel="nofollow">BNF</a></p>
<pre><code>class IfMacro(Macro):
syntax: "if" expression ":" suite ("elif" expression ":" suite )* ["else" ":" suite]
def handle(self, if_, elifs, elseBody):
return If(
[(expression, Stmt(suite)) for expression, suite in [if_] + elifs],
elseBody != None and Stmt(elseBody) or None
)
</code></pre>
| 2 |
2009-01-27T19:33:49Z
|
[
"python",
"syntax",
"macros"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 494,478 |
<p>If you're only asking about the syntax (not implementation) of macros within Python, then I believe the answer is obvious. The syntax should closely match what Python already has (i.e., the "<code>def</code>" keyword).</p>
<p>Whether you implement this as one of the following is up to you:</p>
<pre><code>def macro largest(lst):
defmac largest(lst):
macro largest(lst):
</code></pre>
<p>but I believe it should be exactly the same as a normal function with respect to the rest so that:</p>
<pre><code>def twice_second(a,b):
glob_i = glob_i + 1
return b * 2
x = twice_second (1,7);
</code></pre>
<p>and</p>
<pre><code>defmac twice_second(a,b):
glob_i = glob_i + 1
return b * 2
x = twice_second (1,7);
</code></pre>
<p>are functionally equivalent.</p>
<p>The way I would implement this is with a pre-processor (a la C) which would:</p>
<ul>
<li>replace all defmac's with defs in the input file.</li>
<li>pass it through Python to check syntax (sneaky bit, this).</li>
<li>put the defmac's back in.</li>
<li>find all uses of each macro and "inline" them, using your own reserved variables, such as converting local var <code>a</code> with <code>__macro_second_local_a</code>.</li>
<li>return value should be a special variable as well (macro_second_retval).</li>
<li>global variables would keep their real names.</li>
<li>parameter can be given _macro_second_param_XXX names.</li>
<li>once all inlining is done, remove the defmac 'functions' entirely.</li>
<li>pass the resultant file through Python.</li>
</ul>
<p>No doubt there'll be some nigglies to take care of (like tuples or multiple return points) but Python is sufficiently robust to handle that in my opinion.</p>
<p>So:</p>
<pre><code>x = twice_second (1,7);
</code></pre>
<p>becomes:</p>
<pre><code># These lines are the input params.
__macro_second_param_a = 1
__macro_second_param_b = 7
# These lines are the inlined macro.
glob_i = glob_i + 1
__macro_second_retval = __macro_second_param_b * 2
# Modified call to macro.
x = __macro_second_retval
</code></pre>
| 1 |
2009-01-30T04:18:19Z
|
[
"python",
"syntax",
"macros"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 494,516 |
<p>You might consider looking at how Boo (a .NET-based language with a syntax largely inspired by Python) implements macros, as described at <A HREF="http://boo.codehaus.org/Syntactic+Macros" rel="nofollow">http://boo.codehaus.org/Syntactic+Macros</A>.</p>
| 3 |
2009-01-30T04:55:21Z
|
[
"python",
"syntax",
"macros"
] |
Pythonic macro syntax
| 454,648 |
<p>I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.</p>
<p>My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.</p>
<p>A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.</p>
| 18 |
2009-01-18T04:22:27Z
| 764,479 |
<p>You should take a look at <a href="https://code.google.com/p/metapython/" rel="nofollow">MetaPython</a> to see if it accomplishes what you're looking for.</p>
| 3 |
2009-04-18T23:30:26Z
|
[
"python",
"syntax",
"macros"
] |
Putting separate python packages into same namespace?
| 454,691 |
<p>I'm developing a python framework that would have "addons" written as separate packages. I.e.:</p>
<pre><code>import myframework
from myframework.addons import foo, bar
</code></pre>
<p>Now, what I'm trying to arrange is so that these addons can be distributed separately from core framework and injected into <code>myframework.addons</code> namespace.</p>
<p>Currently my best solution to this is the following. An add-on would be deployed (most likely into <code>{python_version}/site-packages/</code> like so:</p>
<pre><code>fooext/
fooext/__init__.py
fooext/myframework/
fooext/myframework/__init__.py
fooext/myframework/addons/
fooext/myframework/addons/__init__.py
fooext/myframework/addons/foo.py
</code></pre>
<p>The <code>fooext/myframework/addons/__init__.py</code> would have the pkgutil path extension code:</p>
<pre><code>import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
</code></pre>
<p>The problem is that for this to work, the PYTHONPATH needs to have <code>fooext/</code> in it, however the only thing it would have is the parent install directory (most likely, the above-mentioned <code>site-packages</code>). </p>
<p>The solution to this is to have extra code in <code>myframework/addons/__init__.py</code> which would tranverse <code>sys.path</code> and look for any modules with a myframework sub-package, in which case it adds it to <code>sys.path</code> and everything works.</p>
<p>Another idea I had is to write the addon files directly to <code>myframework/addons/</code> install location, but then it would make development and deployed namespace differ.</p>
<p>Is there a better way to accomplish this or perhaps a different approach to the above distribution problem altogether?</p>
| 12 |
2009-01-18T05:17:19Z
| 455,033 |
<p>It sounds like what you're after can be accomplished quite neatly with import hooks.</p>
<p>This is a way of writing custom loading code, which can be associated with a package (or in your case a framework), to perform the loading of all sub-packages and modules, rather than using python's default loading mechanism. Then you can install the loader in site-packages as a base package or under your framework. </p>
<p>When a package is found to be associated with the loader (which can simply be hard-coded to the relative path if necessary), it will then always use the loader to load all add-ons for example. This has the advantage of not requiring any fiddling of the PYTHONPATH, which is generally worth keeping as short as possible.</p>
<p>The alternative to this is to use the <strong>init</strong> files to redirect the import call for a sub-module to the one you want it to pick up, but this is a little bit messy.</p>
<p>More information on import hooks can be found here:</p>
<p><a href="http://www.python.org/dev/peps/pep-0302/" rel="nofollow">http://www.python.org/dev/peps/pep-0302/</a></p>
| 0 |
2009-01-18T12:06:18Z
|
[
"python",
"namespaces",
"distribution",
"extend"
] |
Putting separate python packages into same namespace?
| 454,691 |
<p>I'm developing a python framework that would have "addons" written as separate packages. I.e.:</p>
<pre><code>import myframework
from myframework.addons import foo, bar
</code></pre>
<p>Now, what I'm trying to arrange is so that these addons can be distributed separately from core framework and injected into <code>myframework.addons</code> namespace.</p>
<p>Currently my best solution to this is the following. An add-on would be deployed (most likely into <code>{python_version}/site-packages/</code> like so:</p>
<pre><code>fooext/
fooext/__init__.py
fooext/myframework/
fooext/myframework/__init__.py
fooext/myframework/addons/
fooext/myframework/addons/__init__.py
fooext/myframework/addons/foo.py
</code></pre>
<p>The <code>fooext/myframework/addons/__init__.py</code> would have the pkgutil path extension code:</p>
<pre><code>import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
</code></pre>
<p>The problem is that for this to work, the PYTHONPATH needs to have <code>fooext/</code> in it, however the only thing it would have is the parent install directory (most likely, the above-mentioned <code>site-packages</code>). </p>
<p>The solution to this is to have extra code in <code>myframework/addons/__init__.py</code> which would tranverse <code>sys.path</code> and look for any modules with a myframework sub-package, in which case it adds it to <code>sys.path</code> and everything works.</p>
<p>Another idea I had is to write the addon files directly to <code>myframework/addons/</code> install location, but then it would make development and deployed namespace differ.</p>
<p>Is there a better way to accomplish this or perhaps a different approach to the above distribution problem altogether?</p>
| 12 |
2009-01-18T05:17:19Z
| 455,267 |
<blockquote>
<p>Is there a better way to accomplish this or perhaps a different approach to the above distribution problem altogether?</p>
</blockquote>
<p>Possibly. Python's module/package setup is generally tricky to tamper with dynamically like this, but its object/class system is open and extensible in a well-defined way. When modules and packages don't quite have the features you need to encapsulate your project nicely you can use classes instead.</p>
<p>For example you could have the extension functionality in a completely different package, but allow it to inject classes into your basic framework through a specific interface. eg. myframework/_ââ_âinitâ_ââ_.py containing a basic application wrapper:</p>
<pre><code>class MyFramework(object):
"""A bare MyFramework, I only hold a person's name
"""
_addons= {}
@staticmethod
def addAddon(name, addon):
MyFramework._addons[name]= addon
def __init__(self, person):
self.person= person
for name, addon in MyFramework._addons.items():
setattr(self, name, addon(self))
</code></pre>
<p>Then you could have extension functionality in a myexts/helloer.py, that keeps a reference to its 'owner' or 'outer' MyFramework class instance:</p>
<pre><code>class Helloer(object):
def __init__(self, owner):
self.owner= owner
def hello(self):
print 'hello '+self.owner.person
import myframework
myframework.MyFramework.addAddon('helloer', Helloer)
</code></pre>
<p>So now if you just "import myframework", you only get the basic functionality. But if you also "import myexts.helloer" you also get the ability to call MyFramework.helloer.hello(). Naturally you can also define protocols for addons to interact with the basic framework behaviour, and each other. You can also do things like inner classes a subclass of the framework can override to customise without having to monkey-patch classes that might affect other applications, if you need that level of complexity.</p>
<p>Encapsulating behaviour like this can be useful, but it's typically annoying work to adapt module-level code you've already got to fit this model.</p>
| 4 |
2009-01-18T15:01:30Z
|
[
"python",
"namespaces",
"distribution",
"extend"
] |
Putting separate python packages into same namespace?
| 454,691 |
<p>I'm developing a python framework that would have "addons" written as separate packages. I.e.:</p>
<pre><code>import myframework
from myframework.addons import foo, bar
</code></pre>
<p>Now, what I'm trying to arrange is so that these addons can be distributed separately from core framework and injected into <code>myframework.addons</code> namespace.</p>
<p>Currently my best solution to this is the following. An add-on would be deployed (most likely into <code>{python_version}/site-packages/</code> like so:</p>
<pre><code>fooext/
fooext/__init__.py
fooext/myframework/
fooext/myframework/__init__.py
fooext/myframework/addons/
fooext/myframework/addons/__init__.py
fooext/myframework/addons/foo.py
</code></pre>
<p>The <code>fooext/myframework/addons/__init__.py</code> would have the pkgutil path extension code:</p>
<pre><code>import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
</code></pre>
<p>The problem is that for this to work, the PYTHONPATH needs to have <code>fooext/</code> in it, however the only thing it would have is the parent install directory (most likely, the above-mentioned <code>site-packages</code>). </p>
<p>The solution to this is to have extra code in <code>myframework/addons/__init__.py</code> which would tranverse <code>sys.path</code> and look for any modules with a myframework sub-package, in which case it adds it to <code>sys.path</code> and everything works.</p>
<p>Another idea I had is to write the addon files directly to <code>myframework/addons/</code> install location, but then it would make development and deployed namespace differ.</p>
<p>Is there a better way to accomplish this or perhaps a different approach to the above distribution problem altogether?</p>
| 12 |
2009-01-18T05:17:19Z
| 456,621 |
<p>Setuptools has the ability to lookup package "entry points" (functions, objects, whatever) by name. Trac uses this mechanism to <a href="http://trac.edgewall.org/browser/trunk/trac/loader.py#L33" rel="nofollow">load its plugins</a>, and it works well.</p>
| 3 |
2009-01-19T05:35:28Z
|
[
"python",
"namespaces",
"distribution",
"extend"
] |
Putting separate python packages into same namespace?
| 454,691 |
<p>I'm developing a python framework that would have "addons" written as separate packages. I.e.:</p>
<pre><code>import myframework
from myframework.addons import foo, bar
</code></pre>
<p>Now, what I'm trying to arrange is so that these addons can be distributed separately from core framework and injected into <code>myframework.addons</code> namespace.</p>
<p>Currently my best solution to this is the following. An add-on would be deployed (most likely into <code>{python_version}/site-packages/</code> like so:</p>
<pre><code>fooext/
fooext/__init__.py
fooext/myframework/
fooext/myframework/__init__.py
fooext/myframework/addons/
fooext/myframework/addons/__init__.py
fooext/myframework/addons/foo.py
</code></pre>
<p>The <code>fooext/myframework/addons/__init__.py</code> would have the pkgutil path extension code:</p>
<pre><code>import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
</code></pre>
<p>The problem is that for this to work, the PYTHONPATH needs to have <code>fooext/</code> in it, however the only thing it would have is the parent install directory (most likely, the above-mentioned <code>site-packages</code>). </p>
<p>The solution to this is to have extra code in <code>myframework/addons/__init__.py</code> which would tranverse <code>sys.path</code> and look for any modules with a myframework sub-package, in which case it adds it to <code>sys.path</code> and everything works.</p>
<p>Another idea I had is to write the addon files directly to <code>myframework/addons/</code> install location, but then it would make development and deployed namespace differ.</p>
<p>Is there a better way to accomplish this or perhaps a different approach to the above distribution problem altogether?</p>
| 12 |
2009-01-18T05:17:19Z
| 1,719,512 |
<p>See namespace packages:</p>
<p><a href="http://www.python.org/dev/peps/pep-0382/">http://www.python.org/dev/peps/pep-0382/</a></p>
<p>or in setuptools:</p>
<p><a href="http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages">http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages</a></p>
| 6 |
2009-11-12T02:27:51Z
|
[
"python",
"namespaces",
"distribution",
"extend"
] |
Python get proper line ending
| 454,725 |
<p>Is there an easy way to get the type of line ending that the current operating system uses?</p>
| 38 |
2009-01-18T06:01:14Z
| 454,731 |
<p>Oh, I figured it out. Apparently, <a href="http://www.python.org/dev/peps/pep-0278/">PEP-278</a> states the following: </p>
<blockquote>
<p>Any line ending in the input file will be seen as a '\n' in Python, so little other code has to change to handle universal newlines.</p>
</blockquote>
| 13 |
2009-01-18T06:07:20Z
|
[
"python",
"line-endings"
] |
Python get proper line ending
| 454,725 |
<p>Is there an easy way to get the type of line ending that the current operating system uses?</p>
| 38 |
2009-01-18T06:01:14Z
| 454,809 |
<p>If you are operating on a file that you opened in text mode, then you are correct that line breaks all show up as '<code>\n</code>'. Otherwise, you are looking for <a href="http://docs.python.org/library/os.html"><code>os.linesep</code></a> .</p>
<p>From <a href="http://docs.python.org/library/os.html">http://docs.python.org/library/os.html</a>:</p>
<blockquote>
<p>os.<strong>linesep</strong></p>
<p>The string used to separate (or, rather, terminate) lines on the
current platform. This may be a single
character, such as '\n' for POSIX, or
multiple characters, for example,
'\r\n' for Windows. Do not use
os.linesep as a line terminator when
writing files opened in text mode (the
default); use a single '\n' instead,
on all platforms.</p>
</blockquote>
| 61 |
2009-01-18T08:21:16Z
|
[
"python",
"line-endings"
] |
Python get proper line ending
| 454,725 |
<p>Is there an easy way to get the type of line ending that the current operating system uses?</p>
| 38 |
2009-01-18T06:01:14Z
| 454,810 |
<p>If specify test resp. binary properly when opening files, and use universal newlines, you shouldn't have to worry about different newlines most of the time.</p>
<p>But if you have to, use <a href="http://docs.python.org/library/os.html#os.linesep" rel="nofollow">os.linesep</a></p>
| 3 |
2009-01-18T08:21:36Z
|
[
"python",
"line-endings"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 454,871 |
<p><code>mysqldb</code> is a module for Python that doesn't come pre-installed or with Django. You can download <code>mysqldb</code> <a href="http://sourceforge.net/projects/mysql-python">here</a>.</p>
| 39 |
2009-01-18T09:25:58Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 455,041 |
<p>If you are running on Vista, you may want to check out the <a href="http://bitnami.org/stack/djangostack" rel="nofollow">Bitnami Django stack.</a> It is an all-in-one stack of Apache, Python, MySQL, etc. packaged with <a href="http://bitrock.com" rel="nofollow">Bitrock</a> crossplatform installers to make it really easy to get started. It runs on Windows, Mac and Linux. Oh, and is completely free :)</p>
| 2 |
2009-01-18T12:18:07Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 5,873,259 |
<p>You need to use one of the following commands. Which one depends on what OS and software you have and use.</p>
<ol>
<li><strong>easy_install mysql-python</strong> (mix os)</li>
<li><strong>pip install mysql-python</strong> (mix os)</li>
<li><strong>apt-get install python-mysqldb</strong> (Linux Ubuntu, ...)</li>
<li><strong>cd /usr/ports/databases/py-MySQLdb && make install clean</strong> (FreeBSD)</li>
<li><strong>yum install MySQL-python</strong> (Linux Fedora, CentOS ...)</li>
</ol>
<p>For Windows, see this answer: <a href="http://stackoverflow.com/q/21440230/4646678">Install mysql-python (Windows)</a></p>
| 395 |
2011-05-03T17:23:47Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 5,999,414 |
<p>Ubuntu: </p>
<pre><code>sudo apt-get install python-mysqldb
</code></pre>
| 24 |
2011-05-14T02:17:49Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 12,726,435 |
<p>Thanks to derevo but I think there's another good way for doing this:</p>
<ol>
<li>Download and install <a href="http://www.activestate.com/activepython/downloads#" rel="nofollow">ActivePython</a></li>
<li>Open Command Prompt</li>
<li>Type <code>pypm install mysql-python</code></li>
<li>Read the notes specific to this package.</li>
</ol>
<p>I think <code>pypm</code> is more powerful and reliable than <code>easy_install</code>.</p>
| 2 |
2012-10-04T11:38:40Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 25,475,877 |
<p>...and remember there is <strong>no MySQLdb for python3.x</strong></p>
<p>(I know the question is about python2.x but google rates this post quite high)</p>
<hr>
<p><strong>EDIT:</strong> As stated in the comments, there's a MySQLdb's fork that adds Python 3 support: <a href="http://github.com/PyMySQL/mysqlclient-python">github.com/PyMySQL/mysqlclient-python
</a></p>
| 40 |
2014-08-24T20:11:47Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 28,278,997 |
<ul>
<li>Go to your project directory with <code>cd</code>.</li>
<li>source/bin/activate (activate your env. if not previously).</li>
<li>Run the command <code>easy_install MySQL-python</code></li>
</ul>
| 4 |
2015-02-02T13:36:45Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 31,104,707 |
<p>If you are on a virtual environment then</p>
<pre><code>pip install MySQL-python
</code></pre>
| 3 |
2015-06-28T21:01:10Z
|
[
"python",
"django"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.