title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 31,005,891 | <p>For completeness' sake, I'd like to point out that sometimes you may want to <em>parse</em> code instead of importing it. An <code>import</code> will <em>execute</em> top-level expressions, and that could be a problem.</p>
<p>For example, I'm letting users select entry point functions for packages being made with <a href="https://docs.python.org/dev/library/zipapp.html">zipapp</a>. Using <code>import</code> and <code>inspect</code> risks running astray code, leading to crashes, help messages being printed out, GUI dialogs popping up and so on.</p>
<p>Instead I use the <a href="https://docs.python.org/3.2/library/ast.html#module-ast">ast</a> module to list all the top-level functions:</p>
<pre><code>import ast
import sys
def top_level_functions(body):
return (f for f in body if isinstance(f, ast.FunctionDef))
def parse_ast(filename):
with open(filename, "rt") as file:
return ast.parse(file.read(), filename=filename)
if __name__ == "__main__":
for filename in sys.argv[1:]:
print(filename)
tree = parse_ast(filename)
for func in top_level_functions(tree.body):
print(" %s" % func.name)
</code></pre>
<p>Putting this code in <code>list.py</code> and using itself as input, I get:</p>
<pre><code>$ python list.py list.py
list.py
top_level_functions
parse_ast
</code></pre>
<p>Of course, navigating an AST can be tricky sometimes, even for a relatively simple language like Python, because the AST is quite low-level. But if you have a simple and clear use case, it's both doable and safe.</p>
<p>(Though, a downside is that you can't detect functions that are dynamically generated, like <code>foo = lambda x,y: x*y</code>.)</p>
| 10 | 2015-06-23T14:39:55Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 39,526,714 | <p>In <strong>IPython</strong> you can use tab autocompletion to list available functions in a module.</p>
<p>Specifically, type <code>foo.</code> then hit the <code>tab</code> key.</p>
| 0 | 2016-09-16T08:15:28Z | [
"python"
] |
listing all functions in a python module | 139,180 | <p>I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. </p>
<p>I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?</p>
<p>eg. something like:</p>
<pre><code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code></pre>
| 164 | 2008-09-26T12:38:52Z | 40,118,371 | <p>You can use the following method to get list all the functions in your module from shell:</p>
<p><code>import module</code></p>
<pre><code>module.*?
</code></pre>
| -1 | 2016-10-18T21:26:53Z | [
"python"
] |
Adding Cookie to ZSI Posts | 139,212 | <p>I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fail.</p>
<p>How can I add cookies from a Python CookieJar to ZSI requests?</p>
| 2 | 2008-09-26T12:45:01Z | 145,610 | <p>If you read the <a href="https://pywebsvcs.svn.sourceforge.net/svnroot/pywebsvcs/trunk/zsi/ZSI/client.py" rel="nofollow">_Binding class in client.py of ZSI</a> you can see that it has a variable cookies, which is an instance of <a href="http://docs.python.org/lib/module-Cookie.html" rel="nofollow">Cookie.SimpleCookie</a>. Following the <a href="http://pywebsvcs.sourceforge.net/zsi.html#SECTION003210000000000000000" rel="nofollow">ZSI example</a> and the <a href="http://docs.python.org/lib/cookie-example.html" rel="nofollow">Cookie example</a> that is how it should work:</p>
<pre><code>b = Binding(url='/cgi-bin/simple-test', tracefile=fp)
b.cookies['foo'] = 'bar'
</code></pre>
| 1 | 2008-09-28T10:15:27Z | [
"python",
"web-services",
"cookies",
"soappy",
"zsi"
] |
Adding Cookie to ZSI Posts | 139,212 | <p>I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fail.</p>
<p>How can I add cookies from a Python CookieJar to ZSI requests?</p>
| 2 | 2008-09-26T12:45:01Z | 148,379 | <p>Additionally, the Binding class also allows any header to be added. So I figured out that I can just add a "Cookie" header for each cookie I need to add. This worked well for the code generated by wsdl2py, just adding the cookies right after the binding is formed in the SOAP client class. Adding a parameter to the generated class to take in the cookies as a dictionary is easy and then they can easily be iterated through and added.</p>
| 0 | 2008-09-29T11:55:11Z | [
"python",
"web-services",
"cookies",
"soappy",
"zsi"
] |
Why results of map() and list comprehension are different? | 139,819 | <p>The following test fails:</p>
<pre><code>#!/usr/bin/env python
def f(*args):
"""
>>> t = 1, -1
>>> f(*map(lambda i: lambda: i, t))
[1, -1]
>>> f(*(lambda: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda: i for i in t]) # -> [-1, -1]
[1, -1]
"""
alist = [a() for a in args]
print(alist)
if __name__ == '__main__':
import doctest; doctest.testmod()
</code></pre>
<p>In other words:</p>
<pre><code>>>> t = 1, -1
>>> args = []
>>> for i in t:
... args.append(lambda: i)
...
>>> map(lambda a: a(), args)
[-1, -1]
>>> args = []
>>> for i in t:
... args.append((lambda i: lambda: i)(i))
...
>>> map(lambda a: a(), args)
[1, -1]
>>> args = []
>>> for i in t:
... args.append(lambda i=i: i)
...
>>> map(lambda a: a(), args)
[1, -1]
</code></pre>
| 9 | 2008-09-26T14:19:48Z | 139,880 | <p>The lambda captures variables, not values, hence the code</p>
<pre><code>lambda : i
</code></pre>
<p>will always return the value i is <strong>currently</strong> bound to in the closure. By the time it gets called, this value has been set to -1.</p>
<p>To get what you want, you'll need to capture the actual binding at the time the lambda is created, by:</p>
<pre><code>>>> f(*(lambda i=i: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda i=i: i for i in t]) # -> [-1, -1]
[1, -1]
</code></pre>
| 5 | 2008-09-26T14:28:40Z | [
"python",
"closures",
"list-comprehension",
"late-binding",
"generator-expression"
] |
Why results of map() and list comprehension are different? | 139,819 | <p>The following test fails:</p>
<pre><code>#!/usr/bin/env python
def f(*args):
"""
>>> t = 1, -1
>>> f(*map(lambda i: lambda: i, t))
[1, -1]
>>> f(*(lambda: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda: i for i in t]) # -> [-1, -1]
[1, -1]
"""
alist = [a() for a in args]
print(alist)
if __name__ == '__main__':
import doctest; doctest.testmod()
</code></pre>
<p>In other words:</p>
<pre><code>>>> t = 1, -1
>>> args = []
>>> for i in t:
... args.append(lambda: i)
...
>>> map(lambda a: a(), args)
[-1, -1]
>>> args = []
>>> for i in t:
... args.append((lambda i: lambda: i)(i))
...
>>> map(lambda a: a(), args)
[1, -1]
>>> args = []
>>> for i in t:
... args.append(lambda i=i: i)
...
>>> map(lambda a: a(), args)
[1, -1]
</code></pre>
| 9 | 2008-09-26T14:19:48Z | 139,899 | <p>They are different, because the value of <code>i</code> in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in <code>f</code>.<br />
By that time, <code>i</code> is bound to the last value if <code>t</code>, which is -1.</p>
<p>So basically, this is what the list comprehension does (likewise for the genexp):</p>
<pre><code>x = []
i = 1 # 1. from t
x.append(lambda: i)
i = -1 # 2. from t
x.append(lambda: i)
</code></pre>
<p>Now the lambdas carry around a closure that references <code>i</code>, but <code>i</code> is bound to -1 in both cases, because that is the last value it was assigned to.</p>
<p>If you want to make sure that the lambda receives the current value of <code>i</code>, do</p>
<pre><code>f(*[lambda u=i: u for i in t])
</code></pre>
<p>This way, you force the evaluation of <code>i</code> at the time the closure is created.</p>
<p><strong>Edit</strong>: There is one difference between generator expressions and list comprehensions: the latter leak the loop variable into the surrounding scope.</p>
| 9 | 2008-09-26T14:31:47Z | [
"python",
"closures",
"list-comprehension",
"late-binding",
"generator-expression"
] |
Why results of map() and list comprehension are different? | 139,819 | <p>The following test fails:</p>
<pre><code>#!/usr/bin/env python
def f(*args):
"""
>>> t = 1, -1
>>> f(*map(lambda i: lambda: i, t))
[1, -1]
>>> f(*(lambda: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda: i for i in t]) # -> [-1, -1]
[1, -1]
"""
alist = [a() for a in args]
print(alist)
if __name__ == '__main__':
import doctest; doctest.testmod()
</code></pre>
<p>In other words:</p>
<pre><code>>>> t = 1, -1
>>> args = []
>>> for i in t:
... args.append(lambda: i)
...
>>> map(lambda a: a(), args)
[-1, -1]
>>> args = []
>>> for i in t:
... args.append((lambda i: lambda: i)(i))
...
>>> map(lambda a: a(), args)
[1, -1]
>>> args = []
>>> for i in t:
... args.append(lambda i=i: i)
...
>>> map(lambda a: a(), args)
[1, -1]
</code></pre>
| 9 | 2008-09-26T14:19:48Z | 141,113 | <p>Expression <code>f = lambda: i</code> is equivalent to:</p>
<pre><code>def f():
return i
</code></pre>
<p>Expression <code>g = lambda i=i: i</code> is equivalent to:</p>
<pre><code>def g(i=i):
return i
</code></pre>
<p><code>i</code> is a <a href="http://docs.python.org/ref/naming.html" rel="nofollow">free variable</a> in the first case and it is bound to the function parameter in the second case i.e., it is a local variable in that case. Values for default parameters are evaluated at the time of function definition. </p>
<p>Generator expression is the nearest enclosing scope (where <code>i</code> is defined) for <code>i</code> name in the <code>lambda</code> expression, therefore <code>i</code> is resolved in that block:</p>
<pre><code>f(*(lambda: i for i in (1, -1)) # -> [-1, -1]
</code></pre>
<p><code>i</code> is a local variable of the <code>lambda i: ...</code> block, therefore the object it refers to is defined in that block:</p>
<pre><code>f(*map(lambda i: lambda: i, (1,-1))) # -> [1, -1]
</code></pre>
| 3 | 2008-09-26T18:24:31Z | [
"python",
"closures",
"list-comprehension",
"late-binding",
"generator-expression"
] |
Writing a Domain Specific Language for selecting rows from a table | 140,026 | <p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p>
<p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p>
<p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p>
<p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p>
<p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p>
<p>Edit: Expanded description to clear up some misconceptions.</p>
| 5 | 2008-09-26T14:56:05Z | 140,066 | <p>Why not create a language that when it "compiles" it generates SQL or whatever query language your datastore requires ?</p>
<p>You would be basically creating an abstraction over your persistence layer. </p>
| 0 | 2008-09-26T15:02:56Z | [
"python",
"database",
"algorithm",
"dsl"
] |
Writing a Domain Specific Language for selecting rows from a table | 140,026 | <p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p>
<p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p>
<p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p>
<p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p>
<p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p>
<p>Edit: Expanded description to clear up some misconceptions.</p>
| 5 | 2008-09-26T14:56:05Z | 140,091 | <p>You mentioned Python. Why not use Python? If someone can "type in" an expression in your DSL, they can type in Python.</p>
<p>You'll need some rules on structure of the expression, but that's a lot easier than implementing something new.</p>
| 0 | 2008-09-26T15:07:03Z | [
"python",
"database",
"algorithm",
"dsl"
] |
Writing a Domain Specific Language for selecting rows from a table | 140,026 | <p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p>
<p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p>
<p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p>
<p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p>
<p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p>
<p>Edit: Expanded description to clear up some misconceptions.</p>
| 5 | 2008-09-26T14:56:05Z | 140,228 | <p>You said nobody is going to want to install a server that downloads and executes arbitrary code at runtime. However, that is exactly what your DSL will do (eventually) so there probably isn't that much of a difference. Unless you're doing something very specific with the data then I don't think a DSL will buy you that much and it will frustrate the users who are already versed in SQL. Don't underestimate the size of the task you'll be taking on.</p>
<p>To answer your question however, you will need to come up with a grammar for your language, something to parse the text and walk the tree, emitting code or calling an API that you've written (which is why my comment that you're still going to have to ship some code). </p>
<p>There are plenty of educational texts on grammars for mathematical expressions you can refer to on the net, that's fairly straight forward. You may have a parser generator tool like ANTLR or Yacc you can use to help you generate the parser (or use a language like Lisp/Scheme and marry the two up). Coming up with a reasonable SQL grammar won't be easy. But google 'BNF SQL' and see what you come up with.</p>
<p>Best of luck.</p>
| 0 | 2008-09-26T15:29:21Z | [
"python",
"database",
"algorithm",
"dsl"
] |
Writing a Domain Specific Language for selecting rows from a table | 140,026 | <p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p>
<p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p>
<p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p>
<p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p>
<p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p>
<p>Edit: Expanded description to clear up some misconceptions.</p>
| 5 | 2008-09-26T14:56:05Z | 140,275 | <p>I think we're going to need a bit more information here. Let me know if any of the following is based on incorrect assumptions.</p>
<p>First of all, as you pointed out yourself, there already exists a DSL for selecting rows from arbitrary tables-- it is called "SQL". Since you don't want to reinvent SQL, I'm assuming that you only need to query from a single table with a fixed format.</p>
<p>If this is the case, you probably don't need to implement a DSL (although that's certainly one way to go); it may be easier, if you are used to Object Orientation, to create a Filter object. </p>
<p>More specifically, a "Filter" collection that would hold one or more SelectionCriterion objects. You can implement these to inherit from one or more base classes representing types of selections (Range, LessThan, ExactMatch, Like, etc.) Once these base classes are in place, you can create column-specific inherited versions which are appropriate to that column. Finally, depending on the complexity of the queries you want to support, you'll want to implement some kind of connective glue to handle AND and OR and NOT linkages between the various criteria.</p>
<p>If you feel like it, you can create a simple GUI to load up the collection; I'd look at the filtering in Excel as a model, if you don't have anything else in mind.</p>
<p>Finally, it should be trivial to convert the contents of this Collection to the corresponding SQL, and pass that to the database.</p>
<p>However: if what you are after is simplicity, and your users understand SQL, you could simply ask them to type in the contents of a WHERE clause, and programmatically build up the rest of the query. From a security perspective, if your code has control over the columns selected and the FROM clause, and your database permissions are set properly, and you do some sanity checking on the string coming in from the users, this would be a relatively safe option.</p>
| 1 | 2008-09-26T15:35:16Z | [
"python",
"database",
"algorithm",
"dsl"
] |
Writing a Domain Specific Language for selecting rows from a table | 140,026 | <p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p>
<p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p>
<p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p>
<p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p>
<p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p>
<p>Edit: Expanded description to clear up some misconceptions.</p>
| 5 | 2008-09-26T14:56:05Z | 140,304 | <p>It really sounds like SQL, but perhaps it's worth to try using SQLite if you want to keep it simple?</p>
| 0 | 2008-09-26T15:39:40Z | [
"python",
"database",
"algorithm",
"dsl"
] |
Writing a Domain Specific Language for selecting rows from a table | 140,026 | <p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p>
<p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p>
<p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p>
<p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p>
<p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p>
<p>Edit: Expanded description to clear up some misconceptions.</p>
| 5 | 2008-09-26T14:56:05Z | 141,872 | <p>"implement a Domain Specific Language"</p>
<p>"nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime"</p>
<p>I want a DSL but I don't want Python to be that DSL. Okay. How will you execute this DSL? What runtime <em>is</em> acceptable if not Python?</p>
<p>What if I have a C program that happens to embed the Python interpreter? Is that acceptable?</p>
<p>And -- if Python is not an acceptable runtime -- why does this have a Python tag?</p>
| 1 | 2008-09-26T20:46:31Z | [
"python",
"database",
"algorithm",
"dsl"
] |
Writing a Domain Specific Language for selecting rows from a table | 140,026 | <p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p>
<p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p>
<p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p>
<p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p>
<p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p>
<p>Edit: Expanded description to clear up some misconceptions.</p>
| 5 | 2008-09-26T14:56:05Z | 141,972 | <p>It sounds like you want to create a grammar not a DSL. I'd look into <a href="http://antlr.org/" rel="nofollow">ANTLR</a> which will allow you to create a specific parser that will interpret text and translate to specific commands. ANTLR provides libraries for Python, SQL, Java, C++, C, C# etc.</p>
<p>Also, here is a fine example of an ANTLR <a href="http://www.codeproject.com/KB/recipes/sota_expression_evaluator.aspx" rel="nofollow">calculation engine</a> created in C#</p>
| 0 | 2008-09-26T21:05:15Z | [
"python",
"database",
"algorithm",
"dsl"
] |
Writing a Domain Specific Language for selecting rows from a table | 140,026 | <p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p>
<p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p>
<p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p>
<p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p>
<p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p>
<p>Edit: Expanded description to clear up some misconceptions.</p>
| 5 | 2008-09-26T14:56:05Z | 142,306 | <p>Building a DSL to be interpreted by Python.</p>
<p>Step 1. Build the run-time classes and objects. These classes will have all the cursor loops and SQL statements and all of that algorithmic processing tucked away in their methods. You'll make heavy use of the <a href="http://exciton.cs.rice.edu/javaresources/DesignPatterns/command.htm" rel="nofollow">Command</a> and <a href="http://exciton.cs.rice.edu/javaresources/DesignPatterns/StrategyPattern.htm" rel="nofollow">Strategy</a> design patterns to build these classes. Most things are a command, options and choices are plug-in strategies. Look at the design for Apache Ant's <a href="http://ant.apache.org/manual/develop.html" rel="nofollow">Task</a> API -- it's a good example.</p>
<p>Step 2. Validate that this system of objects actually works. Be sure that the design is simple and complete. You're tests will construct the Command and Strategy objects, and then execute the top-level Command object. The Command objects will do the work. </p>
<p>At this point you're largely done. Your run-time is just a configuration of objects created from the above domain. [This isn't as easy as it sounds. It requires some care to define a set of classes that can be instantiated and then "talk among themselves" to do the work of your application.]</p>
<p>Note that what you'll have will require nothing more than declarations. What's wrong with procedural? One you start to write a DSL with procedural elements, you find that you need more and more features until you've written Python with different syntax. Not good.</p>
<p>Further, procedural language interpreters are simply hard to write. State of execution, and scope of references are simply hard to manage.</p>
<p>You can use native Python -- and stop worrying about "getting out of the sandbox". Indeed, that's how you'll unit test everything, using a short Python script to create your objects. Python will be the DSL. </p>
<p>["But wait", you say, "If I simply use Python as the DSL people can execute arbitrary things." Depends on what's on the PYTHONPATH, and sys.path. Look at the <a href="http://docs.python.org/lib/module-site.html" rel="nofollow">site</a> module for ways to control what's available.]</p>
<p>A declarative DSL is simplest. It's entirely an exercise in representation. A block of Python that merely sets the values of some variables is nice. That's what Django uses.</p>
<p>You can use the <a href="http://docs.python.org/lib/module-ConfigParser.html" rel="nofollow">ConfigParser</a> as a language for representing your run-time configuration of objects.</p>
<p>You can use <a href="http://pypi.python.org/pypi/python-json/" rel="nofollow">JSON</a> or <a href="http://pyyaml.org/" rel="nofollow">YAML</a> as a language for representing your run-time configuration of objects. Ready-made parsers are totally available.</p>
<p>You can use XML, too. It's harder to design and parse, but it works fine. People love it. That's how Ant and Maven (and lots of other tools) use declarative syntax to describe procedures. I don't recommend it, because it's a wordy pain in the neck. I recommend simply using Python.</p>
<p>Or, you can go off the deep-end and invent your own syntax and write your own parser.</p>
| 4 | 2008-09-26T22:14:14Z | [
"python",
"database",
"algorithm",
"dsl"
] |
Regular expressions but for writing in the match | 140,182 | <p>When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... </p>
<p>Right now I'm doing this...</p>
<pre><code>def getExpandedText(pattern, text, replaceValue):
"""
One liner... really ugly but it's only used in here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
</code></pre>
<p>so if I do sth like</p>
<pre><code>>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
</code></pre>
<p>It changes the (...) with 'ooo'.</p>
<p>Do you guys know whether with python regular expressions we can do this?</p>
<p>thanks a lot guys!!</p>
| 1 | 2008-09-26T15:22:06Z | 140,208 | <p>Of course. See the 'sub' and 'subn' methods of compiled regular expressions, or the 're.sub' and 're.subn' functions. You can either make it replace the matches with a string argument you give, or you can pass a callable (such as a function) which will be called to supply the replacement. See <a href="https://docs.python.org/library/re.html" rel="nofollow">https://docs.python.org/library/re.html</a></p>
| 1 | 2008-09-26T15:26:18Z | [
"python",
"regex"
] |
Regular expressions but for writing in the match | 140,182 | <p>When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... </p>
<p>Right now I'm doing this...</p>
<pre><code>def getExpandedText(pattern, text, replaceValue):
"""
One liner... really ugly but it's only used in here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
</code></pre>
<p>so if I do sth like</p>
<pre><code>>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
</code></pre>
<p>It changes the (...) with 'ooo'.</p>
<p>Do you guys know whether with python regular expressions we can do this?</p>
<p>thanks a lot guys!!</p>
| 1 | 2008-09-26T15:22:06Z | 140,209 | <pre><code>sub (replacement, string[, count = 0])
</code></pre>
<p><a href="https://docs.python.org/howto/regex.html#search-and-replace" rel="nofollow">sub</a> returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn't found, string is returned unchanged.</p>
<pre><code> p = re.compile( '(blue|white|red)')
>>> p.sub( 'colour', 'blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub( 'colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'
</code></pre>
| 7 | 2008-09-26T15:26:22Z | [
"python",
"regex"
] |
Regular expressions but for writing in the match | 140,182 | <p>When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... </p>
<p>Right now I'm doing this...</p>
<pre><code>def getExpandedText(pattern, text, replaceValue):
"""
One liner... really ugly but it's only used in here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
</code></pre>
<p>so if I do sth like</p>
<pre><code>>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
</code></pre>
<p>It changes the (...) with 'ooo'.</p>
<p>Do you guys know whether with python regular expressions we can do this?</p>
<p>thanks a lot guys!!</p>
| 1 | 2008-09-26T15:22:06Z | 140,218 | <p>You want to use <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow">re.sub</a>:</p>
<pre><code>>>> import re
>>> re.sub(r'aaa...bbb', 'aaaooobbb', "hola aaaiiibbb como estas?")
'hola aaaooobbb como estas?'
</code></pre>
<p>To re-use variable parts from the pattern, use <code>\g<n></code> in the replacement string to access the n-th <code>()</code> group:</p>
<pre><code>>>> re.sub( "(svcOrdNbr +)..", "\g<1>XX", "svcOrdNbr IASZ0080")
'svcOrdNbr XXSZ0080'
</code></pre>
| 2 | 2008-09-26T15:27:48Z | [
"python",
"regex"
] |
Regular expressions but for writing in the match | 140,182 | <p>When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... </p>
<p>Right now I'm doing this...</p>
<pre><code>def getExpandedText(pattern, text, replaceValue):
"""
One liner... really ugly but it's only used in here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
</code></pre>
<p>so if I do sth like</p>
<pre><code>>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
</code></pre>
<p>It changes the (...) with 'ooo'.</p>
<p>Do you guys know whether with python regular expressions we can do this?</p>
<p>thanks a lot guys!!</p>
| 1 | 2008-09-26T15:22:06Z | 140,776 | <p>If you want to continue using the syntax you mentioned (replace the match value instead of replacing the part that didn't match), and considering you will only have one group, you could use the code below.</p>
<pre><code>def getExpandedText(pattern, text, replaceValue):
m = re.search(pattern, text)
expandedText = text[:m.start(1)] + replaceValue + text[m.end(1):]
return expandedText
</code></pre>
| 0 | 2008-09-26T17:23:44Z | [
"python",
"regex"
] |
Regular expressions but for writing in the match | 140,182 | <p>When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... </p>
<p>Right now I'm doing this...</p>
<pre><code>def getExpandedText(pattern, text, replaceValue):
"""
One liner... really ugly but it's only used in here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
</code></pre>
<p>so if I do sth like</p>
<pre><code>>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
</code></pre>
<p>It changes the (...) with 'ooo'.</p>
<p>Do you guys know whether with python regular expressions we can do this?</p>
<p>thanks a lot guys!!</p>
| 1 | 2008-09-26T15:22:06Z | 142,188 | <pre><code>def getExpandedText(pattern,text,*group):
r""" Searches for pattern in the text and replaces
all captures with the values in group.
Tag renaming:
>>> html = '<div> abc <span id="x"> def </span> ghi </div>'
>>> getExpandedText(r'</?(span\b)[^>]*>', html, 'div')
'<div> abc <div id="x"> def </div> ghi </div>'
Nested groups, capture-references:
>>> getExpandedText(r'A(.*?Z(.*?))B', "abAcdZefBgh", r'<\2>')
'abA<ef>Bgh'
"""
pattern = re.compile(pattern)
ret = []
last = 0
for m in pattern.finditer(text):
for i in xrange(0,len(m.groups())):
start,end = m.span(i+1)
# nested or skipped group
if start < last or group[i] is None:
continue
# text between the previous and current match
if last < start:
ret.append(text[last:start])
last = end
ret.append(m.expand(group[i]))
ret.append(text[last:])
return ''.join(ret)
</code></pre>
<p><strong>Edit:</strong> Allow capture-references in the replacement strings.</p>
| 0 | 2008-09-26T21:48:26Z | [
"python",
"regex"
] |
Using locale.setlocale in embedded Python without breaking file parsing in C thread | 140,295 | <p>We're using a third-party middleware product that allows us to write code in an embedded Python interpreter, and which exposes an API that we can call into. Some of these API calls allow us to load various kinds of file, and the loading code is implemented in C. File loading happens in a separate thread, and calls back into Python when the data is available. So far, all well and dandy.</p>
<p>We've been i14ing (heh) our product, and one thing we'd like to do is format user-facing numerical output according to the user's locale settings. So, from Python, we do this:</p>
<pre><code>import locale
locale.setLocale( locale.LC_ALL, '' )
</code></pre>
<p>Now, this works (in that the user-facing numbers are formatted correctly for their locale). However, if the user's locale differs from the default C locale, any files that are subsequently loaded will return incorrect data, presumably because all string-to-float conversion has been affected, right down to the metal.</p>
<p>We can't work around this by implementing locale aware file loading, so our current workaround is to only set the locale when formatting output for the user, and then set it back again afterwards. That is, something like:</p>
<pre><code>import locale
currentLocale = locale.getLocale( locale.LC_ALL )
locale.setLocale( locale.LC_ALL, '' )
displayNumbersToTheUser()
locale.setlocale( locale.LC_ALL, currentLocale )
</code></pre>
<p>This seems a bit clunky, and I was wondering whether this is a common approach to formatting locale-aware output for the user? My other concern is that this is obviously not thread safe, so we'll presumably still get problems if any file parsing occurs in a separate thread when the locale is changed.</p>
<p>Any information on best practice is appreciated - I don't have much experience with this sort of thing.</p>
| 2 | 2008-09-26T15:38:00Z | 142,802 | <p>Setting the locale after multiple threads have started operating may have unexpected results. Unless I could figure out a more subtle approach, I'd probably just split file loading and the user interface into separate processes, communicating through a pipe or a file socket.</p>
| 1 | 2008-09-27T02:42:40Z | [
"python",
"internationalization",
"locale"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 140,495 | <p>I was missing </p>
<pre><code>l.set_option(ldap.OPT_REFERRALS, 0)
</code></pre>
<p>From the init.</p>
| 37 | 2008-09-26T16:18:18Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 140,737 | <p>Use a Distinguished Name to log on your system.<code>"CN=Your user,CN=Users,DC=b2t,DC=local"</code>
It should work on any LDAP system, including AD</p>
| 1 | 2008-09-26T17:14:23Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 141,729 | <p>If you are open to using pywin32, you can use Win32 calls from Python. This is what we do in our CherryPy web server:</p>
<pre><code>import win32security
token = win32security.LogonUser(
username,
domain,
password,
win32security.LOGON32_LOGON_NETWORK,
win32security.LOGON32_PROVIDER_DEFAULT)
authenticated = bool(token)
</code></pre>
| 22 | 2008-09-26T20:23:04Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 153,339 | <p>I see your comment to @Johan Buret about the DN not fixing your problem, but I also believe that is what you should look into.</p>
<p>Given your example, the DN for the default administrator account in AD will be:
cn=Administrator,cn=Users,dc=mydomain,dc=co,dc=uk - please try that.</p>
| 2 | 2008-09-30T14:36:49Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 1,126,391 | <p>That worked for me, <strong>l.set_option(ldap.OPT_REFERRALS, 0)</strong> was the key to access the ActiveDirectory. Moreover, I think that you should add an "con.unbind()" in order to close the connection before finishing the script.</p>
| 7 | 2009-07-14T16:02:22Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 1,126,427 | <p>If this is part of a webapp intended for authenticated ad-users, <a href="http://stackoverflow.com/questions/922805/spnego-kerberos-token-generation-validation-for-sso-using-python">this so question</a> might be of interest.</p>
| 0 | 2009-07-14T16:08:17Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 3,920,712 | <p>I tried to add</p>
<blockquote>
<p>l.set_option(ldap.OPT_REFERRALS, 0)</p>
</blockquote>
<p>but instead of an error Python just hangs and won't respond to anything any more. Maybe I'm building the search query wrong, what is the Base part of the search? I'm using the same as the DN for the simple bind (oh, and I had to do <code>l.simple_bind</code>, instead of <code>l.simple_bind_s</code>):</p>
<pre><code>import ldap
local = ldap.initialize("ldap://127.0.0.1")
local.simple_bind("CN=staff,DC=mydomain,DC=com")
#my pc is not actually connected to this domain
result_id = local.search("CN=staff,DC=mydomain,DC=com", ldap.SCOPE_SUBTREE, "cn=foobar", None)
local.set_option(ldap.OPT_REFERRALS, 0)
result_type, result_data = local.result(result_id, 0)
</code></pre>
<p>I'm using AD LDS and the instance is registered for the current account.</p>
| 0 | 2010-10-13T04:11:36Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 6,902,892 | <p>if you have Kerberos installed and talking to AD, as would be the case with, say, Centrify Express installed and running, you might just use python-kerberos. E.g.</p>
<pre><code>import kerberos
kerberos.checkPassword('joe','pizza','krbtgt/x.pizza.com','X.PIZZA.COM')`
</code></pre>
<p>would return True a user 'joe' has password 'pizza' in the Kerberos realm X.PIZZA.COM.
(typically, I think, the latter would be the same as the name of the AD Domain)</p>
| 3 | 2011-08-01T18:46:53Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 9,943,894 | <p>For me changing from <code>simple_bind_s()</code> to <code>bind()</code> did the trick.</p>
| 1 | 2012-03-30T13:25:44Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 18,282,435 | <p>Here's some simple code that works for me.</p>
<pre><code>import ldap # run 'pip install python-ldap' to install ldap module.
conn = ldap.open("ldaphost.company.com")
conn.simple_bind_s("myuser@company.com", "mypassword")
</code></pre>
<p>This is based on a <a href="http://stackoverflow.com/a/10743770/487992">previous answer</a>.</p>
| 1 | 2013-08-16T21:32:24Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Authenticating against active directory using python + ldap | 140,439 | <p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p>
<p>I can't even bind to perform a simple query:</p>
<pre><code>import sys
import ldap
Server = "ldap://my-ldap-server"
DN, Secret, un = sys.argv[1:4]
Base = "dc=mydomain,dc=co,dc=uk"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName"]
l = ldap.initialize(Server)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
sys.exit()
</code></pre>
<p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p>
<p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p>
<blockquote>
<p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p>
</blockquote>
<p>What am I missing out to bind properly?</p>
<p>I am getting the same errors on fedora and windows.</p>
| 70 | 2008-09-26T16:08:11Z | 38,348,468 | <p>I had the same issue, but it was regarding the password encoding</p>
<pre><code>.encode('iso-8859-1')
</code></pre>
<p>Solved the problem.</p>
| 0 | 2016-07-13T10:01:51Z | [
"python",
"authentication",
"active-directory",
"ldap"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 140,778 | <p>Straight from Python's Refererence Library</p>
<pre><code>>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
</code></pre>
| 2 | 2008-09-26T17:24:10Z | [
"java",
"python",
"file-traversal"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 140,795 | <p>Try "listdir()" in the os module (<a href="http://docs.python.org/lib/os-file-dir.html" rel="nofollow">docs</a>):</p>
<pre><code>import os
print os.listdir('.')
</code></pre>
| 3 | 2008-09-26T17:26:17Z | [
"java",
"python",
"file-traversal"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 140,805 | <p>Take a look at <code>os.walk()</code> and the examples <a href="http://docs.python.org/lib/os-file-dir.html" rel="nofollow">here</a>. With <code>os.walk()</code> you can easily process a whole directory tree. </p>
<p>An example from the link above...</p>
<pre><code># Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
</code></pre>
| 2 | 2008-09-26T17:27:59Z | [
"java",
"python",
"file-traversal"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 140,818 | <p>Yes, there is. The Python way is even better.</p>
<p>There are three possibilities:</p>
<p><strong>1) Like File.listFiles():</strong></p>
<p>Python has the function os.listdir(path). It works like the Java method.</p>
<p><strong>2) pathname pattern expansion with glob:</strong></p>
<p>The module glob contains functions to list files on the file system using Unix shell like pattern, e.g.
<code><pre>
files = glob.glob('/usr/joe/*.gif')
</pre></code></p>
<p><strong>3) File Traversal with walk:</strong></p>
<p>Really nice is the os.walk function of Python.</p>
<p>The walk method returns a generation function that recursively list all directories and files below a given starting path.</p>
<p>An Example:
<code><pre>
import os
from os.path import join
for root, dirs, files in os.walk('/usr'):
print "Current directory", root
print "Sub directories", dirs
print "Files", files
</pre></code>
You can even on the fly remove directories from "dirs" to avoid walking to that dir: if "joe" in dirs: dirs.remove("joe") to avoid walking into directories called "joe".</p>
<p>listdir and walk are documented <a href="http://docs.python.org/lib/os-file-dir.html">here</a>.
glob is documented <a href="http://docs.python.org/lib/module-glob.html">here</a>.</p>
| 25 | 2008-09-26T17:30:39Z | [
"java",
"python",
"file-traversal"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 140,822 | <p>Use os.path.walk if you want subdirectories as well.</p>
<pre>walk(top, func, arg)
Directory tree walk with callback function.
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
dirname is the name of the directory, and fnames a list of the names of
the files and subdirectories in dirname (excluding '.' and '..'). func
may modify the fnames list in-place (e.g. via del or slice assignment),
and walk will only recurse into the subdirectories whose names remain in
fnames; this can be used to implement a filter, or to impose a specific
order of visiting. No semantics are defined for, or required of, arg,
beyond that arg is always passed to func. It can be used, e.g., to pass
a filename pattern, or a mutable object designed to accumulate
statistics. Passing None for arg is common.
</pre>
| 2 | 2008-09-26T17:31:07Z | [
"java",
"python",
"file-traversal"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 141,277 | <p>I'd recommend against <code>os.path.walk</code> as it is being removed in Python 3.0. <code>os.walk</code> is simpler, anyway, or at least <em>I</em> find it simpler.</p>
| 2 | 2008-09-26T18:58:52Z | [
"java",
"python",
"file-traversal"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 143,227 | <p>As a long-time Pythonista, I have to say the path/file manipulation functions in the std library are sub-par: they are not object-oriented and they reflect an obsolete, lets-wrap-OS-system-functions-without-thinking philosophy. I'd heartily recommend the 'path' module as a wrapper (around os, os.path, glob and tempfile if you must know): much nicer and OOPy: <a href="http://pypi.python.org/pypi/path.py/2.2" rel="nofollow">http://pypi.python.org/pypi/path.py/2.2</a></p>
<p>This is walk() with the path module:</p>
<pre><code>dir = path(os.environ['HOME'])
for f in dir.walk():
if f.isfile() and f.endswith('~'):
f.remove()
</code></pre>
| 5 | 2008-09-27T08:27:39Z | [
"java",
"python",
"file-traversal"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 18,465,955 | <p>You can also check out <a href="https://github.com/mikeorr/Unipath" rel="nofollow">Unipath</a>, an object-oriented wrapper of Python's <code>os</code>, <code>os.path</code> and <code>shutil</code> modules.</p>
<p>Example:</p>
<pre><code>>>> from unipath import Path
>>> p = Path('/Users/kermit')
>>> p.listdir()
Path(u'/Users/kermit/Applications'),
Path(u'/Users/kermit/Desktop'),
Path(u'/Users/kermit/Documents'),
Path(u'/Users/kermit/Downloads'),
...
</code></pre>
<p>Installation through Cheese shop:</p>
<pre><code>$ pip install unipath
</code></pre>
| 1 | 2013-08-27T12:50:45Z | [
"java",
"python",
"file-traversal"
] |
Looking for File Traversal Functions in Python that are Like Java's | 140,758 | <p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p>
<p>Is there an analogous way to do this in Python?</p>
| 10 | 2008-09-26T17:20:14Z | 35,705,659 | <p>Seeing as i have programmed in python for a long time, i have many times used the os module and made my own function to print all files in a directory.</p>
<p>The code for the function:</p>
<pre><code>import os
def PrintFiles(direc):
files = os.listdir(direc)
for x in range(len(files)):
print("File no. "+str(x+1)+": "+files[x])
PrintFiles(direc)
</code></pre>
| 0 | 2016-02-29T17:26:59Z | [
"java",
"python",
"file-traversal"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 141,313 | <pre><code>directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]
</code></pre>
| 9 | 2008-09-26T19:04:46Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 141,317 | <p>Like so?</p>
<p>>>> [path for path in os.listdir(os.getcwd()) if os.path.isdir(path)]</p>
| 0 | 2008-09-26T19:05:26Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 141,318 | <pre><code>[x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]
</code></pre>
| 1 | 2008-09-26T19:05:26Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 141,327 | <p>Filter the result using os.path.isdir() (and use os.path.join() to get the real path):</p>
<pre><code>>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']
</code></pre>
| 61 | 2008-09-26T19:06:57Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 141,336 | <p>Filter the list using os.path.isdir to detect directories.</p>
<pre><code>filter(os.path.isdir, os.listdir(os.getcwd()))
</code></pre>
| 26 | 2008-09-26T19:10:36Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 142,368 | <p>Note that, instead of doing <code>os.listdir(os.getcwd())</code>, it's preferable to do <code>os.listdir(os.path.curdir)</code>. One less function call, and it's as portable.</p>
<p>So, to complete the answer, to get a list of directories in a folder:</p>
<pre><code>def listdirs(folder):
return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]
</code></pre>
<p>If you prefer full pathnames, then use this function:</p>
<pre><code>def listdirs(folder):
return [
d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
if os.path.isdir(d)
]
</code></pre>
| 8 | 2008-09-26T22:32:50Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 142,535 | <pre><code>os.walk('.').next()[1]
</code></pre>
| 99 | 2008-09-26T23:57:04Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 4,820,270 | <p>being a newbie here i can't yet directly comment but here is a small correction i'd like to add to the following part of <a href="http://stackoverflow.com/questions/141291/how-to-list-only-top-level-directories-in-python/142368#142368">ΤÎΩΤÎÎÎÎ¥'s answer</a> :</p>
<blockquote>
<p>If you prefer full pathnames, then use this function:</p>
<pre><code>def listdirs(folder):
return [
d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
if os.path.isdir(d)
]
</code></pre>
</blockquote>
<p><strong>for those still on python < 2.4</strong>: the inner construct needs to be a list instead of a tuple and therefore should read like this:</p>
<pre><code>def listdirs(folder):
return [
d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]
if os.path.isdir(d)
]
</code></pre>
<p>otherwise one gets a syntax error.</p>
| 2 | 2011-01-27T18:25:17Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 14,378,583 | <p>Just to add that using os.listdir() does not <em>"take a lot of processing vs very simple os.walk().next()[1]"</em>. This is because os.walk() uses os.listdir() internally. In fact if you test them together:</p>
<pre><code>>>>> import timeit
>>>> timeit.timeit("os.walk('.').next()[1]", "import os", number=10000)
1.1215229034423828
>>>> timeit.timeit("[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]", "import os", number=10000)
1.0592019557952881
</code></pre>
<p>The filtering of os.listdir() is very slightly faster.</p>
| 6 | 2013-01-17T11:57:25Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 15,521,489 | <p>For a list of full path names I prefer this version to the other <a href="http://stackoverflow.com/a/142368/2190476">solutions</a> here:</p>
<pre><code>def listdirs(dir):
return [os.path.join(os.path.join(dir, x)) for x in os.listdir(dir)
if os.path.isdir(os.path.join(dir, x))]
</code></pre>
| 1 | 2013-03-20T10:53:08Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 26,338,900 | <p>A very much simpler and elegant way is to use this:</p>
<pre><code> import os
dir_list = os.walk('.').next()[1]
print dir_list
</code></pre>
<p>Run this script in the same folder for which you want folder names.It will give you exactly the immediate folders name only(that too without the full path of the folders).</p>
| 5 | 2014-10-13T11:26:42Z | [
"python",
"filesystems"
] |
How to list only top level directories in Python? | 141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| 68 | 2008-09-26T19:01:06Z | 38,216,530 | <p>This seems to work too (at least on linux):</p>
<pre><code>import glob, os
glob.glob('*' + os.path.sep)
</code></pre>
| 1 | 2016-07-06T04:54:49Z | [
"python",
"filesystems"
] |
How do I find what is using memory in a Python process in a production system? | 141,351 | <p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p>
<p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="http://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
| 27 | 2008-09-26T19:13:14Z | 142,138 | <p>I don't know how to dump an entire python interpreter state and restore it. It would be useful, I'll keep my eye on this answer in case anyone else has ideas.</p>
<p>If you have an idea where the memory is leaking, you can add checks the refcounts of your objects. For example:</p>
<pre><code>x = SomeObject()
... later ...
oldRefCount = sys.getrefcount( x )
suspiciousFunction( x )
if (oldRefCount != sys.getrefcount(x)):
print "Possible memory leak..."
</code></pre>
<p>You could also check for reference counts higher than some number that is reasonable for your app. To take it further, you could modify the python interpreter to do these kinds of check by replacing the <code>Py_INCREF</code> and <code>Py_DECREF</code> macros with your own. This might be a bit dangerous in a production app, though.</p>
<p>Here is an essay with more info on debugging these sorts of things. It's more geared for plugin authors but most of it applies.</p>
<p><a href="http://www.python.org/doc/essays/refcnt/" rel="nofollow" title="Debugging Reference Counts">Debugging Reference Counts</a></p>
| 1 | 2008-09-26T21:37:03Z | [
"python",
"memory-leaks",
"coredump"
] |
How do I find what is using memory in a Python process in a production system? | 141,351 | <p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p>
<p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="http://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
| 27 | 2008-09-26T19:13:14Z | 142,177 | <p>The <a href="http://docs.python.org/lib/module-gc.html" rel="nofollow"><code>gc</code> module</a> has some functions that might be useful, like listing all objects the garbage collector found to be unreachable but cannot free, or a list of all objects being tracked.</p>
<p>If you have a suspicion which objects might leak, the <a href="http://docs.python.org/lib/module-weakref.html" rel="nofollow">weakref</a> module could be handy to find out if/when objects are collected.</p>
| 1 | 2008-09-26T21:45:10Z | [
"python",
"memory-leaks",
"coredump"
] |
How do I find what is using memory in a Python process in a production system? | 141,351 | <p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p>
<p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="http://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
| 27 | 2008-09-26T19:13:14Z | 142,500 | <p>Could you record the traffic (via a log) on your production site, then re-play it on your development server instrumented with a python memory debugger? (I recommend dozer: <a href="http://pypi.python.org/pypi/Dozer" rel="nofollow">http://pypi.python.org/pypi/Dozer</a>)</p>
| 3 | 2008-09-26T23:41:01Z | [
"python",
"memory-leaks",
"coredump"
] |
How do I find what is using memory in a Python process in a production system? | 141,351 | <p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p>
<p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="http://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
| 27 | 2008-09-26T19:13:14Z | 142,571 | <p><a href="http://www.gsp.com/cgi-bin/man.cgi?section=1&topic=gcore" rel="nofollow">Make your program dump core</a>, then clone an instance of the program on a sufficiently similar box using <a href="http://www.gsp.com/cgi-bin/man.cgi?section=1&topic=gdb" rel="nofollow">gdb</a>. There are <a href="http://wiki.python.org/moin/DebuggingWithGdb" rel="nofollow">special macros</a> to help with debugging python programs within gdb, but if you can get your program to concurrently <a href="http://blog.vrplumber.com/index.php?/archives/1631-Minimal-example-of-using-twisted.manhole-Since-it-took-me-so-long-to-get-it-working....html" rel="nofollow">serve up a remote shell</a>, you could just continue the program's execution, and query it with python.</p>
<p>I have never had to do this, so I'm not 100% sure it'll work, but perhaps the pointers will be helpful.</p>
| 2 | 2008-09-27T00:11:08Z | [
"python",
"memory-leaks",
"coredump"
] |
How do I find what is using memory in a Python process in a production system? | 141,351 | <p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p>
<p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="http://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
| 27 | 2008-09-26T19:13:14Z | 2,170,051 | <p><a href="https://edge.launchpad.net/meliae" rel="nofollow">Meliae</a> looks promising:</p>
<blockquote>
<p>This project is similar to heapy (in the 'guppy' project), in its attempt to understand how memory has been allocated.</p>
<p>Currently, its main difference is that it splits the task of computing summary statistics, etc of memory consumption from the actual scanning of memory consumption. It does this, because I often want to figure out what is going on in my process, while my process is consuming huge amounts of memory (1GB, etc). It also allows dramatically simplifying the scanner, as I don't allocate python objects while trying to analyze python object memory consumption.</p>
</blockquote>
| 2 | 2010-01-31T00:16:42Z | [
"python",
"memory-leaks",
"coredump"
] |
How do I find what is using memory in a Python process in a production system? | 141,351 | <p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p>
<p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="http://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
| 27 | 2008-09-26T19:13:14Z | 9,567,831 | <p>Using Python's <code>gc</code> garbage collector interface and <code>sys.getsizeof()</code> it's possible to dump all the python objects and their sizes. Here's the code I'm using in production to troubleshoot a memory leak:</p>
<pre><code>rss = psutil.Process(os.getpid()).get_memory_info().rss
# Dump variables if using more than 100MB of memory
if rss > 100 * 1024 * 1024:
memory_dump()
os.abort()
def memory_dump():
dump = open("memory.pickle", 'w')
for obj in gc.get_objects():
i = id(obj)
size = sys.getsizeof(obj, 0)
# referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]
referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]
if hasattr(obj, '__class__'):
cls = str(obj.__class__)
cPickle.dump({'id': i, 'class': cls, 'size': size, 'referents': referents}, dump)
</code></pre>
<p>Note that I'm only saving data from objects that have a <code>__class__</code> attribute because those are the only objects I care about. It should be possible to save the complete list of objects, but you will need to take care choosing other attributes. Also, I found that getting the referrers for each object was extremely slow so I opted to save only the referents. Anyway, after the crash, the resulting pickled data can be read back like this:</p>
<pre><code>dump = open("memory.pickle")
while dump:
obj = cPickle.load(dump)
</code></pre>
| 18 | 2012-03-05T13:56:17Z | [
"python",
"memory-leaks",
"coredump"
] |
How can I create a status bar item with Cocoa and Python (PyObjC)? | 141,432 | <p>I have created a brand new project in XCode and have the following in my AppDelegate.py file:</p>
<pre><code>from Foundation import *
from AppKit import *
class MyApplicationAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setTitle_(u"12%")
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
</code></pre>
<p>However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.</p>
| 8 | 2008-09-26T19:29:48Z | 142,162 | <p>I had to do this to make it work:</p>
<ol>
<li><p>Open MainMenu.xib. Make sure the class of the app delegate is <code>MyApplicationAppDelegate</code>. I'm not sure if you will have to do this, but I did. It was wrong and so the app delegate never got called in the first place.</p></li>
<li><p>Add <code>statusItem.retain()</code> because it gets autoreleased right away.</p></li>
</ol>
| 5 | 2008-09-26T21:41:54Z | [
"python",
"cocoa",
"pyobjc"
] |
How can I create a status bar item with Cocoa and Python (PyObjC)? | 141,432 | <p>I have created a brand new project in XCode and have the following in my AppDelegate.py file:</p>
<pre><code>from Foundation import *
from AppKit import *
class MyApplicationAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setTitle_(u"12%")
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
</code></pre>
<p>However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.</p>
| 8 | 2008-09-26T19:29:48Z | 4,379,633 | <p>The above usage of .retain() is required because the statusItem is being destroyed upon return from the applicationDidFinishLaunching() method. Bind that variable as a field in instances of MyApplicationAppDelegate using self.statusItem instead.</p>
<p>Here is a modified example that does not require a .xib / etc...</p>
<pre><code>from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
start_time = NSDate.date()
class MyApplicationAppDelegate(NSObject):
state = 'idle'
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
self.statusItem.setTitle_(u"Hello World")
self.statusItem.setHighlightMode_(TRUE)
self.statusItem.setEnabled_(TRUE)
# Get the timer going
self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 5.0, self, 'tick:', None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
self.timer.fire()
def sync_(self, notification):
print "sync"
def tick_(self, notification):
print self.state
if __name__ == "__main__":
app = NSApplication.sharedApplication()
delegate = MyApplicationAppDelegate.alloc().init()
app.setDelegate_(delegate)
AppHelper.runEventLoop()
</code></pre>
| 4 | 2010-12-07T17:27:19Z | [
"python",
"cocoa",
"pyobjc"
] |
How do I wrap a string in a file in Python? | 141,449 | <p>How do I create a file-like object (same duck type as File) with the contents of a string?</p>
| 49 | 2008-09-26T19:33:55Z | 141,451 | <p>Use the <a href="https://docs.python.org/2/library/stringio.html" rel="nofollow">StringIO</a> module. For example:</p>
<pre><code>>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
</code></pre>
<p>I use cStringIO (which is faster), but note that it doesn't <a href="http://docs.python.org/lib/module-cStringIO.html" rel="nofollow">accept Unicode strings that cannot be encoded as plain ASCII strings</a>. (You can switch to StringIO by changing "from cStringIO" to "from StringIO".)</p>
| 67 | 2008-09-26T19:34:04Z | [
"python",
"string",
"file",
"wrap"
] |
How do I wrap a string in a file in Python? | 141,449 | <p>How do I create a file-like object (same duck type as File) with the contents of a string?</p>
| 49 | 2008-09-26T19:33:55Z | 142,251 | <p>In Python 3.0:</p>
<pre><code>import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
</code></pre>
| 19 | 2008-09-26T22:00:25Z | [
"python",
"string",
"file",
"wrap"
] |
How do I wrap a string in a file in Python? | 141,449 | <p>How do I create a file-like object (same duck type as File) with the contents of a string?</p>
| 49 | 2008-09-26T19:33:55Z | 143,532 | <p>Two good answers. Iâd add a little trick â if you need a real file object (some methods expect one, not just an interface), here is a way to create an adapter:</p>
<ul>
<li><a href="http://www.rfk.id.au/software/filelike/" rel="nofollow">http://www.rfk.id.au/software/filelike/</a></li>
</ul>
| 1 | 2008-09-27T12:19:45Z | [
"python",
"string",
"file",
"wrap"
] |
Is there an easy way to populate SlugField from CharField? | 141,487 | <pre><code>class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
</code></pre>
<p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
| 20 | 2008-09-26T19:40:57Z | 141,505 | <p>For pre-1.0:</p>
<pre><code>slug = models.SlugField(prepopulate_from=('title',))
</code></pre>
<p>should work just fine</p>
<p>For 1.0, use <a href="http://stackoverflow.com/questions/141487/is-there-an-easy-way-to-populate-slugfield-from-charfield#141554">camflan's</a></p>
| 4 | 2008-09-26T19:44:31Z | [
"python",
"django",
"slug"
] |
Is there an easy way to populate SlugField from CharField? | 141,487 | <pre><code>class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
</code></pre>
<p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
| 20 | 2008-09-26T19:40:57Z | 141,554 | <p>for Admin in Django 1.0 and up, you'd need to use</p>
<pre><code>prepopulated_fields = {'slug': ('title',), }
</code></pre>
<p>in your admin.py</p>
<p>Your key in the prepopulated_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.</p>
<p>Outside of admin, you can use the <code>slugify</code> function in your views. In templates, you can use the <code>|slugify</code> filter.</p>
<p>There is also this package which will take care of this automatically: <a href="https://pypi.python.org/pypi/django-autoslug">https://pypi.python.org/pypi/django-autoslug</a></p>
| 43 | 2008-09-26T19:51:46Z | [
"python",
"django",
"slug"
] |
Is there an easy way to populate SlugField from CharField? | 141,487 | <pre><code>class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
</code></pre>
<p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
| 20 | 2008-09-26T19:40:57Z | 141,947 | <p>Outside the admin, see <a href="http://www.djangosnippets.org/snippets/690/">this django snippet</a>. Put it in your <code>.save()</code>, and it'll work with objects created programmatically. Inside the admin, as the others have said, use <code>prepopulated_fields</code>.</p>
| 5 | 2008-09-26T20:59:49Z | [
"python",
"django",
"slug"
] |
Is there an easy way to populate SlugField from CharField? | 141,487 | <pre><code>class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
</code></pre>
<p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
| 20 | 2008-09-26T19:40:57Z | 153,028 | <p>You can also use pre_save django signal to populate slug outside of django admin code.
See <a href="http://docs.djangoproject.com/en/dev/ref/signals/" rel="nofollow">Django signals documentation</a>.</p>
<p>Ajax slug uniqueness validation will be useful too, see <a href="http://lethain.com/entry/2008/sep/26/as-you-type-slug-uniqueness-validation/" rel="nofollow">As-You-Type Slug Uniqueness Validation @ Irrational Exuberance</a></p>
| 2 | 2008-09-30T13:31:04Z | [
"python",
"django",
"slug"
] |
Is there an easy way to populate SlugField from CharField? | 141,487 | <pre><code>class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
</code></pre>
<p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
| 20 | 2008-09-26T19:40:57Z | 7,470,874 | <p><a href="https://bitbucket.org/neithere/django-autoslug" rel="nofollow">autoslug</a> has worked quite well for me in the past. Although I've never tried using it with the admin app.</p>
| 0 | 2011-09-19T12:23:49Z | [
"python",
"django",
"slug"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 141,565 | <p>A better way would be to use isinstance and type conversion. If I'm understanding you right, you want this:</p>
<pre><code>def __init__ (self, filename):
if isinstance (filename, basestring):
# filename is a string
else:
# try to convert to a list
self.path = list (filename)
</code></pre>
| 6 | 2008-09-26T19:52:59Z | [
"python",
"constructor",
"operator-overloading"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 141,570 | <p>You probably want the <code>isinstance</code> builtin function:</p>
<pre><code>self.data = data if isinstance(data, list) else self.parse(data)
</code></pre>
| 2 | 2008-09-26T19:54:30Z | [
"python",
"constructor",
"operator-overloading"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 141,571 | <p>You should use isinstance</p>
<pre><code>isinstance(...)
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
</code></pre>
| 3 | 2008-09-26T19:54:33Z | [
"python",
"constructor",
"operator-overloading"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 141,700 | <p>OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.</p>
<pre><code>class MyData:
def __init__(self, data):
self.myList = []
if isinstance(data, tuple):
for i in data:
self.myList.append(i)
else:
self.myList = data
def GetData(self):
print self.myList
</code></pre>
<p>a = [1,2]</p>
<p>b = (2,3)</p>
<p>c = MyData(a)</p>
<p>d = MyData(b)</p>
<p>c.GetData()</p>
<p>d.GetData()</p>
<p>[1, 2]</p>
<p>[2, 3]</p>
| -1 | 2008-09-26T20:18:19Z | [
"python",
"constructor",
"operator-overloading"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 141,777 | <p>A much neater way to get 'alternate constructors' is to use classmethods. For instance:</p>
<pre><code>>>> class MyData:
... def __init__(self, data):
... "Initialize MyData from a sequence"
... self.data = data
...
... @classmethod
... def fromfilename(cls, filename):
... "Initialize MyData from a file"
... data = open(filename).readlines()
... return cls(data)
...
... @classmethod
... def fromdict(cls, datadict):
... "Initialize MyData from a dict's items"
... return cls(datadict.items())
...
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]
</code></pre>
<p>The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with <code>isinstance(x, basestring)</code> is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.</p>
| 257 | 2008-09-26T20:30:15Z | [
"python",
"constructor",
"operator-overloading"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 212,130 | <p>Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:</p>
<p>Here's a sample (this is a <code>read</code> method and not a constructor, but the idea is the same):</p>
<pre><code>def read(self, str=None, filename=None, addr=0):
""" Read binary data and return a store object. The data
store is also saved in the interal 'data' attribute.
The data can either be taken from a string (str
argument) or a file (provide a filename, which will
be read in binary mode). If both are provided, the str
will be used. If neither is provided, an ArgumentError
is raised.
"""
if str is None:
if filename is None:
raise ArgumentError('Please supply a string or a filename')
file = open(filename, 'rb')
str = file.read()
file.close()
...
... # rest of code
</code></pre>
<p>The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:</p>
<pre><code>obj.read(filename="blob.txt")
</code></pre>
<p>And to read it from a string, I say:</p>
<pre><code>obj.read(str="\x34\x55")
</code></pre>
<p>This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex</p>
| 26 | 2008-10-17T13:34:31Z | [
"python",
"constructor",
"operator-overloading"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 10,218,436 | <p>Quick and dirty fix</p>
<pre><code>class MyData:
def __init__(string=None,list=None):
if string is not None:
#do stuff
elif list is not None:
#do other stuff
else:
#make data empty
</code></pre>
<p>Then you can call it with</p>
<pre><code>MyData(astring)
MyData(None, alist)
MyData()
</code></pre>
| 6 | 2012-04-18T21:38:33Z | [
"python",
"constructor",
"operator-overloading"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 23,415,425 | <p>Why don't you go even more pythonic?
</p>
<pre><code>class AutoList:
def __init__(self, inp):
try: ## Assume an opened-file...
self.data = inp.read()
except AttributeError:
try: ## Assume an existent filename...
with open(inp, 'r') as fd:
self.data = fd.read()
except:
self.data = inp ## Who cares what that might be?
</code></pre>
| -1 | 2014-05-01T19:49:07Z | [
"python",
"constructor",
"operator-overloading"
] |
overloading __init__ in python | 141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
<p>Thanks.</p>
| 186 | 2008-09-26T19:49:46Z | 26,018,762 | <p>My preferred solution is:</p>
<pre><code>class MyClass:
_data = []
__init__(self,data=None):
# do init stuff
if not data: return
self._data = list(data) # list() copies the list, instead of pointing to it.
</code></pre>
<p>Then invoke it with either <code>MyClass()</code> or <code>MyClass([1,2,3])</code>.</p>
<p>Hope that helps. Happy Coding!</p>
| 0 | 2014-09-24T13:55:57Z | [
"python",
"constructor",
"operator-overloading"
] |
What limitations have closures in Python compared to language X closures? | 141,642 | <p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="http://stackoverflow.com/questions/36636/what-is-a-closure">What is a âClosureâ?</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
| 40 | 2008-09-26T20:06:41Z | 141,670 | <p>The only difficulty I've seen people encounter with Python's in particular is when they try to mix non-functional features like variable reassignment with closures, and are surprised when this doesn't work:</p>
<pre><code>def outer ():
x = 1
def inner ():
print x
x = 2
return inner
outer () ()
</code></pre>
<p>Usually just pointing out that a function has its own local variables is enough to deter such silliness.</p>
| 6 | 2008-09-26T20:11:53Z | [
"python",
"closures"
] |
What limitations have closures in Python compared to language X closures? | 141,642 | <p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="http://stackoverflow.com/questions/36636/what-is-a-closure">What is a âClosureâ?</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
| 40 | 2008-09-26T20:06:41Z | 141,710 | <p>The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only:</p>
<pre><code>>>> def outer(x):
... def inner_reads():
... # Will return outer's 'x'.
... return x
... def inner_writes(y):
... # Will assign to a local 'x', not the outer 'x'
... x = y
... def inner_error(y):
... # Will produce an error: 'x' is local because of the assignment,
... # but we use it before it is assigned to.
... tmp = x
... x = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
5
>>> inner_error(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in inner_error
UnboundLocalError: local variable 'x' referenced before assignment
</code></pre>
<p>A name that gets assigned to in a local scope (a function) is always local, unless declared otherwise. While there is the 'global' declaration to declare a variable global even when it is assigned to, there is no such declaration for enclosed variables -- yet. In Python 3.0, there is (will be) the 'nonlocal' declaration that does just that.</p>
<p>You can work around this limitation in the mean time by using a mutable container type:</p>
<pre><code>>>> def outer(x):
... x = [x]
... def inner_reads():
... # Will return outer's x's first (and only) element.
... return x[0]
... def inner_writes(y):
... # Will look up outer's x, then mutate it.
... x[0] = y
... def inner_error(y):
... # Will now work, because 'x' is not assigned to, just referenced.
... tmp = x[0]
... x[0] = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
10
>>> inner_error(15)
10
>>> inner_reads()
15
</code></pre>
| 39 | 2008-09-26T20:19:27Z | [
"python",
"closures"
] |
What limitations have closures in Python compared to language X closures? | 141,642 | <p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="http://stackoverflow.com/questions/36636/what-is-a-closure">What is a âClosureâ?</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
| 40 | 2008-09-26T20:06:41Z | 141,744 | <p>@<a href="#141670" rel="nofollow">John Millikin</a></p>
<pre><code>def outer():
x = 1 # local to `outer()`
def inner():
x = 2 # local to `inner()`
print(x)
x = 3
return x
def inner2():
nonlocal x
print(x) # local to `outer()`
x = 4 # change `x`, it is not local to `inner2()`
return x
x = 5 # local to `outer()`
return (inner, inner2)
for inner in outer():
print(inner())
# -> 2 3 5 4
</code></pre>
| 2 | 2008-09-26T20:25:13Z | [
"python",
"closures"
] |
What limitations have closures in Python compared to language X closures? | 141,642 | <p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="http://stackoverflow.com/questions/36636/what-is-a-closure">What is a âClosureâ?</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
| 40 | 2008-09-26T20:06:41Z | 141,767 | <p>Fixed in Python 3 via the <a href="https://docs.python.org/3/reference/simple_stmts.html?#nonlocal" rel="nofollow"><code>nonlocal</code></a> statement:</p>
<blockquote>
<p>The <code>nonlocal</code> statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.</p>
</blockquote>
| 3 | 2008-09-26T20:29:21Z | [
"python",
"closures"
] |
What limitations have closures in Python compared to language X closures? | 141,642 | <p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="http://stackoverflow.com/questions/36636/what-is-a-closure">What is a âClosureâ?</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
| 40 | 2008-09-26T20:06:41Z | 141,881 | <p><sub>comment for <a href="http://stackoverflow.com/a/141767/4279">@Kevin Little's answer</a> to include the code example</sub></p>
<p><code>nonlocal</code> does not solve completely this problem on python3.0:</p>
<pre><code>x = 0 # global x
def outer():
x = 1 # local to `outer`
def inner():
global x
x = 2 # change global
print(x)
x = 3 # change global
return x
def inner2():
## nonlocal x # can't use `nonlocal` here
print(x) # prints global
## x = 4 # can't change `x` here
return x
x = 5
return (inner, inner2)
for inner in outer():
print(inner())
# -> 2 3 3 3
</code></pre>
<p>On the other hand:</p>
<pre><code>x = 0
def outer():
x = 1 # local to `outer`
def inner():
## global x
x = 2
print(x) # local to `inner`
x = 3
return x
def inner2():
nonlocal x
print(x)
x = 4 # local to `outer`
return x
x = 5
return (inner, inner2)
for inner in outer():
print(inner())
# -> 2 3 5 4
</code></pre>
<p>it works on python3.1-3.3</p>
| 2 | 2008-09-26T20:47:39Z | [
"python",
"closures"
] |
What limitations have closures in Python compared to language X closures? | 141,642 | <p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="http://stackoverflow.com/questions/36636/what-is-a-closure">What is a âClosureâ?</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
| 40 | 2008-09-26T20:06:41Z | 989,166 | <p>The better workaround until 3.0 is to include the variable as a defaulted parameter in the enclosed function definition:</p>
<pre>
def f()
x = 5
def g(y, z, x=x):
x = x + 1
</pre>
| -1 | 2009-06-12T21:33:32Z | [
"python",
"closures"
] |
What limitations have closures in Python compared to language X closures? | 141,642 | <p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="http://stackoverflow.com/questions/36636/what-is-a-closure">What is a âClosureâ?</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
| 40 | 2008-09-26T20:06:41Z | 6,990,028 | <p>A limitation (or "limitation") of Python closures, comparing to Javascript closures, is that it <strong>cannot</strong> be used for effective <strong>data hiding</strong></p>
<h3>Javascript</h3>
<pre><code>var mksecretmaker = function(){
var secrets = [];
var mksecret = function() {
secrets.push(Math.random())
}
return mksecret
}
var secretmaker = mksecretmaker();
secretmaker(); secretmaker()
// privately generated secret number list
// is practically inaccessible
</code></pre>
<h3>Python</h3>
<pre><code>import random
def mksecretmaker():
secrets = []
def mksecret():
secrets.append(random.random())
return mksecret
secretmaker = mksecretmaker()
secretmaker(); secretmaker()
# "secrets" are easily accessible,
# it's difficult to hide something in Python:
secretmaker.__closure__[0].cell_contents # -> e.g. [0.680752847190161, 0.9068475951742101]
</code></pre>
| 6 | 2011-08-09T00:05:36Z | [
"python",
"closures"
] |
Socket programming for mobile phones in Python | 141,647 | <p>I've written code for communication between my phone and comp thru TCP sockets. When I type out the code line by line in the interactive console it works fine. However, when i try running the script directly through filebrowser.py it just wont work. I'm using Nokia N95. Is there anyway I can run this script directly without using filebrowser.py?
Am new to Python for mobile phones, so any suggestions would be appreciated.
Thanks</p>
| 1 | 2008-09-26T20:07:55Z | 142,379 | <p>Have you read <a href="http://pramode.net/articles/lfy/mobile/pramode.html" rel="nofollow">Hack a Mobile Phone with Linux and Python</a>? It is rather old, but maybe you find it helpful.</p>
| 1 | 2008-09-26T22:36:02Z | [
"python",
"sockets",
"mobile"
] |
Socket programming for mobile phones in Python | 141,647 | <p>I've written code for communication between my phone and comp thru TCP sockets. When I type out the code line by line in the interactive console it works fine. However, when i try running the script directly through filebrowser.py it just wont work. I'm using Nokia N95. Is there anyway I can run this script directly without using filebrowser.py?
Am new to Python for mobile phones, so any suggestions would be appreciated.
Thanks</p>
| 1 | 2008-09-26T20:07:55Z | 142,502 | <p>If the code is working in the interactive interpreter when typed, but not when run directly then I would suggest seeing if your code has reached a deadlock on the socket, for example both ends are waiting for data from the other. When typing into the interactive interpreter there is a longer delay between the execution of each line on code.</p>
| 0 | 2008-09-26T23:42:08Z | [
"python",
"sockets",
"mobile"
] |
Socket programming for mobile phones in Python | 141,647 | <p>I've written code for communication between my phone and comp thru TCP sockets. When I type out the code line by line in the interactive console it works fine. However, when i try running the script directly through filebrowser.py it just wont work. I'm using Nokia N95. Is there anyway I can run this script directly without using filebrowser.py?
Am new to Python for mobile phones, so any suggestions would be appreciated.
Thanks</p>
| 1 | 2008-09-26T20:07:55Z | 142,786 | <p>Well, it doesn't appear to be a deadlock situation. It throws an error saying remote server refused connection. However, like I said before, if i type the very same code into the interactive interpreter it works just fine. I'm wondering if the error is because the script is run through filebrowser.py?</p>
| 0 | 2008-09-27T02:31:34Z | [
"python",
"sockets",
"mobile"
] |
Socket programming for mobile phones in Python | 141,647 | <p>I've written code for communication between my phone and comp thru TCP sockets. When I type out the code line by line in the interactive console it works fine. However, when i try running the script directly through filebrowser.py it just wont work. I'm using Nokia N95. Is there anyway I can run this script directly without using filebrowser.py?
Am new to Python for mobile phones, so any suggestions would be appreciated.
Thanks</p>
| 1 | 2008-09-26T20:07:55Z | 215,001 | <p>Don't you have the "Run script" menu in your interactive Python shell? </p>
| 0 | 2008-10-18T12:53:33Z | [
"python",
"sockets",
"mobile"
] |
How do I dump an entire Python process for later debugging inspection? | 141,802 | <p>I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.</p>
<p>(This is a variation on my question about <a href="http://stackoverflow.com/questions/141351/how-do-i-find-what-is-using-memory-in-a-python-process-in-a-production-system">debugging memleaks in a production system</a>.)</p>
| 17 | 2008-09-26T20:34:19Z | 141,826 | <p>There is no builtin way other than aborting (with os.abort(), causing the coredump if resource limits allow it) -- although you can certainly build your own 'dump' function that dumps relevant information about the data you care about. There are no ready-made tools for it.</p>
<p>As for handling the corefile of a Python process, the <a href="http://svn.python.org/projects/python/trunk/Misc/gdbinit" rel="nofollow">Python source has a gdbinit file</a> that contains useful macros. It's still a lot more painful than somehow getting into the process itself (with pdb or the interactive interpreter) but it makes life a little easier.</p>
| 4 | 2008-09-26T20:38:17Z | [
"python",
"debugging",
"coredump"
] |
How do I dump an entire Python process for later debugging inspection? | 141,802 | <p>I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.</p>
<p>(This is a variation on my question about <a href="http://stackoverflow.com/questions/141351/how-do-i-find-what-is-using-memory-in-a-python-process-in-a-production-system">debugging memleaks in a production system</a>.)</p>
| 17 | 2008-09-26T20:34:19Z | 142,103 | <p>Someone above said that there is no builtin way to perform this, but that's not entirely true. For an example, you could take a look at the pylons debugging tools. Whene there is an exception, the exception handler saves the stack trace and prints a URL on the console that can be used to retrieve the debugging session over HTTP.</p>
<p>While they're probably keeping these sessions in memory, they're just python objects, so there's nothing to stop you from pickling a stack dump and restoring it later for inspection. It would mean some changes to the app, but it should be possible...</p>
<p>After some research, it turns out the relevant code is actually coming from Paste's <a href="http://svn.pythonpaste.org/Paste/trunk/paste/evalexception/evalcontext.py" rel="nofollow">EvalException module</a>. You should be able to look there to figure out what you need.</p>
| 1 | 2008-09-26T21:30:33Z | [
"python",
"debugging",
"coredump"
] |
How do I dump an entire Python process for later debugging inspection? | 141,802 | <p>I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.</p>
<p>(This is a variation on my question about <a href="http://stackoverflow.com/questions/141351/how-do-i-find-what-is-using-memory-in-a-python-process-in-a-production-system">debugging memleaks in a production system</a>.)</p>
| 17 | 2008-09-26T20:34:19Z | 142,582 | <p><a href="http://stackoverflow.com/questions/141351/how-do-i-find-what-is-using-memory-in-a-python-process-in-a-production-system#142571">This answer</a> suggests making your program core dump and then continuing execution on another sufficiently similar box.</p>
| 0 | 2008-09-27T00:15:31Z | [
"python",
"debugging",
"coredump"
] |
How do I dump an entire Python process for later debugging inspection? | 141,802 | <p>I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.</p>
<p>(This is a variation on my question about <a href="http://stackoverflow.com/questions/141351/how-do-i-find-what-is-using-memory-in-a-python-process-in-a-production-system">debugging memleaks in a production system</a>.)</p>
| 17 | 2008-09-26T20:34:19Z | 12,690,278 | <p>It's also possible to write something that would dump all the <strong>data</strong> from the process, e.g.</p>
<ul>
<li>Pickler that ignores the objects it can't pickle (replacing them with something else) (e.g. <a href="http://stackoverflow.com/questions/4080688/">Python: Pickling a dict with some unpicklable items</a>)</li>
<li>Method that recursively converts everything into serializable stuff (e.g. <a href="https://github.com/HoverHell/pyaux/blob/36d7f1b2cf7aadec5db1d97f1ba8c93331517764/pyaux/__init__.py#L289" rel="nofollow">this</a>, except it needs a check for infinitely recursing objects and do something with those; also it could try <code>dir()</code> and <code>getattr()</code> to process some of the unknown objects, e.g. extension classes).</li>
</ul>
<p>But leaving a running process with manhole or pylons or something like that certainly seems more convenient when possible.</p>
<p>(also, I wonder if something more convenient was written since this question was first asked)</p>
| 0 | 2012-10-02T12:30:03Z | [
"python",
"debugging",
"coredump"
] |
How do I get the key value of a db.ReferenceProperty without a database hit? | 141,973 | <p>Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks.</p>
<p>EDIT: Here is what I have unsuccessfully tried:</p>
<pre><code>class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return self._series
</code></pre>
<p>And in my template:</p>
<pre><code><a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a>
</code></pre>
<p>The result:</p>
<pre><code><a href="games/view-series.html?series=#comm59">more</a>
</code></pre>
| 1 | 2008-09-26T21:05:25Z | 142,106 | <p>You're correct - the key is stored as the property name prefixed with '_'. You should just be able to access it directly on the model object. Can you demonstrate what you're trying? I've used this technique in the past with no problems.</p>
<p>Edit: Have you tried calling series_id() directly, or referencing _series in your template directly? I'm not sure whether Django automatically calls methods with no arguments if you specify them in this context. You could also try putting the @property decorator on the method.</p>
| 1 | 2008-09-26T21:30:58Z | [
"python",
"google-app-engine"
] |
How do I get the key value of a db.ReferenceProperty without a database hit? | 141,973 | <p>Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks.</p>
<p>EDIT: Here is what I have unsuccessfully tried:</p>
<pre><code>class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return self._series
</code></pre>
<p>And in my template:</p>
<pre><code><a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a>
</code></pre>
<p>The result:</p>
<pre><code><a href="games/view-series.html?series=#comm59">more</a>
</code></pre>
| 1 | 2008-09-26T21:05:25Z | 164,870 | <p>Actually, the way that you are advocating accessing the key for a ReferenceProperty might well not exist in the future. Attributes that begin with '_' in python are generally accepted to be "protected" in that things that are closely bound and intimate with its implementation can use them, but things that are updated with the implementation must change when it changes.</p>
<p>However, there is a way through the public interface that you can access the key for your reference-property so that it will be safe in the future. I'll revise the above example:</p>
<pre><code>class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return Comment.series.get_value_for_datastore(self)
</code></pre>
<p>When you access properties via the class it is associated, you get the property object itself, which has a public method that can get the underlying values.</p>
| 13 | 2008-10-02T22:17:40Z | [
"python",
"google-app-engine"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 142,561 | <p>This sounds like modifying the <code>__builtin__</code> name space. To do it:</p>
<pre><code>import __builtin__
__builtin__.foo = 'some-value'
</code></pre>
<p>Do not use the <code>__builtins__</code> directly (notice the extra "s") - apparently this can be a dictionary or a module. Thanks to ΤÎΩΤÎÎÎÎ¥ for pointing this out, more can be found <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/1907d5e660444c08/69c29c4ec0c4d3ec" rel="nofollow" title="here">here</a>.</p>
<p>Now <code>foo</code> is available for use everywhere.</p>
<p>I don't recommend doing this generally, but the use of this is up to the programmer.</p>
<p>Assigning to it must be done as above, just setting <code>foo = 'some-other-value'</code> will only set it in the current namespace.</p>
| 2 | 2008-09-27T00:08:25Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 142,566 | <p>I don't endorse this solution in any way, shape or form. But if you add a variable to the <code>__builtin__</code> module, it will be accessible as if a global from any other module that includes <code>__builtin__</code> -- which is all of them, by default.</p>
<p>a.py contains</p>
<pre><code>print foo
</code></pre>
<p>b.py contains</p>
<pre><code>import __builtin__
__builtin__.foo = 1
import a
</code></pre>
<p>The result is that "1" is printed.</p>
<p><strong>Edit:</strong> The <code>__builtin__</code> module is available as the local symbol <code>__builtins__</code> -- that's the reason for the discrepancy between two of these answers. Also note that <code>__builtin__</code> has been renamed to <code>builtins</code> in python3.</p>
| 75 | 2008-09-27T00:09:29Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 142,581 | <p>Define a module ( call it "globalbaz" ) and have the variables defined inside it. All the modules using this "pseudoglobal" should import the "globalbaz" module, and refer to it using "globalbaz.var_name"</p>
<p>This works regardless of the place of the change, you can change the variable before or after the import. The imported module will use the latest value. (I tested this in a toy example)</p>
<p>For clarification, globalbaz.py looks just like this:</p>
<pre><code>var_name = "my_useful_string"
</code></pre>
| 17 | 2008-09-27T00:15:19Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 142,601 | <p>If you need a global cross-module variable maybe just simple global module-level variable will suffice. </p>
<p>a.py:</p>
<pre><code>var = 1
</code></pre>
<p>b.py:</p>
<pre><code>import a
print a.var
import c
print a.var
</code></pre>
<p>c.py:</p>
<pre><code>import a
a.var = 2
</code></pre>
<p>Test:</p>
<pre><code>$ python b.py
# -> 1 2
</code></pre>
<p>Real-world example: <a href="https://github.com/django/django/blob/master/django/conf/global_settings.py">Django's global_settings.py</a> (though in Django apps settings are used by importing the <em>object</em> <a href="http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in-python-code"><code>django.conf.settings</code></a>).</p>
| 101 | 2008-09-27T00:25:00Z | [
"python",
"module",
"global"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.