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 |
---|---|---|---|---|---|---|---|---|---|
Organising my Python project | 391,879 | <p>I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).</p>
<p>If I put a file to import in a folder I can no longer import it. How do I import a file from another folder and will I need to reference to the class it contains differently now that it's in a folder?</p>
<p>Thanks in advance</p>
| 45 | 2008-12-24T17:23:14Z | 391,916 | <p>"As is good practice I want to put them in a separate file each. "</p>
<p>This is not actually a very good practice. You should design modules that contain closely-related classes.</p>
<p>As a practical matter, no class actually stands completely alone. Generally classes come in clusters or groups that are logically related. </p>
| 22 | 2008-12-24T17:42:54Z | [
"python",
"project-organization"
] |
Python Optparse list | 392,041 | <p>I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values.</p>
<p>For example:</p>
<pre><code>--groups one,two,three.
</code></pre>
<p>I'd like to be able to access these values in a list format as <code>options.groups[]</code>. Is there an optparse option to convert comma separated values into a list? Or do I have to do this manually?</p>
| 33 | 2008-12-24T18:54:52Z | 392,061 | <p>Look at <a href="http://docs.python.org/2/library/optparse#option-callbacks" rel="nofollow">option callbacks</a>. Your callback function can parse the value into a list using a basic <code>optarg.split(',')</code></p>
| 35 | 2008-12-24T19:03:51Z | [
"python",
"optparse"
] |
Python Optparse list | 392,041 | <p>I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values.</p>
<p>For example:</p>
<pre><code>--groups one,two,three.
</code></pre>
<p>I'd like to be able to access these values in a list format as <code>options.groups[]</code>. Is there an optparse option to convert comma separated values into a list? Or do I have to do this manually?</p>
| 33 | 2008-12-24T18:54:52Z | 392,258 | <p>S.Lott's answer has already been accepted, but here's a code sample for the archives:</p>
<pre><code>def foo_callback(option, opt, value, parser):
setattr(parser.values, option.dest, value.split(','))
parser = OptionParser()
parser.add_option('-f', '--foo',
type='string',
action='callback',
callback=foo_callback)
</code></pre>
| 73 | 2008-12-24T21:50:34Z | [
"python",
"optparse"
] |
Python Optparse list | 392,041 | <p>I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values.</p>
<p>For example:</p>
<pre><code>--groups one,two,three.
</code></pre>
<p>I'd like to be able to access these values in a list format as <code>options.groups[]</code>. Is there an optparse option to convert comma separated values into a list? Or do I have to do this manually?</p>
| 33 | 2008-12-24T18:54:52Z | 29,301,200 | <p>Again, just for the sake of archive completeness, expanding the example above:</p>
<ul>
<li>You can still use "dest" to specify the option name for later access</li>
<li>Default values cannot be used in such cases (see explanation in <a href="http://stackoverflow.com/questions/14568141/triggering-callback-on-default-value-in-optparse">Triggering callback on default value in optparse</a>)</li>
<li>If you'd like to validate the input, OptionValueError should be thrown from foo_callback</li>
</ul>
<p>The code (with tiny changes) would then be:</p>
<pre><code>def get_comma_separated_args(option, opt, value, parser):
setattr(parser.values, option.dest, value.split(','))
parser = OptionParser()
parser.add_option('-f', '--foo',
type='string',
action='callback',
callback=get_comma_separated_args,
dest = foo_args_list)
</code></pre>
| 7 | 2015-03-27T12:53:43Z | [
"python",
"optparse"
] |
wxPython and sharing objects between windows | 392,100 | <p>I've been working with python for a while now and am just starting to learn wxPython. After creating a few little programs, I'm having difficulty understanding how to create objects that can be shared between dialogs.</p>
<p>Here's some code as an example (apologies for the length - I've tried to trim):</p>
<pre><code>import wx
class ExampleFrame(wx.Frame):
"""The main GUI"""
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(200,75))
mainSizer = wx.BoxSizer(wx.VERTICAL)
# Setup buttons
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
playerButton = wx.Button(self, wx.ID_ANY, "Player number", wx.DefaultPosition, wx.DefaultSize, 0)
buttonSizer.Add(playerButton, 1, wx.ALL | wx.EXPAND, 0)
nameButton = wx.Button(self, wx.ID_ANY, "Player name", wx.DefaultPosition, wx.DefaultSize, 0)
buttonSizer.Add(nameButton, 1, wx.ALL | wx.EXPAND, 0)
# Complete layout and add statusbar
mainSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the events
playerButton.Bind(wx.EVT_BUTTON, self.playerButtonEvent)
nameButton.Bind(wx.EVT_BUTTON, self.nameButtonEvent)
self.Show(True)
return
def playerButtonEvent(self, event):
"""Displays the number of game players"""
playerDialog = PlayerDialogWindow(None, -1, "Player")
playerDialogResult = playerDialog.ShowModal()
playerDialog.Destroy()
return
def nameButtonEvent(self, event):
"""Displays the names of game players"""
nameDialog = NameDialogWindow(None, -1, "Name")
nameDialogResult = nameDialog.ShowModal()
nameDialog.Destroy()
return
class PlayerDialogWindow(wx.Dialog):
"""Displays the player number"""
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(200,120))
# Setup layout items
self.SetAutoLayout(True)
mainSizer = wx.BoxSizer(wx.VERTICAL)
dialogPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
dialogSizer = wx.BoxSizer(wx.VERTICAL)
# Display player number
playerNumber = "Player number is %i" % gamePlayer.number
newLabel = wx.StaticText(dialogPanel, wx.ID_ANY, playerNumber, wx.DefaultPosition, wx.DefaultSize, 0)
dialogSizer.Add(newLabel, 0, wx.ALL | wx.EXPAND, 5)
# Setup buttons
buttonSizer = wx.StdDialogButtonSizer()
okButton = wx.Button(dialogPanel, wx.ID_OK)
buttonSizer.AddButton(okButton)
buttonSizer.Realize()
dialogSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
# Complete layout
dialogPanel.SetSizer(dialogSizer)
dialogPanel.Layout()
dialogSizer.Fit(dialogPanel)
mainSizer.Add(dialogPanel, 1, wx.ALL | wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the button events
okButton.Bind(wx.EVT_BUTTON, self.okClick)
return
def okClick(self, event):
"""Deals with the user clicking the ok button"""
self.EndModal(wx.ID_OK)
return
class NameDialogWindow(wx.Dialog):
"""Displays the player name"""
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(200,120))
# Setup layout items
self.SetAutoLayout(True)
mainSizer = wx.BoxSizer(wx.VERTICAL)
dialogPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
dialogSizer = wx.BoxSizer(wx.VERTICAL)
# Display player number
playerNumber = "Player name is %s" % gamePlayer.name
newLabel = wx.StaticText(dialogPanel, wx.ID_ANY, playerNumber, wx.DefaultPosition, wx.DefaultSize, 0)
dialogSizer.Add(newLabel, 0, wx.ALL | wx.EXPAND, 5)
# Setup buttons
buttonSizer = wx.StdDialogButtonSizer()
okButton = wx.Button(dialogPanel, wx.ID_OK)
buttonSizer.AddButton(okButton)
buttonSizer.Realize()
dialogSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
# Complete layout
dialogPanel.SetSizer(dialogSizer)
dialogPanel.Layout()
dialogSizer.Fit(dialogPanel)
mainSizer.Add(dialogPanel, 1, wx.ALL | wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the button events
okButton.Bind(wx.EVT_BUTTON, self.okClick)
return
def okClick(self, event):
"""Deals with the user clicking the ok button"""
self.EndModal(wx.ID_OK)
return
class Player(object):
"""A game player"""
def __init__(self, number, name):
self.number = number
self.name = name
return
def main():
# Start GUI
global gamePlayer
gamePlayer = Player(1, "John Smith")
app = wx.App(redirect=False)
frame = ExampleFrame(None, -1, "Example frame")
frame.Show(True)
app.MainLoop()
return 0
if __name__ == '__main__':
main()
</code></pre>
<p>So, I want both of the dialogs to access the gamePlayer object. At the moment, the only way I can think of doing it is to create the gamePlayer object as a global object, but these are normally frowned upon - is there a better way to do this?</p>
<p>There is a method of passing objects in event bindings in <a href="http://stackoverflow.com/questions/173687?sort=votes" rel="nofollow">this question</a>, but it doesn't feel quite right.</p>
<p>Is learning to implement the MVC pattern the way forward here?</p>
<p>Thanks.</p>
| 2 | 2008-12-24T19:30:01Z | 392,125 | <p>You can pass a gamePlayer object to <code>__init__</code> as another argument.</p>
<pre><code>def __init__(self, parent, id, title, gamePlayer ):
...etc...
</code></pre>
<p>In the long run, this isn't ideal. </p>
<p>You should separate building an empty panel from loading that panel with data. The empty panel is one thing, populating it with data from the model is unrelated.</p>
<p>Populating a frame with data is where you must be given the gamePlayer object which will be used to update the various display widgets.</p>
<p>I'd suggest you look at the Document-View framework for guidance on this. <a href="http://docs.wxwidgets.org/stable/wx_docviewoverview.html#docviewoverview" rel="nofollow">http://docs.wxwidgets.org/stable/wx_docviewoverview.html#docviewoverview</a>. Unfortunately, there aren't any good Python examples of this, so it can be confusing to convert from the C++ code to Python.</p>
<p>Ultimately, you have a "document" which is the main object ("gamePlayer") that is being displayed. Each Frame is a view of that document.</p>
| 3 | 2008-12-24T19:42:02Z | [
"python",
"wxpython"
] |
wxPython and sharing objects between windows | 392,100 | <p>I've been working with python for a while now and am just starting to learn wxPython. After creating a few little programs, I'm having difficulty understanding how to create objects that can be shared between dialogs.</p>
<p>Here's some code as an example (apologies for the length - I've tried to trim):</p>
<pre><code>import wx
class ExampleFrame(wx.Frame):
"""The main GUI"""
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(200,75))
mainSizer = wx.BoxSizer(wx.VERTICAL)
# Setup buttons
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
playerButton = wx.Button(self, wx.ID_ANY, "Player number", wx.DefaultPosition, wx.DefaultSize, 0)
buttonSizer.Add(playerButton, 1, wx.ALL | wx.EXPAND, 0)
nameButton = wx.Button(self, wx.ID_ANY, "Player name", wx.DefaultPosition, wx.DefaultSize, 0)
buttonSizer.Add(nameButton, 1, wx.ALL | wx.EXPAND, 0)
# Complete layout and add statusbar
mainSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the events
playerButton.Bind(wx.EVT_BUTTON, self.playerButtonEvent)
nameButton.Bind(wx.EVT_BUTTON, self.nameButtonEvent)
self.Show(True)
return
def playerButtonEvent(self, event):
"""Displays the number of game players"""
playerDialog = PlayerDialogWindow(None, -1, "Player")
playerDialogResult = playerDialog.ShowModal()
playerDialog.Destroy()
return
def nameButtonEvent(self, event):
"""Displays the names of game players"""
nameDialog = NameDialogWindow(None, -1, "Name")
nameDialogResult = nameDialog.ShowModal()
nameDialog.Destroy()
return
class PlayerDialogWindow(wx.Dialog):
"""Displays the player number"""
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(200,120))
# Setup layout items
self.SetAutoLayout(True)
mainSizer = wx.BoxSizer(wx.VERTICAL)
dialogPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
dialogSizer = wx.BoxSizer(wx.VERTICAL)
# Display player number
playerNumber = "Player number is %i" % gamePlayer.number
newLabel = wx.StaticText(dialogPanel, wx.ID_ANY, playerNumber, wx.DefaultPosition, wx.DefaultSize, 0)
dialogSizer.Add(newLabel, 0, wx.ALL | wx.EXPAND, 5)
# Setup buttons
buttonSizer = wx.StdDialogButtonSizer()
okButton = wx.Button(dialogPanel, wx.ID_OK)
buttonSizer.AddButton(okButton)
buttonSizer.Realize()
dialogSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
# Complete layout
dialogPanel.SetSizer(dialogSizer)
dialogPanel.Layout()
dialogSizer.Fit(dialogPanel)
mainSizer.Add(dialogPanel, 1, wx.ALL | wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the button events
okButton.Bind(wx.EVT_BUTTON, self.okClick)
return
def okClick(self, event):
"""Deals with the user clicking the ok button"""
self.EndModal(wx.ID_OK)
return
class NameDialogWindow(wx.Dialog):
"""Displays the player name"""
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(200,120))
# Setup layout items
self.SetAutoLayout(True)
mainSizer = wx.BoxSizer(wx.VERTICAL)
dialogPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
dialogSizer = wx.BoxSizer(wx.VERTICAL)
# Display player number
playerNumber = "Player name is %s" % gamePlayer.name
newLabel = wx.StaticText(dialogPanel, wx.ID_ANY, playerNumber, wx.DefaultPosition, wx.DefaultSize, 0)
dialogSizer.Add(newLabel, 0, wx.ALL | wx.EXPAND, 5)
# Setup buttons
buttonSizer = wx.StdDialogButtonSizer()
okButton = wx.Button(dialogPanel, wx.ID_OK)
buttonSizer.AddButton(okButton)
buttonSizer.Realize()
dialogSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
# Complete layout
dialogPanel.SetSizer(dialogSizer)
dialogPanel.Layout()
dialogSizer.Fit(dialogPanel)
mainSizer.Add(dialogPanel, 1, wx.ALL | wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the button events
okButton.Bind(wx.EVT_BUTTON, self.okClick)
return
def okClick(self, event):
"""Deals with the user clicking the ok button"""
self.EndModal(wx.ID_OK)
return
class Player(object):
"""A game player"""
def __init__(self, number, name):
self.number = number
self.name = name
return
def main():
# Start GUI
global gamePlayer
gamePlayer = Player(1, "John Smith")
app = wx.App(redirect=False)
frame = ExampleFrame(None, -1, "Example frame")
frame.Show(True)
app.MainLoop()
return 0
if __name__ == '__main__':
main()
</code></pre>
<p>So, I want both of the dialogs to access the gamePlayer object. At the moment, the only way I can think of doing it is to create the gamePlayer object as a global object, but these are normally frowned upon - is there a better way to do this?</p>
<p>There is a method of passing objects in event bindings in <a href="http://stackoverflow.com/questions/173687?sort=votes" rel="nofollow">this question</a>, but it doesn't feel quite right.</p>
<p>Is learning to implement the MVC pattern the way forward here?</p>
<p>Thanks.</p>
| 2 | 2008-12-24T19:30:01Z | 20,334,493 | <p>A Model-View-Controller (MVC) framework allows you to access common data (Model) and display it in your GUI (Views) through a Controller. A good explanation is found here:</p>
<p><a href="http://wiki.wxpython.org/ModelViewController" rel="nofollow">MVC Framework for wxPython</a></p>
<p>Basically, you avoid tangled messes by not allowing the model to talk to the views directly, but rather posting to a controller that it has made changes. The controller then updates the views appropriately. Likewise for updating the model from controls on you gui. This way the model and view code are independent, and they are tied together with the controller code that access the APIs of each.</p>
| 1 | 2013-12-02T17:42:28Z | [
"python",
"wxpython"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 392,230 | <p>You never absolutely <em>need</em> to use a metaclass, since you can always construct a class that does what you want using inheritance or aggregation of the class you want to modify.</p>
<p>That said, it can be very handy in Smalltalk and Ruby to be able to modify an existing class, but Python doesn't like to do that directly.</p>
<p>There's an excellent <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">DeveloperWorks article</a> on metaclassing in Python that might help. The <a href="http://en.wikipedia.org/wiki/Metaclass" rel="nofollow">Wikipedia article</a> is also pretty good.</p>
| 4 | 2008-12-24T21:17:25Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 392,232 | <p>The only time I used metaclasses in Python was when writing a wrapper for the Flickr API. </p>
<p>My goal was to scrape <a href="http://www.flickr.com/services/api/" rel="nofollow">flickr's api site</a> and dynamically generate a complete class hierarchy to allow API access using Python objects:</p>
<pre><code># Both the photo type and the flickr.photos.search API method
# are generated at "run-time"
for photo in flickr.photos.search(text=balloons):
print photo.description
</code></pre>
<p>So in that example, because I generated the entire Python Flickr API from the website, I really don't know the class definitions at runtime. Being able to dynamically generate types was very useful. </p>
| 4 | 2008-12-24T21:19:39Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 392,255 | <p>The purpose of metaclasses isn't to replace the class/object distinction with metaclass/class - it's to change the behaviour of class definitions (and thus their instances) in some way. Effectively it's to alter the behaviour of the class statement in ways that may be more useful for your particular domain than the default. The things I have used them for are:</p>
<ul>
<li><p>Tracking subclasses, usually to register handlers. This is handy when using a plugin style setup, where you wish to register a handler for a particular thing simply by subclassing and setting up a few class attributes. eg. suppose you write a handler for various music formats, where each class implements appropriate methods (play / get tags etc) for its type. Adding a handler for a new type becomes:</p>
<pre><code>class Mp3File(MusicFile):
extensions = ['.mp3'] # Register this type as a handler for mp3 files
...
# Implementation of mp3 methods go here
</code></pre>
<p>The metaclass then maintains a dictionary of <code>{'.mp3' : MP3File, ... }</code> etc, and constructs an object of the appropriate type when you request a handler through a factory function.</p></li>
<li><p>Changing behaviour. You may want to attach a special meaning to certain attributes, resulting in altered behaviour when they are present. For example, you may want to look for methods with the name <code>_get_foo</code> and <code>_set_foo</code> and transparently convert them to properties. As a real-world example, <a href="http://code.activestate.com/recipes/498149/">here's</a> a recipe I wrote to give more C-like struct definitions. The metaclass is used to convert the declared items into a struct format string, handling inheritance etc, and produce a class capable of dealing with it.</p>
<p>For other real-world examples, take a look at various ORMs, like <a href="http://www.sqlalchemy.org/">sqlalchemy's</a> ORM or <a href="http://www.sqlobject.org/">sqlobject</a>. Again, the purpose is to interpret defintions (here SQL column definitions) with a particular meaning.</p></li>
</ul>
| 27 | 2008-12-24T21:43:05Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 392,278 | <p>Metaclasses aren't replacing programming! They're just a trick which can automate or make more elegant some tasks. A good example of this is <a href="http://pygments.org/" rel="nofollow">Pygments</a> syntax highlighting library. It has a class called <code>RegexLexer</code> which lets the user define a set of lexing rules as regular expressions on a class. A metaclass is used to turn the definitions into a useful parser.</p>
<p>They're like salt; it's easy to use too much.</p>
| 3 | 2008-12-24T22:15:22Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 392,308 | <p>Metaclasses can be handy for construction of Domain Specific Languages in Python. Concrete examples are Django, SQLObject 's declarative syntax of database schemata. </p>
<p>A basic example from <a href="http://blog.ianbicking.org/a-conservative-metaclass.html" rel="nofollow">A Conservative Metaclass</a> by Ian Bicking:</p>
<blockquote>
<p>The metaclasses I've used have been
primarily to support a sort of
declarative style of programming. For
instance, consider a validation
schema:</p>
</blockquote>
<pre><code>class Registration(schema.Schema):
first_name = validators.String(notEmpty=True)
last_name = validators.String(notEmpty=True)
mi = validators.MaxLength(1)
class Numbers(foreach.ForEach):
class Number(schema.Schema):
type = validators.OneOf(['home', 'work'])
phone_number = validators.PhoneNumber()
</code></pre>
<p>Some other techniques: <a href="http://web.archive.org/web/20091229094610/http://media.brianbeck.com/files/Python_DSLs_I.pdf" rel="nofollow">Ingredients for Building a DSL in Python</a> (pdf). </p>
<p>Edit (by Ali): An example of doing this using collections and instances is what I would prefer. The important fact is the instances, which give you more power, and eliminate reason to use metaclasses. Further worth noting that your example uses a mixture of classes and instances, which is surely an indication that you can't just do it all with metaclasses. And creates a truly non-uniform way of doing it.</p>
<pre><code>number_validator = [
v.OneOf('type', ['home', 'work']),
v.PhoneNumber('phone_number'),
]
validators = [
v.String('first_name', notEmpty=True),
v.String('last_name', notEmpty=True),
v.MaxLength('mi', 1),
v.ForEach([number_validator,])
]
</code></pre>
<p>It's not perfect, but already there is almost zero magic, no need for metaclasses, and improved uniformity.</p>
| 6 | 2008-12-24T22:54:53Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 392,442 | <p>Let's start with Tim Peter's classic quote:</p>
<blockquote>
<p>Metaclasses are deeper magic than 99%
of users should ever worry about. If
you wonder whether you need them, you
don't (the people who actually need
them know with certainty that they
need them, and don't need an
explanation about why). Tim Peters
(c.l.p post 2002-12-22)</p>
</blockquote>
<p>Having said that, I have (periodically) run across true uses of metaclasses. The one that comes to mind is in Django where all of your models inherit from models.Model. models.Model, in turn, does some serious magic to wrap your DB models with Django's ORM goodness. That magic happens by way of metaclasses. It creates all manner of exception classes, manager classes, etc. etc.</p>
<p>See django/db/models/base.py, class ModelBase() for the beginning of the story. </p>
| 12 | 2008-12-25T02:23:47Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 392,767 | <p>The way I used metaclasses was to provide some attributes to classes. Take for example:</p>
<pre><code>class NameClass(type):
def __init__(cls, *args, **kwargs):
type.__init__(cls, *args, **kwargs)
cls.name = cls.__name__
</code></pre>
<p>will put the <em>name</em> attribute on every class that will have the metaclass set to point to NameClass.</p>
| 3 | 2008-12-25T11:47:43Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 393,368 | <p>I have a class that handles non-interactive plotting, as a frontend to Matplotlib. However, on occasion one wants to do interactive plotting. With only a couple functions I found that I was able to increment the figure count, call draw manually, etc, but I needed to do these before and after every plotting call. So to create both an interactive plotting wrapper and an offscreen plotting wrapper, I found it was more efficient to do this via metaclasses, wrapping the appropriate methods, than to do something like:</p>
<pre><code>class PlottingInteractive:
add_slice = wrap_pylab_newplot(add_slice)
</code></pre>
<p>This method doesn't keep up with API changes and so on, but one that iterates over the class attributes in <code>__init__</code> before re-setting the class attributes is more efficient and keeps things up to date:</p>
<pre><code>class _Interactify(type):
def __init__(cls, name, bases, d):
super(_Interactify, cls).__init__(name, bases, d)
for base in bases:
for attrname in dir(base):
if attrname in d: continue # If overridden, don't reset
attr = getattr(cls, attrname)
if type(attr) == types.MethodType:
if attrname.startswith("add_"):
setattr(cls, attrname, wrap_pylab_newplot(attr))
elif attrname.startswith("set_"):
setattr(cls, attrname, wrap_pylab_show(attr))
</code></pre>
<p>Of course, there might be better ways to do this, but I've found this to be effective. Of course, this could also be done in <code>__new__</code> or <code>__init__</code>, but this was the solution I found the most straightforward.</p>
| 10 | 2008-12-26T01:35:56Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 395,751 | <p>I was thinking the same thing just yesterday and completely agree. The complications in the code caused by attempts to make it more declarative generally make the codebase harder to maintain, harder to read and less pythonic in my opinion.
It also normally requires a lot of copy.copy()ing (to maintain inheritance and to copy from class to instance) and means you have to look in many places to see whats going on (always looking from metaclass up) which goes against the python grain also.
I have been picking through formencode and sqlalchemy code to see if such a declarative style was worth it and its clearly not. Such style should be left to descriptors (such as property and methods) and immutable data.
Ruby has better support for such declarative styles and I am glad the core python language is not going down that route.</p>
<p>I can see their use for debugging, add a metaclass to all your base classes to get richer info.
I also see their use only in (very) large projects to get rid of some boilerplate code (but at the loss of clarity). sqlalchemy for <a href="http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/lib/sqlalchemy/sql/visitors.py">example</a> does use them elsewhere, to add a particular custom method to all subclasses based on an attribute value in their class definition
e.g a toy example</p>
<pre><code>class test(baseclass_with_metaclass):
method_maker_value = "hello"
</code></pre>
<p>could have a metaclass that generated a method in that class with special properties based on "hello" (say a method that added "hello" to the end of a string). It could be good for maintainability to make sure you did not have to write a method in every subclass you make instead all you have to define is method_maker_value. </p>
<p>The need for this is so rare though and only cuts down on a bit of typing that its not really worth considering unless you have a large enough codebase.</p>
| 5 | 2008-12-28T03:20:15Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 5,330,521 | <p>The only legitimate use-case of a metaclass is to keep other nosy developers from touching your code. Once a nosy developer masters metaclasses and starts poking around with yours, throw in another level or two to keep them out. If that doesn't work, start using type.<strong>new</strong> or perhaps some scheme using a recursive metaclass.</p>
<p>(written tongue in cheek, but I've seen this kind of obfuscation done. Django is a perfect example)</p>
| 2 | 2011-03-16T19:13:50Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 7,057,480 | <p>A reasonable pattern of metaclass use is doing something once when a class is defined rather than repeatedly whenever the same class is instantiated. </p>
<p>When multiple classes share the same special behaviour, repeating <strong>__metaclass__=X</strong> is obviously better than repeating the special purpose code and/or introducing ad-hoc shared superclasses.</p>
<p>But even with only one special class and no foreseeable extension, <strong>__new__</strong> and <strong>__init__</strong> of a metaclass are a cleaner way to initialize class variables or other global data than intermixing special-purpose code and normal <strong>def</strong> and <strong>class</strong> statements in the class definition body.</p>
| 4 | 2011-08-14T14:49:02Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 7,058,179 | <p>This is a minor use, but... one thing I've found metaclasses useful for is to invoke a function whenever a subclass is created. I codified this into a metaclass which looks for an <code>__initsubclass__</code> attribute: whenever a subclass is created, all parent classes which define that method are invoked with <code>__initsubclass__(cls, subcls)</code>. This allows creation of a parent class which then registers all subclasses with some global registry, runs invariant checks on subclasses whenever they are defined, perform late-binding operations, etc... all without have to manually call functions <em>or</em> to create custom metaclasses that perform each of these separate duties. </p>
<p>Mind you, I've slowly come to realize the implicit magicalness of this behavior is somewhat undesirable, since it's unexpected if looking at a class definition out of context... and so I've moved away from using that solution for anything serious besides initializing a <code>__super</code> attribute for each class and instance. </p>
| 2 | 2011-08-14T16:44:08Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 16,925,938 | <p>Some GUI libraries have trouble when multiple threads try to interact with them. <code>tkinter</code> is one such example; and while one can explicitly handle the problem with events and queues, it can be far simpler to use the library in a manner that ignores the problem altogether. Behold -- the magic of metaclasses.</p>
<p>Being able to dynamically rewrite an entire library seamlessly so that it works properly as expected in a multithreaded application can be extremely helpful in some circumstances. The <a href="http://code.activestate.com/recipes/578153/" rel="nofollow">safetkinter</a> module does that with the help of a metaclass provided by the <a href="http://code.activestate.com/recipes/578152/" rel="nofollow">threadbox</a> module -- events and queues not needed.</p>
<p>One neat aspect of <code>threadbox</code> is that it does not care what class it clones. It provides an example of how all base classes can be touched by a metaclass if needed. A further benefit that comes with metaclasses is that they run on inheriting classes as well. Programs that write themselves -- why not?</p>
| 3 | 2013-06-04T19:29:42Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 19,865,575 | <p>I recently had to use a metaclass to help declaratively define an SQLAlchemy model around a database table populated with U.S. Census data from <a href="http://census.ire.org/data/bulkdata.html" rel="nofollow">http://census.ire.org/data/bulkdata.html</a></p>
<p>IRE provides <a href="https://github.com/ireapps/census/tree/master/tools/sql/ire_export" rel="nofollow">database shells</a> for the census data tables, which create integer columns following a naming convention from the Census Bureau of p012015, p012016, p012017, etc.</p>
<p>I wanted to a) be able to access these columns using a <code>model_instance.p012017</code> syntax, b) be fairly explicit about what I was doing and c) not have to explicitly define dozens of fields on the model, so I subclassed SQLAlchemy's <code>DeclarativeMeta</code> to iterate through a range of the columns and automatically create model fields corresponding to the columns:</p>
<pre><code>from sqlalchemy.ext.declarative.api import DeclarativeMeta
class CensusTableMeta(DeclarativeMeta):
def __init__(cls, classname, bases, dict_):
table = 'p012'
for i in range(1, 49):
fname = "%s%03d" % (table, i)
dict_[fname] = Column(Integer)
setattr(cls, fname, dict_[fname])
super(CensusTableMeta, cls).__init__(classname, bases, dict_)
</code></pre>
<p>I could then use this metaclass for my model definition and access the automatically enumerated fields on the model:</p>
<pre><code>CensusTableBase = declarative_base(metaclass=CensusTableMeta)
class P12Tract(CensusTableBase):
__tablename__ = 'ire_p12'
geoid = Column(String(12), primary_key=True)
@property
def male_under_5(self):
return self.p012003
...
</code></pre>
| 1 | 2013-11-08T17:59:56Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 23,853,525 | <p>There seems to be a legitimate use described <a href="http://www.jesshamrick.com/2013/04/17/rewriting-python-docstrings-with-a-metaclass/" rel="nofollow">here</a> - Rewriting Python Docstrings with a Metaclass.</p>
| 1 | 2014-05-25T08:44:58Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 31,061,875 | <p>I was asked the same question recently, and came up with several answers. I hope it's OK to revive this thread, as I wanted to elaborate on a few of the use cases mentioned, and add a few new ones.</p>
<p>Most metaclasses I've seen do one of two things:</p>
<ol>
<li><p>Registration (adding a class to a data structure):</p>
<pre><code>models = {}
class ModelMetaclass(type):
def __new__(meta, name, bases, attrs):
models[name] = cls = type.__new__(meta, name, bases, attrs)
return cls
class Model(object):
__metaclass__ = ModelMetaclass
</code></pre>
<p>Whenever you subclass <code>Model</code>, your class is registered in the <code>models</code> dictionary:</p>
<pre><code>>>> class A(Model):
... pass
...
>>> class B(A):
... pass
...
>>> models
{'A': <__main__.A class at 0x...>,
'B': <__main__.B class at 0x...>}
</code></pre>
<p>This can also be done with class decorators:</p>
<pre><code>models = {}
def model(cls):
models[cls.__name__] = cls
return cls
@model
class A(object):
pass
</code></pre>
<p>Or with an explicit registration function:</p>
<pre><code>models = {}
def register_model(cls):
models[cls.__name__] = cls
class A(object):
pass
register_model(A)
</code></pre>
<p>Actually, this is pretty much the same: you mention class decorators unfavorably, but it's really nothing more than syntactic sugar for a function invocation on a class, so there's no magic about it.</p>
<p>Anyway, the advantage of metaclasses in this case is inheritance, as they work for any subclasses, whereas the other solutions only work for subclasses explicitly decorated or registered.</p>
<pre><code>>>> class B(A):
... pass
...
>>> models
{'A': <__main__.A class at 0x...> # No B :(
</code></pre></li>
<li><p>Refactoring (modifying class attributes or adding new ones):</p>
<pre><code>class ModelMetaclass(type):
def __new__(meta, name, bases, attrs):
fields = {}
for key, value in attrs.items():
if isinstance(value, Field):
value.name = '%s.%s' % (name, key)
fields[key] = value
for base in bases:
if hasattr(base, '_fields'):
fields.update(base._fields)
attrs['_fields'] = fields
return type.__new__(meta, name, bases, attrs)
class Model(object):
__metaclass__ = ModelMetaclass
</code></pre>
<p>Whenever you subclass <code>Model</code> and define some <code>Field</code> attributes, they are injected with their names (for more informative error messages, for example), and grouped into a <code>_fields</code> dictionary (for easy iteration, without having to look through all the class attributes and all its base classes' attributes every time):</p>
<pre><code>>>> class A(Model):
... foo = Integer()
...
>>> class B(A):
... bar = String()
...
>>> B._fields
{'foo': Integer('A.foo'), 'bar': String('B.bar')}
</code></pre>
<p>Again, this can be done (without inheritance) with a class decorator:</p>
<pre><code>def model(cls):
fields = {}
for key, value in vars(cls).items():
if isinstance(value, Field):
value.name = '%s.%s' % (cls.__name__, key)
fields[key] = value
for base in cls.__bases__:
if hasattr(base, '_fields'):
fields.update(base._fields)
cls._fields = fields
return cls
@model
class A(object):
foo = Integer()
class B(A):
bar = String()
# B.bar has no name :(
# B._fields is {'foo': Integer('A.foo')} :(
</code></pre>
<p>Or explicitly:</p>
<pre><code>class A(object):
foo = Integer('A.foo')
_fields = {'foo': foo} # Don't forget all the base classes' fields, too!
</code></pre>
<p>Although, on the contrary to your advocacy for readable and maintainable non-meta programming, this is much more cumbersome, redundant and error prone:</p>
<pre><code>class B(A):
bar = String()
# vs.
class B(A):
bar = String('bar')
_fields = {'B.bar': bar, 'A.foo': A.foo}
</code></pre></li>
</ol>
<p>Having considered the most common and concrete use cases, the only cases where you absolutely HAVE to use metaclasses are when you want to modify the class name or list of base classes, because once defined, these parameters are baked into the class, and no decorator or function can unbake them.</p>
<pre><code>class Metaclass(type):
def __new__(meta, name, bases, attrs):
return type.__new__(meta, 'foo', (int,), attrs)
class Baseclass(object):
__metaclass__ = Metaclass
class A(Baseclass):
pass
class B(A):
pass
print A.__name__ # foo
print B.__name__ # foo
print issubclass(B, A) # False
print issubclass(B, int) # True
</code></pre>
<p>This may be useful in frameworks for issuing warnings whenever classes with similar names or incomplete inheritance trees are defined, but I can't think of a reason beside trolling to actually change these values. Maybe David Beazley can.</p>
<p>Anyway, in Python 3, metaclasses also have the <code>__prepare__</code> method, which lets you evaluate the class body into a mapping other than a <code>dict</code>, thus supporting ordered attributes, overloaded attributes, and other wicked cool stuff:</p>
<pre><code>import collections
class Metaclass(type):
@classmethod
def __prepare__(meta, name, bases, **kwds):
return collections.OrderedDict()
def __new__(meta, name, bases, attrs, **kwds):
print(list(attrs))
# Do more stuff...
class A(metaclass=Metaclass):
x = 1
y = 2
# prints ['x', 'y'] rather than ['y', 'x']
</code></pre>
<p>Â </p>
<pre><code>class ListDict(dict):
def __setitem__(self, key, value):
self.setdefault(key, []).append(value)
class Metaclass(type):
@classmethod
def __prepare__(meta, name, bases, **kwds):
return ListDict()
def __new__(meta, name, bases, attrs, **kwds):
print(attrs['foo'])
# Do more stuff...
class A(metaclass=Metaclass):
def foo(self):
pass
def foo(self, x):
pass
# prints [<function foo at 0x...>, <function foo at 0x...>] rather than <function foo at 0x...>
</code></pre>
<p>You might argue ordered attributes can be achieved with creation counters, and overloading can be simulated with default arguments:</p>
<pre><code>import itertools
class Attribute(object):
_counter = itertools.count()
def __init__(self):
self._count = Attribute._counter.next()
class A(object):
x = Attribute()
y = Attribute()
A._order = sorted([(k, v) for k, v in vars(A).items() if isinstance(v, Attribute)],
key = lambda (k, v): v._count)
</code></pre>
<p>Â </p>
<pre><code>class A(object):
def _foo0(self):
pass
def _foo1(self, x):
pass
def foo(self, x=None):
if x is None:
return self._foo0()
else:
return self._foo1(x)
</code></pre>
<p>Besides being much more ugly, it's also less flexible: what if you want ordered literal attributes, like integers and strings? What if <code>None</code> is a valid value for <code>x</code>?</p>
<p>Here's a creative way to solve the first problem:</p>
<pre><code>import sys
class Builder(object):
def __call__(self, cls):
cls._order = self.frame.f_code.co_names
return cls
def ordered():
builder = Builder()
def trace(frame, event, arg):
builder.frame = frame
sys.settrace(None)
sys.settrace(trace)
return builder
@ordered()
class A(object):
x = 1
y = 'foo'
print A._order # ['x', 'y']
</code></pre>
<p>And here's a creative way to solve the second one:</p>
<pre><code>_undefined = object()
class A(object):
def _foo0(self):
pass
def _foo1(self, x):
pass
def foo(self, x=_undefined):
if x is _undefined:
return self._foo0()
else:
return self._foo1(x)
</code></pre>
<p>But this is much, MUCH voodoo-er than a simple metaclass (especially the first one, which really melts your brain). My point is, you look at metaclasses as unfamiliar and counter-intuitive, but you can also look at them as the next step of evolution in programming languages: you just have to adjust your mindset. After all, you could probably do everything in C, including defining a struct with function pointers and passing it as the first argument to its functions. A person seeing C++ for the first time might say, "what is this magic? Why is the compiler implicitly passing <code>this</code> to methods, but not to regular and static functions? It's better to be explicit and verbose about your arguments". But then, object-oriented programming is much more powerful once you get it; and so is this, uh... quasi-aspect-oriented programming, I guess. And once you understand metaclasses, they're actually very simple, so why not use them when convenient?</p>
<p>And finally, metaclasses are rad, and programming should be fun. Using standard programming constructs and design patterns all the time is boring and uninspiring, and hinders your imagination. Live a little! Here's a metametaclass, just for you.</p>
<pre><code>class MetaMetaclass(type):
def __new__(meta, name, bases, attrs):
def __new__(meta, name, bases, attrs):
cls = type.__new__(meta, name, bases, attrs)
cls._label = 'Made in %s' % meta.__name__
return cls
attrs['__new__'] = __new__
return type.__new__(meta, name, bases, attrs)
class China(type):
__metaclass__ = MetaMetaclass
class Taiwan(type):
__metaclass__ = MetaMetaclass
class A(object):
__metaclass__ = China
class B(object):
__metaclass__ = Taiwan
print A._label # Made in China
print B._label # Made in Taiwan
</code></pre>
| 13 | 2015-06-25T22:26:32Z | [
"python",
"metaclass"
] |
What are your (concrete) use-cases for metaclasses in Python? | 392,160 | <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| 51 | 2008-12-24T20:13:06Z | 39,292,817 | <p>I had to use them once for a binary parser to make it easier to use. You define a message class with attributes of the fields present on the wire.
They needed to be ordered in the way they were declared to construct the final wire format from it. You can do that with metaclasses, if you use an ordered namespace dict. In fact, its in the examples for Metaclasses:</p>
<p><a href="https://docs.python.org/3/reference/datamodel.html#metaclass-example" rel="nofollow">https://docs.python.org/3/reference/datamodel.html#metaclass-example</a></p>
<p>But in general: Very carefully evaluate, if you really really need the added complexity of metaclasses.</p>
| 0 | 2016-09-02T12:47:37Z | [
"python",
"metaclass"
] |
Is there a Ruby/Python HTML reflow/layout library? | 392,217 | <p>I'm looking for a library in Ruby or Python that would take some HTML and CSS as the input and return data that contains the positions and sizes of the elements. If it helps, I don't need the info for all the elements but just the major divs of the page.</p>
| 3 | 2008-12-24T21:05:12Z | 392,243 | <p>Scriptor, I think what you likely are looking for might be something in JavaScript more then Ruby or Python. I mean - the positions and sizes are essentially going to be determined by the rendering engine (the browser). You might consider using something like jQuery to loop through all of your desired objects - outputting the name of the object (like the DIV's ID) and the height and width of that item. So, for what it's worth I'd look at jQuery if I was in your position and the height() and width() methods. You never know - there may already be a jQuery plugin.</p>
| 3 | 2008-12-24T21:29:45Z | [
"python",
"html",
"ruby",
"layout"
] |
Is there a Ruby/Python HTML reflow/layout library? | 392,217 | <p>I'm looking for a library in Ruby or Python that would take some HTML and CSS as the input and return data that contains the positions and sizes of the elements. If it helps, I don't need the info for all the elements but just the major divs of the page.</p>
| 3 | 2008-12-24T21:05:12Z | 392,412 | <p>Both Ruby and Python have a Regex library. Why not search for things like /width=\"(\d+)px\"/ and /height:(\d+)px/. Use $1 to find the value in the group. I'm not a regex expert and I'm doing this from memory, so refer to any of the tutorials on the net for the correct syntax and variable usage, but that's where to start. Good luck,
bsperlinus</p>
| -1 | 2008-12-25T01:23:46Z | [
"python",
"html",
"ruby",
"layout"
] |
Modify bound variables of a closure in Python | 392,349 | <p>Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.</p>
<pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
| 22 | 2008-12-24T23:38:30Z | 392,360 | <p>Why not make var_a and var_b arguments of the function foo?</p>
<pre><code>def foo(var_a = 2, var_b = 3):
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo() # uses default arguments 2, 3
print localClosure(1) # 2 + 3 + 1 = 6
localClosure = foo(0, 3)
print localClosure(1) # 0 + 3 + 1 = 4
</code></pre>
| 0 | 2008-12-24T23:53:01Z | [
"python",
"functional-programming",
"closures"
] |
Modify bound variables of a closure in Python | 392,349 | <p>Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.</p>
<pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
| 22 | 2008-12-24T23:38:30Z | 392,366 | <p>I don't think there is any way to do that in Python. When the closure is defined, the current state of variables in the enclosing scope is captured and no longer has a directly referenceable name (from outside the closure). If you were to call <code>foo()</code> again, the new closure would have a different set of variables from the enclosing scope.</p>
<p>In your simple example, you might be better off using a class:</p>
<pre><code>class foo:
def __init__(self):
self.var_a = 2
self.var_b = 3
def __call__(self, x):
return self.var_a + self.var_b + x
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
localClosure.var_a = 0
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
<p>If you do use this technique I would no longer use the name <code>localClosure</code> because it is no longer actually a closure. However, it works the same as one.</p>
| 17 | 2008-12-24T23:58:23Z | [
"python",
"functional-programming",
"closures"
] |
Modify bound variables of a closure in Python | 392,349 | <p>Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.</p>
<pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
| 22 | 2008-12-24T23:38:30Z | 392,372 | <p>I've found an alternate answer answer to Greg's, slightly less verbose because it uses Python 2.1's custom function attributes (which conveniently enough can be accessed from inside their own function).</p>
<pre><code>def foo():
var_b = 3
def _closure(x):
return _closure.var_a + var_b + x
_closure.func_dict['var_a'] = 2
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# apparently, it is
localClosure.var_a = 0
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
<p>Thought I'd post it for completeness. Cheers anyways.</p>
| 8 | 2008-12-25T00:08:52Z | [
"python",
"functional-programming",
"closures"
] |
Modify bound variables of a closure in Python | 392,349 | <p>Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.</p>
<pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
| 22 | 2008-12-24T23:38:30Z | 392,468 | <p>It is quite possible in python 3 thanks to the magic of <a href="http://jeremyhylton.blogspot.com/2007/02/nonlocal-implemented.html">nonlocal</a>.</p>
<pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x, magic = None):
nonlocal var_a
if magic is not None:
var_a = magic
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
print(a)
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
localClosure(0, 0)
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
print(b)
</code></pre>
| 19 | 2008-12-25T03:13:56Z | [
"python",
"functional-programming",
"closures"
] |
Modify bound variables of a closure in Python | 392,349 | <p>Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.</p>
<pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
| 22 | 2008-12-24T23:38:30Z | 3,399,159 | <p>We've done the following. I think it's simpler than other solutions here.</p>
<pre><code>class State:
pass
def foo():
st = State()
st.var_a = 2
st.var_b = 3
def _closure(x):
return st.var_a + st.var_b + x
def _set_a(a):
st.var_a = a
return _closure, _set_a
localClosure, localSetA = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
localSetA(0)
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
print a, b
</code></pre>
| 6 | 2010-08-03T17:44:46Z | [
"python",
"functional-programming",
"closures"
] |
Modify bound variables of a closure in Python | 392,349 | <p>Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.</p>
<pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
| 22 | 2008-12-24T23:38:30Z | 4,576,305 | <p>I worked around a similar limitation by using one-item lists instead of a plain variable. It's ugly but it works because modifying a list item doesn't get treated as a binding operation by the interpreter. </p>
<p>For example:</p>
<pre><code>def my_function()
max_value = [0]
def callback (data)
if (data.val > max_value[0]):
max_value[0] = data.val
# more code here
# . . .
results = some_function (callback)
store_max (max_value[0])
</code></pre>
| 3 | 2011-01-01T23:31:30Z | [
"python",
"functional-programming",
"closures"
] |
Modify bound variables of a closure in Python | 392,349 | <p>Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.</p>
<pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
</code></pre>
| 22 | 2008-12-24T23:38:30Z | 8,792,493 | <pre><code>def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
def bar():
var_a = [2]
var_b = [3]
def _closure(x):
return var_a[0] + var_b[0] + x
def _magic(y):
var_a[0] = y
return _closure, _magic
localClosureFoo = foo()
a = localClosureFoo(1)
print a
localClosureBar, localClosureBarMAGIC = bar()
b = localClosureBar(1)
print b
localClosureBarMAGIC(0)
b = localClosureBar(1)
print b
</code></pre>
| 0 | 2012-01-09T17:25:59Z | [
"python",
"functional-programming",
"closures"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,627 | <p>I hate to say it, and I know I'm risking a down mod here, but it doesn't sound like there's a language out there for you. All programming languages have their quirks and programmers simply have to adapt to them. It's completely possible to write a working server in Python without classes (eliminating the "self" variable class references) and likewise just as easy to write C++ with clean syntax.</p>
<p>If you're looking to deploy cross-platform and want to develop cross-platform as well, your best bet would probably be Java. It shorter development cycles than compiled languages like C and C++, but is higher performance (arguable, but I've always been anti-Java =P) than interpreted languages like Python and Perl and you don't have to work with unofficial implementations like Mono that may from time to time not support all of a language's features.</p>
| 19 | 2008-12-25T08:30:16Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,645 | <p>It may depend a lot on what language your "game logic" (you may know this term as "business logic") is best expressed in. For example, if the game logic is best expressed in Python (or any other particular language) it might be best to just write it in Python and deal with the performance issues the hard way with either multi-threading or clustering. Even though it may cost you a lot of time to get the performance you want out of Python it will be less that the time it will take you to express "player A now casts a level 70 Spell of darkness in the radius of 7 units effecting all units that have spoken with player B and .... " in C++.</p>
<p>Something else to consider is what protocol you will be using to communicate with the clients. If you have a complex binary protocol C++ may be easier (esp. if you already had experience doing it before) while a JSON (or similar) may be easier to parse in Python. Yes, i know C++ and python aren't languages you are limited to (or even considering) but i'm refer to them generally here.</p>
<p>Probably comes down to what language you are the best at. A poorly written program which you hated writing will be worse that one written in a language you know and enjoy, even if the poorly written program was in an arguable more powerful language.</p>
| 1 | 2008-12-25T08:50:13Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,650 | <p>What kind of performance do you need?</p>
<p>twisted is great for servers that need lots of concurrency, as is erlang. Either supports massive concurrency easily and has facilities for distributed computing.</p>
<p>If you want to span more than one core in a python app, do the same thing you'd do if you wanted to span more than one machine — run more than one process.</p>
| 7 | 2008-12-25T08:55:56Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,672 | <p>Speaking of pure performance, if you can run Java 6 you get about 1:1 performance when compared to optimized C++ (special cases notwithstanding, sometimes Java is faster, sometimes C++), the only problem you will have is of course stuff like database libraries, interconnectivity, scalability and such. I believe there's a variety of good to great solutions available to each of these problems but you won't find one language which would solve everything for you so I have to give you the age old advice: Choose the language you like and use that one.</p>
<p>Oh, you're still reading this? :) Well, here's some extra pointers.</p>
<ul>
<li><a href="http://www.eve-online.com/">EVE Online</a> uses Python for its client and server side code and it's both bug-ridden and laggy as something I don't think I should write here so that'd be an example of how Python can be extended to (poorly) serve vast amounts of users.</li>
<li>While Java has some good to great solutions to various related problems, it's really not the best language out there for vast amount of users; it doesn't scale well to extremes without tuning. However there's multi-VM solutions to this which somewhat fix the issue, for example <a href="http://www.terracotta.org/">Terracotta</a> is said to do the job well.</li>
<li>While C++ is rather cumbersome, it allows for such a low-level interaction with the system that you may actually find yourself doing things you thought you couldn't do. I'm thinking of something like dynamic per-core microclustering of runtime code blocks for "filling" every possible clock cycle of the processor as efficiently as possible for maximum performance and things like that.</li>
<li>Mono is far behind the .NET VM/equivalent on Windows platforms so you wouldn't be able to use the latest and fanciest features of C#. However Windows XP (x64) OEM licenses are so laughably cheap at the moment that with small investment you could get a bunch of those and you could then run your code on the platform it was meant to be. And don't fall into the Linux hype, Linux is your saviour only if you really know how to use it and especially XP is pretty damn fast and stable nowadays.</li>
</ul>
| 7 | 2008-12-25T09:23:36Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,739 | <p>You could also look at <a href="http://jruby.codehaus.org/" rel="nofollow">jRuby</a>. It comes with lots of the benefits of Java and lots of the benefits of Ruby in one neat package. You'll have access to huge libraries from both languages.</p>
| 0 | 2008-12-25T11:07:24Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,764 | <p>You could as well use Java and compile the code using GCC to a native executable.</p>
<p>That way you don't get the performance hit of the bytecode engine (Yes, I know - Java out of the box is as fast as C++. It must be just me who always measures a factor 5 performance difference). The drawback is that the GCC Java-frontend does not support all of the Java 1.6 language features. </p>
<p>Another choice would be to use your language of choice, get the code working first and then move the performance critical stuff into native code. Nearly all languages support binding to compiled libraries.</p>
<p>That does not solve your "python does not multithread well"-problem, but it gives you more choices.</p>
| 2 | 2008-12-25T11:44:26Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,814 | <p>Erlang is a language which is designed around concurrency and distribution over several servers, which is perfect for server software. Some links about Erlang and game-servers:</p>
<p><a href="http://www.devmaster.net/articles/mmo-scalable-server/">http://www.devmaster.net/articles/mmo-scalable-server/</a></p>
<p><a href="http://www.erlang-consulting.com/euc2005/mmog/mmog_in_erlang.htm">http://www.erlang-consulting.com/euc2005/mmog/mmog_in_erlang.htm</a></p>
<p>I'm thinking of writing a game-server in Erlang myself.</p>
| 16 | 2008-12-25T13:50:59Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,831 | <p>More details about this game server might help folks better answer your question. Is this a game server in the sense of something like a Counter Strike dedicated server which sits in the background and hosts multiplayer interactions or are you writing something which will be hosted on an HTTP webserver?</p>
<p>Personally, if it were me, I'd be considering Java or C++. My personal preference and skill set would probably lead me towards C++ because I find Java clumsy to work with on both platforms (moreso on Linux) and don't have the confidence that C# is ready for prime-time in Linux yet.</p>
<p>That said, you also need to have a pretty significant community hammering on said server before performance of your language is going to be so problematic. My advise would be to write it in whatever language you can at the moment and if your game grows to be of sufficient size, invest in a rewrite at that time.</p>
| 3 | 2008-12-25T14:13:45Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,844 | <p>The obvious candidates are Java and Erlang:</p>
<p>Pro Java:</p>
<ul>
<li>ease of development</li>
<li>good development environments</li>
<li>stability, good stack traces</li>
<li>well-known (easy to find experienced programmers, lots of libraries, books, ...)</li>
<li>quite fast, mature VM</li>
</ul>
<p>Pro Erlang:</p>
<ul>
<li>proven in systems that need >99.9% uptime</li>
<li>ability to have software updates without downtime</li>
<li>scalable (not only multi-core, but also multi-machine)</li>
</ul>
<p>Contra Erlang:</p>
<ul>
<li>unfamiliar syntax and programming paradigm</li>
<li>not so well known; hard to get experienced programmers for</li>
<li>VM is not nearly as fast as java</li>
</ul>
<p>If your game server mainly works as a event dispatcher (with a bit of a database tucked on), Erlang's message-driven paradigm should be a good match.</p>
<p>In this day and age, I would not consider using an unmanaged language (like C or C++); the marginal performance benefits simply aren't worth the hassle.</p>
| 2 | 2008-12-25T14:34:43Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,874 | <p>What are your objectives? Not the creation of the game itself, but why are you creating it?</p>
<p>If you're doing it to learn a new language, then pick the one that seems the most interesting to you (i.e., the one you most want to learn).</p>
<p>If it is for any other reason, then the best language will be the one that you already know best and enjoy using most. This will allow you to focus on working out the game logic and getting something up and running so that you can see progress and remain motivated to continue, rather than getting bogged down in details of the language you're using and losing interest.</p>
<p>If your favorite language proves inadequate in some ways (too slow, not expressive enough, whatever), then you can rewrite the problem sections in a more suitable language when issues come up - and you won't know the best language to address the specific problems until you know what the problems end up being. Even if your chosen language proves entirely unsuitable for final production use and the whole thing has to be rewritten, it will give you a working prototype with tested game logic, which will make dealing with the new language far easier.</p>
| 0 | 2008-12-25T15:16:55Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,907 | <p>You could take a look at <a href="http://www.stackless.com/" rel="nofollow">Stackless Python</a>. It's an alternative Python interpreter that provides greater support for concurrency. Both EVE Online's server and client software use Stackless Python.</p>
<p>Disclaimer: I haven't used Stackless Python extensively myself, so I can't provide any first-hand accounts of its effectiveness.</p>
| 0 | 2008-12-25T15:54:34Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 392,911 | <p>I might be going slightly off-topic here, but the topic interests me as I have (hobby-wise) worked on quite a few game servers (MMORPG servers) - on others' code as well as mine. There is literature out there that will be of interest to you, drop me a note if you want some references.</p>
<p>One thing that strikes me in your question is the want to serve a thousand users off a multithreaded application. From my humble experience, that does not work too well. :-) </p>
<p>When you serve thousands of users you want a design that is as modular as possible, because one of your primary goals will be to keep the service as a whole up and running. Game servers tend to be rather complex, so there will be quite a few show-stopping bugs. Don't make your life miserable with a single point of failure (one application!).</p>
<p>Instead, try to build multiple processes that can run on a multitude of hosts. My humble suggestion is the following:</p>
<ul>
<li>Make them independent, so a failing process will be irrelevant to the service.</li>
<li>Make them small, so that the different parts of the service and how they interact are easy to grasp.</li>
<li>Don't let users communicate with the gamelogic OR DB directly. Write a proxy - network stacks can and will show odd behaviour on different architectures when you have a multitude of users. Also make sure that you can later "clean"/filter what the proxies forward.</li>
<li>Have a process that will only monitor other processes to see if they are still working properly, with the ability to restart parts.</li>
<li>Make them distributable. Coordinate processes via TCP from the start or you will run into scalability problems.</li>
<li>If you have large landscapes, consider means to dynamically divide load by dividing servers by geography. Don't have every backend process hold all the data in memory.</li>
</ul>
<p>I have ported a few such engines written in C++ and C# for hosts operating on Linux, FreeBSD and also Solaris (on an old UltraSparc IIi - yes, mono still runs there :). From my experience, C# is well fast enough, considering on what ancient hardware it operates on that sparc machine.</p>
<p>The industry (as far as I know) tends to use a lot of C++ for the serving work and embeds scripting languages for the actual game logic. Ah, written too much already - way cool topic.</p>
| 13 | 2008-12-25T15:57:19Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 393,963 | <p>C++ and Java are quite slow compared to C. The language should be a tool but not a crutch.</p>
| -1 | 2008-12-26T16:40:00Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 397,103 | <p>There is a pretty cool framework in development that addresses all your needs:</p>
<p><a href="http://www.projectdarkstar.com" rel="nofollow" title="Project Darkstar">Project Darkstar</a> from Sun. So I'd say Java seems to be a good language for game server development :-)</p>
| 0 | 2008-12-29T03:56:17Z | [
"c#",
"java",
"python",
"networking"
] |
Good language to develop a game server in? | 392,624 | <p>I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).</p>
<p>I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?</p>
<p>Please help me and my picky self arrive on a solution.</p>
<p>UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?</p>
| 11 | 2008-12-25T08:25:54Z | 2,130,979 | <p>I know facebook uses a combination of Erlang and C++ for their chat engine. </p>
<p>Whatever you decide, if you choose a combination of languages, check out facebook's thrift framework for cross language services deployment. They open sourced it about a year+ back:</p>
<p><a href="http://incubator.apache.org/thrift/" rel="nofollow">http://incubator.apache.org/thrift/</a> </p>
| 0 | 2010-01-25T08:17:18Z | [
"c#",
"java",
"python",
"networking"
] |
How to make a color from a number | 392,728 | <p>I have a function that returns a float from 0 to 255. I would like to make a gradient in red color from this, but I need a string in "#FFFFFF" format. Is there a function for that?</p>
| 4 | 2008-12-25T10:56:00Z | 392,732 | <p>You could use:</p>
<pre><code>"#%02X0000" % x
</code></pre>
| 10 | 2008-12-25T10:58:37Z | [
"python",
"colors"
] |
How to make a color from a number | 392,728 | <p>I have a function that returns a float from 0 to 255. I would like to make a gradient in red color from this, but I need a string in "#FFFFFF" format. Is there a function for that?</p>
| 4 | 2008-12-25T10:56:00Z | 392,976 | <pre><code>def rgbtohex(r,g,b):
return "#%02X%02X%02X" % (r,g,b)
</code></pre>
| 3 | 2008-12-25T17:11:00Z | [
"python",
"colors"
] |
How to process two forms in one view? | 392,784 | <p>I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it's better to write separate views?<br /><br />
regards<br />
chriss</p>
| 4 | 2008-12-25T12:40:27Z | 392,801 | <p>Personally, I'd use one view to handle each form's POST.</p>
<p>On the other hand, you could use a hidden input element that indicate which form was used</p>
<pre><code><form action="/blog/" method="POST">
{{ blog_form.as_p }}
<input type="hidden" name="form-type" value"blog-form" /> <!-- set type -->
<input type="submit" value="Submit" />
</form>
...
<form action="/blog/" method="POST">
{{ micro_form.as_p }}
<input type="hidden" name="form-type" value"micro-form" /> <!-- set type -->
<input type="submit" value="Submit" />
</form>
</code></pre>
<p>With a view like:</p>
<pre><code>def blog(request):
if request.method == 'POST':
if request.POST['form-type'] == u"blog-form": # test the form type
form = BlogForm(request.POST)
...
else:
form = MicroForm(request.POST)
...
return render_to_response('blog.html', {
'blog_form': BlogForm(),
'micro_form': MicroForm(),
})
</code></pre>
<p>... but once again, I think one view per form (even if the view only accepts POSTs) is simpler than trying to do the above.</p>
| 5 | 2008-12-25T13:23:25Z | [
"python",
"django",
"django-forms",
"django-templates"
] |
How to process two forms in one view? | 392,784 | <p>I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it's better to write separate views?<br /><br />
regards<br />
chriss</p>
| 4 | 2008-12-25T12:40:27Z | 392,849 | <p>If the two forms are completely different, it will certainly not hurt to have them be handled by two different views. Otherwise, you may use the 'hidden input element' trick <em>zacherates</em> has touched upon. Or, you could always give each <code>submit</code> element a <strong>unique</strong> name, and differentiate in the view which form was submitted based on that.</p>
| 0 | 2008-12-25T14:42:22Z | [
"python",
"django",
"django-forms",
"django-templates"
] |
How to process two forms in one view? | 392,784 | <p>I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it's better to write separate views?<br /><br />
regards<br />
chriss</p>
| 4 | 2008-12-25T12:40:27Z | 393,567 | <p>like ayaz said, you should give unique name to form submit button</p>
<pre><code><form action="." method="post">
......
<input type="submit" name="form1">
</form>
<form action="." method="post">
......
<input type="submit" name="form2">
</form>
#view
if "form1" in request.POST:
...
if "form2" in request.POST:
...
</code></pre>
| 3 | 2008-12-26T07:02:48Z | [
"python",
"django",
"django-forms",
"django-templates"
] |
Length of generator output | 393,053 | <p>Python provides a nice method for getting length of an eager iterable, <code>len(x)</code> that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:</p>
<pre><code>def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
</code></pre>
<p>But I can't get rid of a feeling that I'm reimplementing a bicycle.</p>
<p>(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).</p>
<p>P.S.: concerning the first answers - yes, something like <code>len(list(x))</code> would work too, but that drastically increases the usage of memory.</p>
<p>P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.</p>
| 81 | 2008-12-25T18:50:18Z | 393,059 | <p>There isn't one because you can't do it in the general case - what if you have a lazy infinite generator? For example:</p>
<pre><code>def fib():
a, b = 0, 1
while True:
a, b = b, a + b
yield a
</code></pre>
<p>This never terminates but will generate the Fibonacci numbers. You can get as many Fibanacci numbers as you want by calling <code>next()</code>.</p>
<p>If you really need to know the number of items there are, then you can't iterate through them linearly one time anyways, so just use a different data structure such as a regular list.</p>
| 26 | 2008-12-25T18:53:39Z | [
"python",
"generator",
"iterable"
] |
Length of generator output | 393,053 | <p>Python provides a nice method for getting length of an eager iterable, <code>len(x)</code> that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:</p>
<pre><code>def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
</code></pre>
<p>But I can't get rid of a feeling that I'm reimplementing a bicycle.</p>
<p>(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).</p>
<p>P.S.: concerning the first answers - yes, something like <code>len(list(x))</code> would work too, but that drastically increases the usage of memory.</p>
<p>P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.</p>
| 81 | 2008-12-25T18:50:18Z | 393,134 | <p>You can use enumerate() to loop through the generated data stream, then return the last number -- the number of items.</p>
<p>I tried to use itertools.count() with itertools.izip() but no luck. This is the best/shortest answer I've come up with:</p>
<pre><code>#!/usr/bin/python
import itertools
def func():
for i in 'yummy beer':
yield i
def icount(ifunc):
size = -1 # for the case of an empty iterator
for size, _ in enumerate(ifunc()):
pass
return size + 1
print list(func())
print 'icount', icount(func)
# ['y', 'u', 'm', 'm', 'y', ' ', 'b', 'e', 'e', 'r']
# icount 10
</code></pre>
<p>Kamil Kisiel's solution is way better:</p>
<pre><code>def count_iterable(i):
return sum(1 for e in i)
</code></pre>
| 7 | 2008-12-25T19:55:48Z | [
"python",
"generator",
"iterable"
] |
Length of generator output | 393,053 | <p>Python provides a nice method for getting length of an eager iterable, <code>len(x)</code> that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:</p>
<pre><code>def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
</code></pre>
<p>But I can't get rid of a feeling that I'm reimplementing a bicycle.</p>
<p>(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).</p>
<p>P.S.: concerning the first answers - yes, something like <code>len(list(x))</code> would work too, but that drastically increases the usage of memory.</p>
<p>P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.</p>
| 81 | 2008-12-25T18:50:18Z | 7,223,557 | <p>The easiest way is probably just <code>sum(1 for _ in gen)</code> where gen is your generator. </p>
| 161 | 2011-08-28T20:04:50Z | [
"python",
"generator",
"iterable"
] |
Length of generator output | 393,053 | <p>Python provides a nice method for getting length of an eager iterable, <code>len(x)</code> that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:</p>
<pre><code>def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
</code></pre>
<p>But I can't get rid of a feeling that I'm reimplementing a bicycle.</p>
<p>(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).</p>
<p>P.S.: concerning the first answers - yes, something like <code>len(list(x))</code> would work too, but that drastically increases the usage of memory.</p>
<p>P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.</p>
| 81 | 2008-12-25T18:50:18Z | 11,464,079 | <pre><code>def count(iter):
return sum(1 for _ in iter)
</code></pre>
<p>Or better yet:</p>
<pre><code>def count(iter):
try:
return len(iter)
except TypeError:
return sum(1 for _ in iter)
</code></pre>
<p>If it's not iterable, it will throw a <code>TypeError</code>.</p>
<p>Or, if you want to count something specific in the generator:</p>
<pre><code>def count(iter, key=None):
if key:
if callable(key):
return sum(bool(key(x)) for x in iter)
return sum(x == key for x in iter)
try:
return len(iter)
except TypeError:
return sum(1 for _ in iter)
</code></pre>
| 6 | 2012-07-13T04:22:31Z | [
"python",
"generator",
"iterable"
] |
Length of generator output | 393,053 | <p>Python provides a nice method for getting length of an eager iterable, <code>len(x)</code> that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:</p>
<pre><code>def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
</code></pre>
<p>But I can't get rid of a feeling that I'm reimplementing a bicycle.</p>
<p>(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).</p>
<p>P.S.: concerning the first answers - yes, something like <code>len(list(x))</code> would work too, but that drastically increases the usage of memory.</p>
<p>P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.</p>
| 81 | 2008-12-25T18:50:18Z | 15,690,900 | <p>By definition, only a subset of generators will return after a certain number of arguments (have a pre-defined length), and even then, only a subset of these finite generators have a predictable end (accessing the generator can have side-effects which could stop the generator earlier).</p>
<p>If you wish to implement length methods for your generator, you have to first define what you consider the "length" (is it the total number of elements? the number of remaining elements?), then wrap your generator in a class. Here's an example:</p>
<pre><code>class MyFib(object):
"""
A class iterator that iterates through values of the
Fibonacci sequence, until, optionally, a maximum length is reached.
"""
def __init__(self, length):
self._length = length
self._i = 0
def __iter__(self):
a, b = 0, 1
while not self._length or self._i < self._length:
a, b = b, a + b
self._i += 1
yield a
def __len__(self):
"This method returns the total number of elements"
if self._length:
return self._length
else:
raise NotImplementedError("Infinite sequence has no length")
# or simply return None / 0 depending
# on implementation
</code></pre>
<p>Here is how to use it:</p>
<pre><code>In [151]: mf = MyFib(20)
In [152]: len(mf)
Out[152]: 20
In [153]: l = [n for n in mf]
In [154]: len(l)
Out[154]: 20
In [155]: l
Out[155]:
[1,
1,
2,
...
6765]
In [156]: mf0 = MyFib(0)
In [157]: len(mf0)
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-157-2e89b32ad3e4> in <module>()
----> 1 len(mf0)
/tmp/ipython_edit_TWcV1I.py in __len__(self)
22 return self._length
23 else:
---> 24 raise NotImplementedError
25 # or simply return None / 0 depending
26 # on implementation
NotImplementedError:
In [158]: g = iter(mf0)
In [159]: l0 = [g.next(), g.next(), g.next()]
In [160]: l0
Out[160]: [1, 1, 2]
</code></pre>
| 1 | 2013-03-28T19:51:29Z | [
"python",
"generator",
"iterable"
] |
Length of generator output | 393,053 | <p>Python provides a nice method for getting length of an eager iterable, <code>len(x)</code> that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:</p>
<pre><code>def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
</code></pre>
<p>But I can't get rid of a feeling that I'm reimplementing a bicycle.</p>
<p>(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).</p>
<p>P.S.: concerning the first answers - yes, something like <code>len(list(x))</code> would work too, but that drastically increases the usage of memory.</p>
<p>P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.</p>
| 81 | 2008-12-25T18:50:18Z | 18,630,336 | <p>Use <a href="http://docs.python.org/2/library/functions.html#reduce" rel="nofollow">reduce(function, iterable[, initializer])</a> for a memory efficient purely functional solution:</p>
<pre><code>>>> iter = "This string has 30 characters."
>>> reduce(lambda acc, e: acc + 1, iter, 0)
30
</code></pre>
| 3 | 2013-09-05T07:32:31Z | [
"python",
"generator",
"iterable"
] |
Length of generator output | 393,053 | <p>Python provides a nice method for getting length of an eager iterable, <code>len(x)</code> that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:</p>
<pre><code>def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
</code></pre>
<p>But I can't get rid of a feeling that I'm reimplementing a bicycle.</p>
<p>(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).</p>
<p>P.S.: concerning the first answers - yes, something like <code>len(list(x))</code> would work too, but that drastically increases the usage of memory.</p>
<p>P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.</p>
| 81 | 2008-12-25T18:50:18Z | 35,995,169 | <p>This is a hack, but if you really want to have <code>len</code> work on a general iterable (consuming it in the way), you can create your own version of <code>len</code>.</p>
<p>The <code>len</code> function is essentially equivalent to the following (though implementations usually provide some optimizations to avoid the extra lookup):</p>
<pre><code>def len(iterable):
return iterable.__len__()
</code></pre>
<p>Therefore we can redefine <code>len</code> to try that, and if <code>__len__</code> does not exist, count the number of elements ourselves by consuming the iterable:</p>
<pre><code>def len(iterable):
try:
return iterable.__len__()
except AttributeError:
return sum(1 for _ in iterable)
</code></pre>
<p>The above works in Python 2/3, and (as far as I know) should cover every conceivable kind of iterable .</p>
| 1 | 2016-03-14T18:24:23Z | [
"python",
"generator",
"iterable"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 393,576 | <p>You can use consumer-producer pattern. For example you can create queue that is shared between threads. First thread that fetches data from the web enqueues this data in the shared queue. Another thread that owns database connection dequeues data from the queue and passes it to the database. </p>
| 34 | 2008-12-26T07:10:39Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 393,737 | <p>I like Evgeny's answer - Queues are generally the best way to implement inter-thread communication. For completeness, here are some other options:</p>
<ul>
<li>Close the DB connection when the spawned threads have finished using it. This would fix your <code>OperationalError</code>, but opening and closing connections like this is generally a No-No, due to performance overhead.</li>
<li>Don't use child threads. If the once-per-second task is reasonably lightweight, you could get away with doing the fetch and store, then sleeping until the right moment. This is undesirable as fetch and store operations could take >1sec, and you lose the benefit of multiplexed resources you have with a multi-threaded approach.</li>
</ul>
| 0 | 2008-12-26T12:51:53Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 393,984 | <p>Switch to <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a>. It is much better, scales well, can go beyond the use of multiple cores by using multiple CPUs, and the interface is the same as using python threading module.</p>
<p>Or, as Ali suggested, just use <a href="http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/pooling.html#sqlalchemy.pool.SingletonThreadPool" rel="nofollow">SQLAlchemy's thread pooling mechanism</a>. It will handle everything for you automatically and has many extra features, just to quote some of them:</p>
<ol>
<li>SQLAlchemy includes dialects for SQLite, Postgres, MySQL, Oracle, MS-SQL, Firebird, MaxDB, MS Access, Sybase and Informix; IBM has also released a DB2 driver. So you don't have to rewrite your application if you decide to move away from SQLite.</li>
<li>The Unit Of Work system, a central part of SQLAlchemy's Object Relational Mapper (ORM), organizes pending create/insert/update/delete operations into queues and flushes them all in one batch. To accomplish this it performs a topological "dependency sort" of all modified items in the queue so as to honor foreign key constraints, and groups redundant statements together where they can sometimes be batched even further. This produces the maxiumum efficiency and transaction safety, and minimizes chances of deadlocks.</li>
</ol>
| 10 | 2008-12-26T16:51:24Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 394,109 | <p>Or if you are lazy, like me, you can use <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>. It will handle the threading for you, (<a href="http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/pooling.html#sqlalchemy.pool.SingletonThreadPool">using thread local, and some connection pooling</a>) and the way it does it is even <a href="http://www.sqlalchemy.org/docs/05/reference/dialects/sqlite.html#threading-behavior">configurable</a>.</p>
<p>For added bonus, if/when you realise/decide that using Sqlite for any concurrent application is going to be a disaster, you won't have to change your code to use MySQL, or Postgres, or anything else. You can just switch over.</p>
| 6 | 2008-12-26T18:31:37Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 394,165 | <p>You need to design the concurrency for your program. SQLite has clear limitations and you need to obey them, see the <a href="http://sqlite.org/faq.html#q5" rel="nofollow">FAQ</a> (also the following question).</p>
| 0 | 2008-12-26T19:32:37Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 394,331 | <p>You shouldn't be using threads at all for this. This is a trivial task for <a href="http://twistedmatrix.com/">twisted</a> and that would likely take you significantly further anyway.</p>
<p>Use only one thread, and have the completion of the request trigger an event to do the write.</p>
<p>twisted will take care of the scheduling, callbacks, etc... for you. It'll hand you the entire result as a string, or you can run it through a stream-processor (I have a <a href="https://github.com/dustin/twitty-twister">twitter API</a> and a <a href="https://github.com/dustin/twisted-friends">friendfeed API</a> that both fire off events to callers as results are still being downloaded).</p>
<p>Depending on what you're doing with your data, you could just dump the full result into sqlite as it's complete, cook it and dump it, or cook it while it's being read and dump it at the end.</p>
<p>I have a very simple application that does something close to what you're wanting on github. I call it <a href="https://github.com/dustin/pfetch">pfetch</a> (parallel fetch). It grabs various pages on a schedule, streams the results to a file, and optionally runs a script upon successful completion of each one. It also does some fancy stuff like conditional GETs, but still could be a good base for whatever you're doing.</p>
| 13 | 2008-12-26T21:59:14Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 395,897 | <p><a href="http://dev.scrapy.org/" rel="nofollow">Scrapy</a> seems like a potential answer to my question. Its home page describes my exact task. (Though I'm not sure how stable the code is yet.)</p>
| 0 | 2008-12-28T05:55:27Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 1,813,731 | <p>I would take a look at the y_serial Python module for data persistence: <a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a> </p>
<p>which handles deadlock issues surrounding a single SQLite database. If demand on concurrency gets heavy one can easily set up the class Farm of many databases to diffuse the load over stochastic time.</p>
<p>Hope this helps your project... it should be simple enough to implement in 10 minutes.</p>
| 0 | 2009-11-28T20:39:23Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 2,578,401 | <p>The following found on <a href="http://mail.python.org/pipermail/python-list/2010-March/1239789.html">mail.python.org.pipermail.1239789</a>
<br/><br/>
I have found the solution. I don't know why python documentation has not a single word about this option. So we have to add a new keyword argument to connection function
and we will be able to create cursors out of it in different thread. So use:</p>
<pre><code>sqlite.connect(":memory:", check_same_thread = False)
</code></pre>
<p>works out perfectly for me. Of course from now on I need to take care
of safe multithreading access to the db. Anyway thx all for trying to help.</p>
| 12 | 2010-04-05T12:41:29Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 2,894,830 | <p>Contrary to popular belief, newer versions of sqlite3 <strong>do</strong> support access from multiple threads.</p>
<p>This can be enabled via optional keyword argument <code>check_same_thread</code>:</p>
<pre><code>sqlite.connect(":memory:", check_same_thread=False)
</code></pre>
| 115 | 2010-05-24T05:03:46Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 3,525,147 | <p>Use <a href="http://docs.python.org/library/threading.html#lock-objects" rel="nofollow">threading.Lock()</a></p>
| 0 | 2010-08-19T18:49:37Z | [
"python",
"sqlite"
] |
Python sqlite3 and concurrency | 393,554 | <p>I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:</p>
<pre><code>conn = sqlite3.connect("mydatabase.db")
</code></pre>
<ul>
<li>If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.</li>
<li>If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.</li>
</ul>
<p>Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?</p>
| 54 | 2008-12-26T06:51:54Z | 19,860,325 | <p>The most likely reason you get errors with locked databases is that you must issue</p>
<pre><code>conn.commit()
</code></pre>
<p>after finishing a database operation. If you do not, your database will be write-locked and stay that way. The other threads that are waiting to write will time-out after a time (default is set to 5 seconds, see <a href="http://docs.python.org/2/library/sqlite3.html#sqlite3.connect" rel="nofollow">http://docs.python.org/2/library/sqlite3.html#sqlite3.connect</a> for details on that).</p>
<p>An example of a correct and concurrent insertion would be this:</p>
<pre><code>import threading, sqlite3
class InsertionThread(threading.Thread):
def __init__(self, number):
super(InsertionThread, self).__init__()
self.number = number
def run(self):
conn = sqlite3.connect('yourdb.db', timeout=5)
conn.execute('CREATE TABLE IF NOT EXISTS threadcount (threadnum, count);')
conn.commit()
for i in range(1000):
conn.execute("INSERT INTO threadcount VALUES (?, ?);", (self.number, i))
conn.commit()
# create as many of these as you wish
# but be careful to set the timeout value appropriately: thread switching in
# python takes some time
for i in range(2):
t = InsertionThread(i)
t.start()
</code></pre>
<p>If you like SQLite, or have other tools that work with SQLite databases, or want to replace CSV files with SQLite db files, or must do something rare like inter-platform IPC, then SQLite is a great tool and very fitting for the purpose. Don't let yourself be pressured into using a different solution if it doesn't feel right! </p>
| -1 | 2013-11-08T13:33:32Z | [
"python",
"sqlite"
] |
What values to use for FastCGI maxrequests, maxspare, minspare, maxchildren? | 393,629 | <p>I'm running a Django app using FastCGI and lighttpd.</p>
<p>Can somebody explain me what I should consider when deciding what value to use for maxrequests, maxspare, minspare, maxchildren?</p>
<p>These options are not too well documented, but seem quite important.</p>
<p>Don't just tell me what they do; I want to understand what <em>implications</em> they have and how I should decide on what values to use.</p>
<p>Thanks.</p>
| 5 | 2008-12-26T08:49:51Z | 393,636 | <p>Let's start with the definition</p>
<pre>
maxrequests: How many requests does a child server before being killed
and a new one forked
maxspare : Maximum number of spare processes to keep running
minspare : Minimum number of spare processes to prefork
maxchildren: Hard limit number of processes in prefork mode
</pre>
<p>This means that you'll have at most <em>maxchildren</em> processes running at any given time in your webserver, each running for <em>maxrequests</em> requests. At server start you'll get <em>minspare</em> processes, which will keep growing until <em>maxspare</em> (or <em>maxchildren</em>) if more requests are coming.</p>
<p>So, <em>minspare</em> lets you say how many concurrent requests are you expecting at a minimum (important to avoid the process creation if you start with one, it's good to start at, say 10), and <em>maxspare</em> lets you say how many concurrent requests will your server attend to at most (without compromising it's expected response time and so on. Needs a stress test to validate). And <em>maxrequests</em> is talking about the lifetime of each child, in case they cannot run forever due to any kind of constraint.</p>
| 13 | 2008-12-26T09:00:13Z | [
"python",
"django",
"fastcgi"
] |
What values to use for FastCGI maxrequests, maxspare, minspare, maxchildren? | 393,629 | <p>I'm running a Django app using FastCGI and lighttpd.</p>
<p>Can somebody explain me what I should consider when deciding what value to use for maxrequests, maxspare, minspare, maxchildren?</p>
<p>These options are not too well documented, but seem quite important.</p>
<p>Don't just tell me what they do; I want to understand what <em>implications</em> they have and how I should decide on what values to use.</p>
<p>Thanks.</p>
| 5 | 2008-12-26T08:49:51Z | 393,649 | <p>Don't forget to coordinate your fcgi settings with your apache worker settings. I usually keep more apache workers around than fcgi workers... they are lighter weight and will wait for an available fcgi worker to free up to process the request if the concurrency reaches higher than my maxspare.</p>
| -1 | 2008-12-26T09:34:20Z | [
"python",
"django",
"fastcgi"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 393,656 | <p>In the switch, did you change PostgreSQL client/server versions?</p>
<p>I have seen similar problems with php+mysql, and the culprit was an incompatibility between the client/server versions (even though they had the same major version!)</p>
| 0 | 2008-12-26T09:43:27Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 394,025 | <p>Smells like a possible threading problem. Django is <em>not</em> guaranteed thread-safe although the in-file docs seem to indicate that Django/FCGI can be run that way. Try running with prefork and then beat the crap out of the server. If the problem goes away ...</p>
| 0 | 2008-12-26T17:29:32Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 546,865 | <p>Maybe the PYTHONPATH and PATH environment variable is different for both setups (Apache+mod_python and lighttpd + FastCGI).</p>
| 0 | 2009-02-13T17:29:29Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 601,989 | <p>In the end I switched back to Apache + mod_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now.</p>
<p>The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :)</p>
| 0 | 2009-03-02T11:23:49Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 645,020 | <p>I fixed a similar issue when using a geodjango model that was not using the default ORM for one of its functions. When I added a line to manually close the connection the error went away.</p>
<p><a href="http://code.djangoproject.com/ticket/9437" rel="nofollow">http://code.djangoproject.com/ticket/9437</a></p>
<p>I still see the error randomly (~50% of requests) when doing stuff with user login/sessions however.</p>
| 0 | 2009-03-13T23:56:27Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 803,664 | <p>Have you considered downgrading to Python 2.5.x (2.5.4 specifically)? I don't think Django would be considered mature on Python 2.6 since there are some backwards incompatible changes. However, I doubt this will fix your problem.</p>
<p>Also, Django 1.0.2 fixed some nefarious little bugs so make sure you're running that. This very well could fix your problem.</p>
| -1 | 2009-04-29T18:35:06Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 1,053,436 | <p>I went through the same problem recently (lighttpd, fastcgi & postgre). Searched for a solution for days without success, and as a last resort switched to mysql. The problem is gone.</p>
| 0 | 2009-06-27T19:17:03Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 1,691,350 | <p>Why not storing session in cache?
Set</p>
<pre><code>SESSION_ENGINE = "django.contrib.sessions.backends.cache"
</code></pre>
<p>Also you can try use postgres with <em>pgbouncer</em> (postgres - prefork server and don't like many connects/disconnects per time), but firstly check your postgresql.log.</p>
<p>Another version - you have many records in session tables and <em>django-admin.py cleanup</em> can help.</p>
| 0 | 2009-11-07T00:07:35Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 1,744,068 | <p>The problem could be mainly with Imports. Atleast thats what happened to me.
I wrote my own solution after finding nothing from the web. Please check my blogpost here: <a href="http://nandakishore.posterous.com/simple-djangopython-utility-to-check-all-the" rel="nofollow">Simple Python Utility to check all Imports in your project</a></p>
<p>Ofcourse this will only help you to get to the solution of the original issue pretty quickly and not the actual solution for your problem by itself.</p>
| 0 | 2009-11-16T18:46:07Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 2,390,581 | <p>Change from method=prefork to method=threaded solved the problem for me.</p>
| 0 | 2010-03-05T23:06:49Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 2,503,925 | <p>Possible solution: <a href="http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48" rel="nofollow">http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48</a></p>
<blockquote>
<p>Until recently I was curious to test
this on Django 1.1.1. Will this
exception be thrown again... surprise,
there it was again. It took me some
time to debug this, helpful hint was
that it only shows when (pre)forking.
So for those who getting randomly
those exceptions, I can say... fix
your code :) Ok.. seriously, there
are always few ways of doing this, so
let me firs explain where is a
problem first. If you access database
when any of your modules will import
as, e.g. reading configuration from
database then you will get this error.
When your fastcgi-prefork application
starts, first it imports all modules,
and only after this forks children.
If you have established db connection
during import all children processes
will have an exact copy of that
object. This connection is being
closed at the end of request phase
(request_finished signal). So first
child which will be called to process
your request, will close this
connection. But what will happen to
the rest of the child processes? They
will believe that they have open and
presumably working connection to the
db, so any db operation will cause an
exception. Why this is not showing in
threaded execution model? I suppose
because threads are using same object
and know when any other thread is
closing connection. How to fix this?
Best way is to fix your code... but
this can be difficult sometimes.
Other option, in my opinion quite
clean, is to write somewhere in your
application small piece of code:</p>
</blockquote>
<pre><code>from django.db import connection
from django.core import signals
def close_connection(**kwargs):
connection.close()
signals.request_started.connect(close_connection)
</code></pre>
<p>Not ideal thought, connecting twice to the DB is a workaround at best.</p>
<hr>
<p>Possible solution: using connection pooling (pgpool, pgbouncer), so you have DB connections pooled and stable, and handed fast to your FCGI daemons.</p>
<p>The problem is that this triggers another bug, psycopg2 raising an <em>InterfaceError</em> because it's trying to disconnect twice (pgbouncer already handled this).</p>
<p>Now the culprit is Django signal *request_finished* triggering <em>connection.close()</em>, and failing loud even if it was already disconnected. I don't think this behavior is desired, as if the request already finished, we don't care about the DB connection anymore. A patch for correcting this should be simple.</p>
<p>The relevant traceback:</p>
<pre><code> /usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/core/handlers/wsgi.py in __call__(self=<django.core.handlers.wsgi.WSGIHandler object at 0x24fb210>, environ={'AUTH_TYPE': 'Basic', 'DOCUMENT_ROOT': '/storage/test', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTPS': 'off', 'HTTP_ACCEPT': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_AUTHORIZATION': 'Basic dGVzdGU6c3VjZXNzbw==', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_COOKIE': '__utma=175602209.1371964931.1269354495.126938948...none); sessionid=a1990f0d8d32c78a285489586c510e8c', 'HTTP_HOST': 'www.rede-colibri.com', ...}, start_response=<function start_response at 0x24f87d0>)
246 response = self.apply_response_fixes(request, response)
247 finally:
248 signals.request_finished.send(sender=self.__class__)
249
250 try:
global signals = <module 'django.core.signals' from '/usr/local/l.../Django-1.1.1-py2.6.egg/django/core/signals.pyc'>, signals.request_finished = <django.dispatch.dispatcher.Signal object at 0x1975710>, signals.request_finished.send = <bound method Signal.send of <django.dispatch.dispatcher.Signal object at 0x1975710>>, sender undefined, self = <django.core.handlers.wsgi.WSGIHandler object at 0x24fb210>, self.__class__ = <class 'django.core.handlers.wsgi.WSGIHandler'>
/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/dispatch/dispatcher.py in send(self=<django.dispatch.dispatcher.Signal object at 0x1975710>, sender=<class 'django.core.handlers.wsgi.WSGIHandler'>, **named={})
164
165 for receiver in self._live_receivers(_make_id(sender)):
166 response = receiver(signal=self, sender=sender, **named)
167 responses.append((receiver, response))
168 return responses
response undefined, receiver = <function close_connection at 0x197b050>, signal undefined, self = <django.dispatch.dispatcher.Signal object at 0x1975710>, sender = <class 'django.core.handlers.wsgi.WSGIHandler'>, named = {}
/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/db/__init__.py in close_connection(**kwargs={'sender': <class 'django.core.handlers.wsgi.WSGIHandler'>, 'signal': <django.dispatch.dispatcher.Signal object at 0x1975710>})
63 # when a Django request is finished.
64 def close_connection(**kwargs):
65 connection.close()
66 signals.request_finished.connect(close_connection)
67
global connection = <django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object at 0x17b14c8>, connection.close = <bound method DatabaseWrapper.close of <django.d...ycopg2.base.DatabaseWrapper object at 0x17b14c8>>
/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/db/backends/__init__.py in close(self=<django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object at 0x17b14c8>)
74 def close(self):
75 if self.connection is not None:
76 self.connection.close()
77 self.connection = None
78
self = <django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object at 0x17b14c8>, self.connection = <connection object at 0x1f80870; dsn: 'dbname=co...st=127.0.0.1 port=6432 user=postgres', closed: 2>, self.connection.close = <built-in method close of psycopg2._psycopg.connection object at 0x1f80870>
</code></pre>
<p>Exception handling here could add more leniency:</p>
<p><strong>/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/db/_<em>init</em>_.py</strong></p>
<pre><code> 63 # when a Django request is finished.
64 def close_connection(**kwargs):
65 connection.close()
66 signals.request_finished.connect(close_connection)
</code></pre>
<p>Or it could be handled better on psycopg2, so to not throw fatal errors if all we're trying to do is disconnect and it already is:</p>
<p><strong>/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/db/backends/_<em>init</em>_.py</strong></p>
<pre><code> 74 def close(self):
75 if self.connection is not None:
76 self.connection.close()
77 self.connection = None
</code></pre>
<p>Other than that, I'm short on ideas.</p>
| 3 | 2010-03-23T21:57:07Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Django + FastCGI - randomly raising OperationalError | 393,637 | <p>I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.</p>
<p>Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.</p>
<p>Any ideas where to look for?</p>
<p>PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.</p>
<pre><code> File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
</code></pre>
| 8 | 2008-12-26T09:04:03Z | 33,128,806 | <p>I try to give an answer to this even if I'am not using django but pyramid as the framework. I was running into this problem since a long time. Problem was, that it was really difficult to produce this error for tests... Anyway. Finally I solved it by digging through the whole stuff of sessions, scoped sessions, instances of sessions, engines and connections etc. I found this:</p>
<p><a href="http://docs.sqlalchemy.org/en/rel_0_7/core/pooling.html#disconnect-handling-pessimistic" rel="nofollow">http://docs.sqlalchemy.org/en/rel_0_7/core/pooling.html#disconnect-handling-pessimistic</a></p>
<p>This approach simply adds a listener to the connection pool of the engine. In the listener a static select is queried to the database. If it fails the pool try to establish a new connection to the database before it fails at all. Important: This happens before any other stuff is thrown to the database. So it is possible to pre check connection what prevents the rest of your code from failing.</p>
<p>This is not a clean solution since it don't solve the error itself but it works like a charm. Hope this helps someone.</p>
| 0 | 2015-10-14T14:57:08Z | [
"python",
"django",
"exception",
"fastcgi",
"lighttpd"
] |
Programmatic Form Submit | 393,738 | <p>I want to scrape the contents of a webpage. The contents are produced after a form on that site has been filled in and submitted. </p>
<p>I've read on how to scrape the end result content/webpage - but how to I programmatically submit the form? </p>
<p>I'm using python and have read that I might need to get the original webpage with the form, parse it, get the form parameters and then do X? </p>
<p>Can anyone point me in the rigth direction?</p>
| 2 | 2008-12-26T12:54:27Z | 393,749 | <p>You can do it with javascript. If the form is something like:</p>
<pre><code><form name='myform' ...
</code></pre>
<p>Then you can do this in javascript:</p>
<pre><code><script language="JavaScript">
function submitform()
{
document.myform.submit();
}
</script>
</code></pre>
<p>You can use the "onClick" attribute of links or buttons to invoke this code. To invoke it automatically when a page is loaded, use the "onLoad" attribute of the element:</p>
<pre><code><body onLoad="submitform()" ...>
</code></pre>
| -1 | 2008-12-26T13:10:50Z | [
"python",
"forms",
"screen-scraping",
"submit"
] |
Programmatic Form Submit | 393,738 | <p>I want to scrape the contents of a webpage. The contents are produced after a form on that site has been filled in and submitted. </p>
<p>I've read on how to scrape the end result content/webpage - but how to I programmatically submit the form? </p>
<p>I'm using python and have read that I might need to get the original webpage with the form, parse it, get the form parameters and then do X? </p>
<p>Can anyone point me in the rigth direction?</p>
| 2 | 2008-12-26T12:54:27Z | 393,760 | <p>you'll need to generate a HTTP request containing the data for the form. </p>
<p>The form will look something like:</p>
<pre><code><form action="submit.php" method="POST"> ... </form>
</code></pre>
<p>This tells you the url to request is www.example.com/submit.php and your request should be a POST.</p>
<p>In the form will be several input items, eg:</p>
<pre><code><input type="text" name="itemnumber"> ... </input>
</code></pre>
<p>you need to create a string of all these input name=value pairs encoded for a URL appended to the end of your requested URL, which now becomes
www.example.com/submit.php?itemnumber=5234&otherinput=othervalue etc...
This will work fine for GET. POST is a little trickier.</p>
<pre><code></motivation>
</code></pre>
<p>Just follow S.Lott's links for some much easier to use library support :P</p>
| 2 | 2008-12-26T13:25:55Z | [
"python",
"forms",
"screen-scraping",
"submit"
] |
Programmatic Form Submit | 393,738 | <p>I want to scrape the contents of a webpage. The contents are produced after a form on that site has been filled in and submitted. </p>
<p>I've read on how to scrape the end result content/webpage - but how to I programmatically submit the form? </p>
<p>I'm using python and have read that I might need to get the original webpage with the form, parse it, get the form parameters and then do X? </p>
<p>Can anyone point me in the rigth direction?</p>
| 2 | 2008-12-26T12:54:27Z | 393,763 | <p>Using python, I think it takes the following steps:</p>
<ol>
<li>parse the web page that contains the form, find out the form submit address, and the submit method ("post" or "get").</li>
</ol>
<p><a href="http://www.w3.org/TR/html401/interact/forms.html" rel="nofollow">this explains form elements in html file</a></p>
<ol>
<li>Use urllib2 to submit the form. You may need some functions like "urlencode", "quote" from urllib to generate the url and data for post method. Read the library doc for details.</li>
</ol>
| 2 | 2008-12-26T13:29:29Z | [
"python",
"forms",
"screen-scraping",
"submit"
] |
Programmatic Form Submit | 393,738 | <p>I want to scrape the contents of a webpage. The contents are produced after a form on that site has been filled in and submitted. </p>
<p>I've read on how to scrape the end result content/webpage - but how to I programmatically submit the form? </p>
<p>I'm using python and have read that I might need to get the original webpage with the form, parse it, get the form parameters and then do X? </p>
<p>Can anyone point me in the rigth direction?</p>
| 2 | 2008-12-26T12:54:27Z | 393,777 | <p>From a similar question - <a href="http://stackoverflow.com/questions/2861/options-for-html-scraping">options-for-html-scraping</a> - you can learn that with Python you can use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>.</p>
<blockquote>
<p>Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:</p>
<ol>
<li>Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away.</li>
<li>Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application.</li>
<li>Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding. </li>
</ol>
</blockquote>
<p>The unusual name <a href="http://blog.stackoverflow.com/2008/11/podcast-29/" rel="nofollow">caught the attention of our host</a>, November 12, 2008.</p>
| 2 | 2008-12-26T13:45:29Z | [
"python",
"forms",
"screen-scraping",
"submit"
] |
python and regular expression with unicode | 393,843 | <p>I need to delete some unicode symbols from the string 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù'</p>
<p>I know they exist here for sure. I try:</p>
<pre><code>re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù')
</code></pre>
<p>but it doesn't work. String stays the same. ant suggestion what i do wrong?</p>
| 57 | 2008-12-26T14:40:04Z | 393,856 | <p>Are you using python 2.x or 3.0?</p>
<p>If you're using 2.x, try making the regex string a unicode-escape string, with 'u'. Since it's regex it's good practice to make your regex string a raw string, with 'r'. Also, putting your entire pattern in parentheses is superfluous.</p>
<pre><code>re.sub(ur'[\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+', '', ...)
</code></pre>
<p><a href="http://docs.python.org/tutorial/introduction.html#unicode-strings">http://docs.python.org/tutorial/introduction.html#unicode-strings</a></p>
<p>Edit:</p>
<p>It's also good practice to use the re.UNICODE/re.U/(?u) flag for unicode regexes, but it only affects character class aliases like \w or \b, of which this pattern does not use any and so would not be affected by.</p>
| 75 | 2008-12-26T14:57:57Z | [
"python",
"regex",
"character-properties"
] |
python and regular expression with unicode | 393,843 | <p>I need to delete some unicode symbols from the string 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù'</p>
<p>I know they exist here for sure. I try:</p>
<pre><code>re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù')
</code></pre>
<p>but it doesn't work. String stays the same. ant suggestion what i do wrong?</p>
| 57 | 2008-12-26T14:40:04Z | 393,915 | <p>Use <a href="http://www.amk.ca/python/howto/unicode">unicode</a> strings. Use the <a href="http://docs.python.org/library/re.html#re.UNICODE">re.UNICODE</a> flag.</p>
<pre><code>>>> myre = re.compile(ur'[\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+',
re.UNICODE)
>>> myre
<_sre.SRE_Pattern object at 0xb20b378>
>>> mystr = u'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù'
>>> result = myre.sub('', mystr)
>>> len(mystr), len(result)
(38, 22)
>>> print result
بسÙ
اÙÙÙ Ø§ÙØ±ØÙ
Ù Ø§ÙØ±ØÙÙ
</code></pre>
<p>Read the article by <em>Joel Spolsky</em> called <a href="http://www.joelonsoftware.com/articles/Unicode.html">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a></p>
| 44 | 2008-12-26T15:55:11Z | [
"python",
"regex",
"character-properties"
] |
Scripting inside a Python application | 393,871 | <p><br/>
I'd like to include <strong>Python scripting</strong> in one of my applications, that is written in Python itself. </p>
<p>My application must be able to call external Python functions (written by the user) as <strong>callbacks</strong>. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that.</p>
<p>What is the best way to do this?
<br/>Thanks.</p>
<p><em>edit</em>: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.</p>
| 4 | 2008-12-26T15:12:10Z | 393,893 | <p><a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a> provides a restricted execution environment for Python, e.g. for running untrusted code.</p>
| 4 | 2008-12-26T15:34:26Z | [
"python",
"scripting"
] |
Scripting inside a Python application | 393,871 | <p><br/>
I'd like to include <strong>Python scripting</strong> in one of my applications, that is written in Python itself. </p>
<p>My application must be able to call external Python functions (written by the user) as <strong>callbacks</strong>. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that.</p>
<p>What is the best way to do this?
<br/>Thanks.</p>
<p><em>edit</em>: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.</p>
| 4 | 2008-12-26T15:12:10Z | 393,897 | <p>Use <code>__import__</code> to import the files provided by the user. This function will return a module. Use that to call the functions from the imported file.</p>
<p>Use <code>try..except</code> both on <code>__import__</code> and on the actual call to catch errors.</p>
<p>Example:</p>
<pre><code>m = None
try:
m = __import__("external_module")
except:
# invalid module - show error
if m:
try:
m.user_defined_func()
except:
# some error - display it
</code></pre>
| 8 | 2008-12-26T15:36:49Z | [
"python",
"scripting"
] |
Scripting inside a Python application | 393,871 | <p><br/>
I'd like to include <strong>Python scripting</strong> in one of my applications, that is written in Python itself. </p>
<p>My application must be able to call external Python functions (written by the user) as <strong>callbacks</strong>. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that.</p>
<p>What is the best way to do this?
<br/>Thanks.</p>
<p><em>edit</em>: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.</p>
| 4 | 2008-12-26T15:12:10Z | 393,921 | <p>If you'd like the user to interactively enter commands, I can highly recommend the <a href="http://docs.python.org/library/code.html">code</a> module, part of the standard library. The InteractiveConsole and InteractiveInterpreter objects allow for easy entry and evaluation of user input, and errors are handled very nicely, with tracebacks available to help the user get it right.</p>
<p>Just make sure to catch SystemExit!</p>
<pre><code>$ python
Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> shared_var = "Set in main console"
>>> import code
>>> ic = code.InteractiveConsole({ 'shared_var': shared_var })
>>> try:
... ic.interact("My custom console banner!")
... except SystemExit, e:
... print "Got SystemExit!"
...
My custom console banner!
>>> shared_var
'Set in main console'
>>> shared_var = "Set in sub-console"
>>> sys.exit()
Got SystemExit!
>>> shared_var
'Set in main console'
</code></pre>
| 7 | 2008-12-26T16:01:20Z | [
"python",
"scripting"
] |
Scripting inside a Python application | 393,871 | <p><br/>
I'd like to include <strong>Python scripting</strong> in one of my applications, that is written in Python itself. </p>
<p>My application must be able to call external Python functions (written by the user) as <strong>callbacks</strong>. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that.</p>
<p>What is the best way to do this?
<br/>Thanks.</p>
<p><em>edit</em>: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.</p>
| 4 | 2008-12-26T15:12:10Z | 394,205 | <p>"My application must be able to call external Python functions (written by the user) as callbacks".</p>
<p>There's an alternative that's often simpler.</p>
<p>Define classes which call method functions at specific points. You provide a default implementation.</p>
<p>Your user can then extended the classes and provide appropriate method functions instead of callbacks.</p>
<p>This rarely requires global variables. It's also simpler to implement because your user does something like the following</p>
<pre><code>import core_classes
class MyExtension( core_classes.SomeClass ):
def event_1( self, args ):
# override the default behavior for event_1.
core_classes.main( MyExtension )
</code></pre>
<p>This works very smoothly, and allows maximum flexibility. Errors will always be in their code, since their code is the "main" module.</p>
| 0 | 2008-12-26T20:00:14Z | [
"python",
"scripting"
] |
python introspection not showing functions for Lock | 394,300 | <p>When I try to use introspection to look at what methods are available on threading.Lock I don't see what I would expect.</p>
<p>Specifically I don't see acquire, release or locked. Why is this?</p>
<p>Here's what I do see:</p>
<pre><code>>>> dir (threading.Lock)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__']
</code></pre>
| 1 | 2008-12-26T21:34:05Z | 394,307 | <p>You're doing it wrong. <code>threading.Lock</code> is not an object.</p>
<pre><code>>>> import threading
>>> threading.Lock
<built-in function allocate_lock>
>>> type(threading.Lock)
<type 'builtin_function_or_method'>
>>> x=threading.Lock()
>>> type(x)
<type 'thread.lock'>
>>> dir(x)
['__enter__', '__exit__', 'acquire', 'acquire_lock', 'locked', 'locked_lock', 'release', 'release_lock']
>>>
</code></pre>
| 5 | 2008-12-26T21:42:07Z | [
"python"
] |
Finding when the ActiveApplication changes in OSX through Python | 394,372 | <p>Is there a way to find when the activeApplication changes in OSX through Python and AppKit? I know how to find out launchedApplication and activeApplication ( please refer to my other question here: <a href="http://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python">http://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python</a> )</p>
| 0 | 2008-12-26T22:24:43Z | 394,410 | <p>I've got <a href="http://github.com/dustin/app-hider" rel="nofollow">an OS X app</a> that does this by <a href="http://github.com/dustin/app-hider/tree/master/AppTracker.m#L212" rel="nofollow">polling with an NSTimer</a>. I tried searching for distributed notifications to see if I could find a better way to do it, but I couldn't see anything terribly useful.</p>
<p>I did get notifications when application were <a href="http://github.com/dustin/app-hider/tree/master/AppTracker.m#L49" rel="nofollow">launched</a> or <a href="http://github.com/dustin/app-hider/tree/master/AppTracker.m#L73" rel="nofollow">quit</a>. which is at least a little helpful. You can see the registration of these where my <a href="http://github.com/dustin/app-hider/tree/master/Controller.m#L231" rel="nofollow">controller wakes up</a>.</p>
<p>This application has been immensely helpful to me and even polling once a second uses nearly no CPU. If I could make it more event driven, I would, though. :)</p>
| 1 | 2008-12-26T22:50:24Z | [
"python",
"cocoa-touch",
"osx"
] |
Finding when the ActiveApplication changes in OSX through Python | 394,372 | <p>Is there a way to find when the activeApplication changes in OSX through Python and AppKit? I know how to find out launchedApplication and activeApplication ( please refer to my other question here: <a href="http://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python">http://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python</a> )</p>
| 0 | 2008-12-26T22:24:43Z | 394,416 | <p>I'm not aware of an 'official'/good way to do this, but one hackish way to go about this is to listen for any distributed notifications and see which ones are always fired when the frontmost app changes, so you can listen for that one:</p>
<p>You can set something like this up:</p>
<pre><code>def awakeFromNib(self):
NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_(
self, 'someNotification:', None, None)
def someNotification_(self, notification):
NSLog(notification.name())
</code></pre>
<p>After you've found a notification that always fires when apps are switched, you can replace the first 'None' in the addObserver_etc_ call with the name of that notification and check for the frontmost app in your 'someNotification_' method.</p>
<p>In my case I noticed that the 'AppleSelectedInputSourcesChangedNotification' fired everytime I switched apps, so I would listen to that..</p>
<p>Keep in mind that this can break any moment and you'll prolly be checking for a change in the frontmost app more often than needed.</p>
<p>There must be a better way though.. hopefully :)</p>
| 0 | 2008-12-26T22:52:05Z | [
"python",
"cocoa-touch",
"osx"
] |
Python: Lock directory access under windows | 394,439 | <p>I'd like to be able to lock directory access under windows.
The following code work greatly with file or directory under POSIX system:</p>
<pre><code>def flock(fd, blocking=False, exclusive=False):
if exclusive:
flags = fcntl.LOCK_EX
else:
flags = fcntl.LOCK_SH
if not blocking:
flags |= fcntl.LOCK_NB
fcntl.flock(fd, flags)
</code></pre>
<p>But I only find a way to perform lock access for file, not directory with the following code:</p>
<pre><code>def flock(fd, blocking=False, exclusive=False):
if blocking:
flags = msvcrt.LK_NBLCK
else:
flags = msvcrt.LK_LOCK
msvcrt.locking(fd.fileno(), flags, os.path.getsize(fd.name))
</code></pre>
<p>Have you got any idea how to improve this code and be able to lock directory access ?</p>
<p>Bertrand</p>
| 3 | 2008-12-26T23:16:23Z | 394,464 | <p>You probably can do something like this to indirectly lock a directory with the latter flock function.</p>
<pre><code>for file in os.listdir(dir):
f = open(file)
flock(f)
</code></pre>
<p>This is a limited version, since the user will be able to create new files in the directory.</p>
| 0 | 2008-12-26T23:33:21Z | [
"python",
"windows",
"directory",
"locking"
] |
Python: Lock directory access under windows | 394,439 | <p>I'd like to be able to lock directory access under windows.
The following code work greatly with file or directory under POSIX system:</p>
<pre><code>def flock(fd, blocking=False, exclusive=False):
if exclusive:
flags = fcntl.LOCK_EX
else:
flags = fcntl.LOCK_SH
if not blocking:
flags |= fcntl.LOCK_NB
fcntl.flock(fd, flags)
</code></pre>
<p>But I only find a way to perform lock access for file, not directory with the following code:</p>
<pre><code>def flock(fd, blocking=False, exclusive=False):
if blocking:
flags = msvcrt.LK_NBLCK
else:
flags = msvcrt.LK_LOCK
msvcrt.locking(fd.fileno(), flags, os.path.getsize(fd.name))
</code></pre>
<p>Have you got any idea how to improve this code and be able to lock directory access ?</p>
<p>Bertrand</p>
| 3 | 2008-12-26T23:16:23Z | 394,813 | <p>Yep you are right, at least I can try to lock every file of the directory but it can be painful because I need to walk into all the subdirectories of my directory.
In POSIX system it's easy because directories are seen like files so, no problem with that. But in Windows when I try to open a directory, it doesn't really like that.</p>
<pre><code>open(dirname)
</code></pre>
<p>raises exception: </p>
<pre><code>OSError: [Errno 13] Permission denied: dirname
</code></pre>
<p>I am not really sure my solution is actually the good way to do it.</p>
| 0 | 2008-12-27T08:41:06Z | [
"python",
"windows",
"directory",
"locking"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.