title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Adding a generic image field onto a ModelForm in django
467,985
<p>I have two models, <code>Room</code> and <code>Image</code>. <code>Image</code> is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.</p> <p>Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. </p> <p><strong>Update:</strong></p> <p>I've tried to clarify why I chose this design in comments to the current answers. To summarize: </p> <p>I didn't simply put an <code>ImageField</code> on the <code>Room</code> model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single <code>Image</code> class, which seemed messy, or multiple <code>Image</code> classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.</p> <p>Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.</p> <pre><code># Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context) </code></pre>
2
2009-01-22T03:45:49Z
550,174
<p>Ok I figured it out with some more reading... I feel like you want to do exactly what I have done so here it is.</p> <p>I'll be using GenericForeignKeys for this.</p> <p>First the imports for <code>models.py</code></p> <pre><code>from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic </code></pre> <p>Now add the following to your Image Model</p> <pre><code>class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() </code></pre> <p>This lets this model be just that, a Generic Foreign Key for any number of models. Then add the following to all the models you want to have related images</p> <pre><code>images = generic.GenericRelation(Image) </code></pre> <p>Now in admin.py you need to add the following things.</p> <pre><code>from django.contrib.contenttypes.generic import GenericTabularInline class ImageInline(GenericTabularInline): model = Image extra = 3 ct_field_name = 'content_type' id_field_name = 'object_id' </code></pre> <p>And then include it in a admin declaration</p> <pre><code>class ReviewAdmin(admin.ModelAdmin): inlines = [ImageInline] </code></pre> <p>And thats it. Its working great over here. Hope this helps man! .adam.</p>
0
2009-02-15T02:10:21Z
[ "python", "django", "django-forms" ]
Adding a generic image field onto a ModelForm in django
467,985
<p>I have two models, <code>Room</code> and <code>Image</code>. <code>Image</code> is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.</p> <p>Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong. </p> <p><strong>Update:</strong></p> <p>I've tried to clarify why I chose this design in comments to the current answers. To summarize: </p> <p>I didn't simply put an <code>ImageField</code> on the <code>Room</code> model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single <code>Image</code> class, which seemed messy, or multiple <code>Image</code> classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.</p> <p>Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.</p> <pre><code># Models class Image(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(_('Image'), height_field='', width_field='', upload_to='uploads/images', max_length=200) class Room(models.Model): name = models.CharField(max_length=50) image_set = generic.GenericRelation('Image') # The form class AddRoomForm(forms.ModelForm): image_1 = forms.ImageField() class Meta: model = Room # The view def handle_uploaded_file(f): # DRY violation, I've already specified the upload path in the image model upload_suffix = join('uploads/images', f.name) upload_path = join(settings.MEDIA_ROOT, upload_suffix) destination = open(upload_path, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() return upload_suffix def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'): apartment = Apartment.objects.get(id=apartment_id) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): room = form.save() image_1 = form.cleaned_data['image_1'] # Instead of writing a special function to handle the image, # shouldn't I just be able to pass it straight into Image.objects.create # ...but it doesn't seem to work for some reason, wrong syntax perhaps? upload_path = handle_uploaded_file(image_1) image = Image.objects.create(content_object=room, image=upload_path) return HttpResponseRedirect(room.get_absolute_url()) else: form = form_class() context = {'form': form, } return direct_to_template(request, template, extra_context=context) </code></pre>
2
2009-01-22T03:45:49Z
2,401,025
<p>Use two forms, one for the room and one for the image:</p> <p>class Image(models.Model)</p> <pre><code>content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to='') </code></pre> <p>class UploadImage(forms.ModelForm):</p> <pre><code>class Meta: model = Image fields = ('image') </code></pre> <p>class Room(models.Model):</p> <pre><code>name = models.CharField(max_length=50) images = models.ManyToManyField(Image) </code></pre> <p>class RoomForm(forms.ModelForm):</p> <pre><code>class Meta: model = Room </code></pre> <p>in the views</p> <p>if request.method == "POST":</p> <pre><code> ##2 form, una per l'annuncio ed una per la fotografia form = RoomForm(request.POST) image_form = UploadImage(request.POST, request.FILES) #my_logger.debug('form.is_valid() : ' + str(form.is_valid())) if form.is_valid() and image_form.is_valid(): ##save room room = room.save() ##save image image = image_form.save() ##ManyToMany room.images = [image] room.save() </code></pre>
0
2010-03-08T11:49:47Z
[ "python", "django", "django-forms" ]
Tracking file load progress in Python
468,238
<p>A lot of modules I use import entire files into memory or trickle a file's contents in while they process it. I'm wondering if there's any way to track this sort of loading progress? Possibly a wrapper class that takes a callback?</p>
3
2009-01-22T06:44:52Z
468,349
<p>I would go by this by determining the size of the file, and then simply dividing the total by the number of bytes read. Like this:</p> <pre><code>import os def show_progress(file_name, chunk_size=1024): fh = open(file_name, "r") total_size = os.path.getsize(file_name) total_read = 0 while True: chunk = fh.read(chunk_size) if not chunk: fh.close() break total_read += len(chunk) print "Progress: %s percent" % (total_read/total_size) yield chunk for chunk in show_progress("my_file.txt"): # Process the chunk pass </code></pre> <p><strong>Edit:</strong> I know it isn't the best code, but I just wanted to show the concept.</p>
7
2009-01-22T07:46:14Z
[ "python", "file", "load", "progress" ]
Tracking file load progress in Python
468,238
<p>A lot of modules I use import entire files into memory or trickle a file's contents in while they process it. I'm wondering if there's any way to track this sort of loading progress? Possibly a wrapper class that takes a callback?</p>
3
2009-01-22T06:44:52Z
468,796
<p>If you actually mean "import" (not "read") then you can override the import module definitions. You can add timing capabilities.</p> <p>See the <a href="http://www.python.org/doc/2.5.2/lib/module-imp.html" rel="nofollow">imp</a> module.</p> <p>If you mean "read", then you can trivially wrap Python files with your own file-like wrapper. Files don't expose too many methods. You can override the interesting ones to get timing data.</p> <pre><code>&gt;&gt;&gt; class MyFile(file): ... def read(self,*args,**kw): ... # start timing ... result= super(MyFile,self).read(*args,**kw) ... # finish timing ... return result </code></pre>
2
2009-01-22T11:41:32Z
[ "python", "file", "load", "progress" ]
Python: convert alphabetically spelled out numbers to numerics?
468,241
<p>I'm looking for a library, service, or code suggestions to turn spelled out numbers and amounts (eg. "thirty five dollars and fifteen cents", "one point five") into numerics ($35.15, 1.5) . Suggestions?</p>
0
2009-01-22T06:47:33Z
468,249
<p>I wrote some code to do this for integers a while ago: <a href="http://github.com/ghewgill/text2num">http://github.com/ghewgill/text2num</a></p> <p>Feel free to fork and hack.</p>
6
2009-01-22T06:52:37Z
[ "python", "parsing" ]
Python code for sorting files into folders
468,383
<p>Python 2.5.1</p> <p><a href="http://www.cgsecurity.org/wiki/After_Using_PhotoRec" rel="nofollow">http://www.cgsecurity.org/wiki/After_Using_PhotoRec</a></p> <p>I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks :</p> <p>[EDIT2: Two points:</p> <ol> <li>This question was voted down because it was a 'usage' of code, somehow not a programming question. Does it qualify as a coding question? I argue yes.</li> <li><p>I've gone back and edited the page where the code came from to clarify the need for parameters for the benefit of others.]</p> <p>gyaresu$ python recovery.py Traceback (most recent call last): File "recovery.py", line 8, in source = sys.argv[1] IndexError: list index out of range</p></li> </ol> <p>Script:</p> <pre><code>#!/usr/bin/env python import os import os.path import shutil import string import sys source = sys.argv[1] destination = sys.argv[2] while os.path.exists(source) != True: source = raw_input('Enter a valid source directory\n') while os.path.exists(destination) != True: destination = raw_input('Enter a valid destination directory\n') for root, dirs, files in os.walk(source, topdown=False): for file in files: extension = string.upper(os.path.splitext(file)[1][1:]) destinationPath = os.path.join(destination,extension) if os.path.exists(destinationPath) != True: os.mkdir(destinationPath) if os.path.exists(os.path.join(destinationPath,file)): print 'WARNING: this file was not copied :' + os.path.join(root,file) else: shutil.copy2(os.path.join(root,file), destinationPath) </code></pre>
1
2009-01-22T08:07:43Z
468,395
<p>It simply means that the program is expecting two command line arguments: source and destination. If you wish to use the same code in another function, replace sys.argv[1] and [2] with your own variables.</p>
2
2009-01-22T08:14:34Z
[ "python", "scripting", "recovery" ]
Python code for sorting files into folders
468,383
<p>Python 2.5.1</p> <p><a href="http://www.cgsecurity.org/wiki/After_Using_PhotoRec" rel="nofollow">http://www.cgsecurity.org/wiki/After_Using_PhotoRec</a></p> <p>I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks :</p> <p>[EDIT2: Two points:</p> <ol> <li>This question was voted down because it was a 'usage' of code, somehow not a programming question. Does it qualify as a coding question? I argue yes.</li> <li><p>I've gone back and edited the page where the code came from to clarify the need for parameters for the benefit of others.]</p> <p>gyaresu$ python recovery.py Traceback (most recent call last): File "recovery.py", line 8, in source = sys.argv[1] IndexError: list index out of range</p></li> </ol> <p>Script:</p> <pre><code>#!/usr/bin/env python import os import os.path import shutil import string import sys source = sys.argv[1] destination = sys.argv[2] while os.path.exists(source) != True: source = raw_input('Enter a valid source directory\n') while os.path.exists(destination) != True: destination = raw_input('Enter a valid destination directory\n') for root, dirs, files in os.walk(source, topdown=False): for file in files: extension = string.upper(os.path.splitext(file)[1][1:]) destinationPath = os.path.join(destination,extension) if os.path.exists(destinationPath) != True: os.mkdir(destinationPath) if os.path.exists(os.path.join(destinationPath,file)): print 'WARNING: this file was not copied :' + os.path.join(root,file) else: shutil.copy2(os.path.join(root,file), destinationPath) </code></pre>
1
2009-01-22T08:07:43Z
468,463
<p>Since the script is going to ask for paths if they don't exist, you could make the program arguments optional.</p> <p>Change</p> <pre><code>source = sys.argv[1] destination = sys.argv[2] </code></pre> <p>to</p> <pre><code>source = sys.argv[1] if len(sys.argv &gt; 1) else "" destination = sys.argv[2] if len(sys.argv &gt; 2) else "" </code></pre>
0
2009-01-22T08:55:29Z
[ "python", "scripting", "recovery" ]
Python code for sorting files into folders
468,383
<p>Python 2.5.1</p> <p><a href="http://www.cgsecurity.org/wiki/After_Using_PhotoRec" rel="nofollow">http://www.cgsecurity.org/wiki/After_Using_PhotoRec</a></p> <p>I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks :</p> <p>[EDIT2: Two points:</p> <ol> <li>This question was voted down because it was a 'usage' of code, somehow not a programming question. Does it qualify as a coding question? I argue yes.</li> <li><p>I've gone back and edited the page where the code came from to clarify the need for parameters for the benefit of others.]</p> <p>gyaresu$ python recovery.py Traceback (most recent call last): File "recovery.py", line 8, in source = sys.argv[1] IndexError: list index out of range</p></li> </ol> <p>Script:</p> <pre><code>#!/usr/bin/env python import os import os.path import shutil import string import sys source = sys.argv[1] destination = sys.argv[2] while os.path.exists(source) != True: source = raw_input('Enter a valid source directory\n') while os.path.exists(destination) != True: destination = raw_input('Enter a valid destination directory\n') for root, dirs, files in os.walk(source, topdown=False): for file in files: extension = string.upper(os.path.splitext(file)[1][1:]) destinationPath = os.path.join(destination,extension) if os.path.exists(destinationPath) != True: os.mkdir(destinationPath) if os.path.exists(os.path.join(destinationPath,file)): print 'WARNING: this file was not copied :' + os.path.join(root,file) else: shutil.copy2(os.path.join(root,file), destinationPath) </code></pre>
1
2009-01-22T08:07:43Z
468,472
<p>Or you can modify the original script and add</p> <pre><code>if len(sys.argv) != 3: print "Require 2 arguments: %s &lt;source&gt; &lt;destination&gt;" %(sys.argv[0]) sys.exit(1) </code></pre> <p>after the import statements for proper error handling.</p>
2
2009-01-22T08:57:37Z
[ "python", "scripting", "recovery" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
468,433
<p>As far as I know not exactly but you get somewhere with</p> <pre><code>object.methods.sort </code></pre>
44
2009-01-22T08:39:41Z
[ "python", "ruby", "inspection" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
468,442
<p>You can take a module, such as <code>Enumerable</code>, and send the <code>methods</code> method which lists all the methods the module defines. Classes that include this module will respond to these methods.</p> <pre><code>&gt;&gt; Enumerable.methods =&gt; ["inspect", "private_class_method", "const_missing", "clone", "method", "public_methods", "public_instance_methods", "instance_variable_defined?", "method_defined?", "equal?", "freeze", "included_modules", "const_get", "yaml_as", "methods", "respond_to?", "module_eval", "class_variables", "dup", "protected_instance_methods", "instance_variables", "public_method_defined?", "__id__", "object_id", "taguri", "yaml_tag_read_class", "eql?", "const_set", "id", "to_yaml", "taguri=", "singleton_methods", "send", "class_eval", "taint", "frozen?", "instance_variable_get", "include?", "private_instance_methods", "__send__", "instance_of?", "private_method_defined?", "to_a", "name", "to_yaml_style", "autoload", "type", "yaml_tag_class_name", "&lt;", "protected_methods", "instance_eval", "&lt;=&gt;", "==", "&gt;", "display", "===", "instance_method", "instance_variable_set", "to_yaml_properties", "kind_of?", "extend", "protected_method_defined?", "const_defined?", "&gt;=", "ancestors", "to_s", "&lt;=", "public_class_method", "hash", "class", "instance_methods", "tainted?", "=~", "private_methods", "class_variable_defined?", "nil?", "untaint", "constants", "autoload?", "is_a?"] </code></pre>
4
2009-01-22T08:41:01Z
[ "python", "ruby", "inspection" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
468,635
<p>I'd go for something like this:</p> <pre><code>y String.methods.sort </code></pre> <p>Which will give you a yaml representation of the sorted array of methods. Note that this can be used to list the methods of both classes and objects.</p>
1
2009-01-22T10:25:56Z
[ "python", "ruby", "inspection" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
468,771
<p>Tip for "searching" for a method in irb: </p> <pre><code>"something".methods.select {|item| item =~ /query/ } </code></pre> <p>Tip for trying out methods on a value for comparison:</p> <pre><code>value = "something" [:upcase, :downcase, :capitalize].collect {|method| [method, value.send(method)] } </code></pre> <p>Also, note that you won't get all the same information as Python's dir with object.methods. You have to use a combination of object.methods and class.constants, also class.singleton_methods to get the class methods.</p>
4
2009-01-22T11:33:44Z
[ "python", "ruby", "inspection" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
469,011
<p>Not really. Like the others said, you can get part of what you want by listing class instance methods (e.g. <code>String.instance_methods</code>) but that doesn't help you if a file you open reopens a class (unless you check before and after).</p> <p>If you don't need programmatic access to the list of methods, consider checking out the documentation for a class, module or method using the <code>ri</code> command line tool.</p>
0
2009-01-22T12:57:58Z
[ "python", "ruby", "inspection" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
469,926
<p>I would have made this a comment to jonelf's answer, but apparently I don't have enough rep.</p> <p>some_object.methods.sort - Object.new.methods</p> <p>This isn't exactly what you were asking as others have said, but it gives you the info you are after.</p>
0
2009-01-22T16:53:00Z
[ "python", "ruby", "inspection" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
470,967
<p>If I stricly read your question, I must answer it that way: a file as specified by <code>require</code> in Ruby is just a container and does not have necessarely have any relation with a class. The content can be:</p> <ul> <li>a class</li> <li>a module</li> <li>plain code</li> </ul> <p>or any combination of the above, several times. So you can not directly ask for all methods in a given file.</p> <p>If you meant to list all methods of a given module or class, then the other answers are what you seek (mainly using the <code>#methods</code> method on a module name or class).</p>
0
2009-01-22T21:50:35Z
[ "python", "ruby", "inspection" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
704,557
<p>I like to have this in my .irbrc:</p> <pre><code>class Object def local_methods (methods - Object.instance_methods).sort end end </code></pre> <p>So when I'm in irb:</p> <pre><code>&gt;&gt; Time.now.local_methods =&gt; ["+", "-", "&lt;", "&lt;=", "&lt;=&gt;", "&gt;", "&gt;=", "_dump", "asctime", "between?", "ctime", "day", "dst?", "getgm", "getlocal", "getutc", "gmt?", "gmt_offset", "gmtime", "gmtoff", "hour", "isdst", "localtime", "mday", "min", "mon", "month", "sec", "strftime", "succ", "to_f", "to_i", "tv_sec", "tv_usec", "usec", "utc", "utc?", "utc_offset", "wday", "yday", "year", "zone"] </code></pre> <p>Or even cuter - with grep:</p> <pre><code>&gt;&gt; Time.now.local_methods.grep /str/ =&gt; ["strftime"] </code></pre>
15
2009-04-01T08:20:38Z
[ "python", "ruby", "inspection" ]
Ruby equivalent of Python's "dir"?
468,421
<p>In Python we can "dir" a module, like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; dir(re) </code></pre> <p>And it lists all functions in the module. Is there a similar way to do this in Ruby?</p>
39
2009-01-22T08:32:05Z
24,001,868
<p>Maybe not answering the original question (depends on the use case), but for those who are looking for this to be used in the <code>irb</code> only, you can use "double-TAB" for autocompletion. Which, effectively, can also list (almost all) the methods available for a given object.</p> <p>Put the following line into your <code>~/.irbrc</code> file:</p> <pre><code>require 'irb/completion' </code></pre> <p>Now, (re)start the <code>irb</code>, start typing a method and hit TAB twice - irb autocompletes the input!</p> <p>I actually learned it here: <a href="http://drnicwilliams.com/2006/10/12/my-irbrc-for-consoleirb/" rel="nofollow">http://drnicwilliams.com/2006/10/12/my-irbrc-for-consoleirb/</a></p>
0
2014-06-02T19:32:19Z
[ "python", "ruby", "inspection" ]
Is there a standalone Python type conversion library?
468,639
<p>Are there any standalone type conversion libraries?</p> <p>I have a data storage system that only understands bytes/strings, but I can tag metadata such as the type to be converted to.</p> <p>I could hack up some naive system of type converters, as every other application has done before me, or I could hopefully use a standalone library, except I can't find one. Odd for such a common activity.</p> <p>Just to clarify, I will have something like:</p> <p>('123', 'integer') and I want to get out 123</p>
0
2009-01-22T10:29:33Z
468,683
<p>You've got two options, either use the <a href="http://docs.python.org/library/struct.html#module-struct" rel="nofollow">struct</a> or <a href="http://docs.python.org/library/pickle.html#module-pickle" rel="nofollow">pickle</a> modules.</p> <p>With struct you specify a format and it compacts your data to byte array. This is useful for working with C structures or writing to networked apps that require are binary protocol.</p> <p>pickle can automatically serialise and deserialise complex Python structures to a string. There are some caveats so it's best read the <a href="http://docs.python.org/library/pickle.html#module-pickle" rel="nofollow">documentation</a>. I think this is the most likely the library you want.</p> <pre> >>> import pickle >>> v = pickle.dumps(123) >>> v 'I123\n.' >>> pickle.loads(v) 123 >>> v = pickle.dumps({"abc": 123}) >>> v "(dp0\nS'abc'\np1\nI123\ns." >>> pickle.loads(v) {'abc': 123} </pre>
3
2009-01-22T10:59:44Z
[ "python", "type-conversion" ]
Is there a standalone Python type conversion library?
468,639
<p>Are there any standalone type conversion libraries?</p> <p>I have a data storage system that only understands bytes/strings, but I can tag metadata such as the type to be converted to.</p> <p>I could hack up some naive system of type converters, as every other application has done before me, or I could hopefully use a standalone library, except I can't find one. Odd for such a common activity.</p> <p>Just to clarify, I will have something like:</p> <p>('123', 'integer') and I want to get out 123</p>
0
2009-01-22T10:29:33Z
468,866
<p>Consider this.</p> <pre><code>import datetime def toDate( someString ): return datetime.datetime.strptime( someString, "%x" ).date() typeConversionMapping = { 'integer': int, 'string': str, 'float': float, 'date': toDate } def typeConversionFunction( typeConversionTuple ): theStringRepresentation, theTypeName = typeConversionTuple return typeConversionMapping[theTypeName](theStringRepresentation) </code></pre> <p>Is that a good enough standalone library for such a common activity? Would that be enough of a well-tested, error-resilient library? Or is there something more that's required? </p> <p>If you need more or different date/time conversions, you simply add new <code>toDate</code> functions with different formats.</p>
3
2009-01-22T12:02:48Z
[ "python", "type-conversion" ]
Is there a standalone Python type conversion library?
468,639
<p>Are there any standalone type conversion libraries?</p> <p>I have a data storage system that only understands bytes/strings, but I can tag metadata such as the type to be converted to.</p> <p>I could hack up some naive system of type converters, as every other application has done before me, or I could hopefully use a standalone library, except I can't find one. Odd for such a common activity.</p> <p>Just to clarify, I will have something like:</p> <p>('123', 'integer') and I want to get out 123</p>
0
2009-01-22T10:29:33Z
1,584,810
<p>Flatland does this well. <a href="http://discorporate.us/projects/flatland/" rel="nofollow">http://discorporate.us/projects/flatland/</a></p>
1
2009-10-18T12:51:46Z
[ "python", "type-conversion" ]
Templates within templates. How to avoid rendering twice?
468,736
<p>I've got a CMS that takes some dynamic content and renders it using a standard template. However I am now using template tags in the dynamic content itself so I have to do a render_to_string and then pass the results of that as a context variable to render_to_response. This seems wasteful.</p> <p>What's a better way to do this?</p>
1
2009-01-22T11:22:00Z
468,751
<p>"This seems wasteful" Why does it seem that way?</p> <p>Every template is a mix of tags and text. In your case some block of text has already been visited by a template engine. So what? Once it's been transformed it's just text and passes through the next template engine very, very quickly.</p> <p>Do you have specific performance problems? Are you not meeting your transaction throughput requirements? Is there a specific problem?</p> <p>Is the code too complex? Is it hard to maintain? Does it break all the time?</p> <p>I think your solution is adequate. I'm not sure template tags in dynamic content is good from a debugging point of view, but from a basic "template rendering" point of view, it is fine.</p>
2
2009-01-22T11:28:28Z
[ "python", "django", "django-templates" ]
Templates within templates. How to avoid rendering twice?
468,736
<p>I've got a CMS that takes some dynamic content and renders it using a standard template. However I am now using template tags in the dynamic content itself so I have to do a render_to_string and then pass the results of that as a context variable to render_to_response. This seems wasteful.</p> <p>What's a better way to do this?</p>
1
2009-01-22T11:22:00Z
468,953
<p>What you're doing sounds fine, but the question could be asked: Why not put the templatetag references directly in your template instead of manually rendering them?</p> <pre><code>&lt;div&gt; {% if object matches some criteria %} {% render_type1_object object %} {% else %} {% render_type2_object object %} {% endif % ... etc ... &lt;/div&gt; </code></pre> <p>Or, better yet, have one central templatetag for rendering an object (or list of objects), which encapsulates the mapping of object types to templatetags. Then all of your templates simply reference the one templatetag, with no type-knowledge necessary in the templates themselves.</p> <p>The key being that you're moving knowledge of how to render individual objects out of your views.</p>
0
2009-01-22T12:39:47Z
[ "python", "django", "django-templates" ]
In Django how do i return the total number of items that are related to a model?
469,110
<p>In Django how can i return the total number of items (count) that are related to another model, e.g the way stackoverflow does a list of questions then on the side it shows the count on the answers related to that question.</p> <p>This is easy if i get the questionid, i can return all answers related to that question but when am displaying the entire list of question it becomes a bit tricky to display on the side the count showing the total count.</p> <p>I don't know if am clear but just think how stackoverflow displays its questions with answer,views count next to each question! </p>
1
2009-01-22T13:26:22Z
469,423
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#count">QuerySet.count()</a></p> <p>See also an <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward">example</a> how to build QuerySets of related models.</p>
5
2009-01-22T14:56:38Z
[ "python", "django" ]
In Django how do i return the total number of items that are related to a model?
469,110
<p>In Django how can i return the total number of items (count) that are related to another model, e.g the way stackoverflow does a list of questions then on the side it shows the count on the answers related to that question.</p> <p>This is easy if i get the questionid, i can return all answers related to that question but when am displaying the entire list of question it becomes a bit tricky to display on the side the count showing the total count.</p> <p>I don't know if am clear but just think how stackoverflow displays its questions with answer,views count next to each question! </p>
1
2009-01-22T13:26:22Z
470,293
<p>If you're willing to use trunk, you can take advantage of the brand new annotate() QuerySet method added just a week or so ago, which solves this exact problem:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/aggregation/</a></p> <p>If you want to stick with Django 1.0, you can achieve this in a slightly less elegant way using the select argument of the extra() QuerySet method. There's an example of exactly what you are talking about using extra() here:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none</a></p> <p>Finally, if you need this to be really high performance you can denormalise the count in to a separate column. I've got some examples of how to do this in the unit testing part of my presentation here:</p> <p><a href="http://www.slideshare.net/simon/advanced-django" rel="nofollow">http://www.slideshare.net/simon/advanced-django</a></p>
1
2009-01-22T18:24:37Z
[ "python", "django" ]
Any Python OLAP/MDX ORM engines?
469,200
<p>I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like Django ORM for Python that would support OLAP.</p> <p>I'm a Python/Django developer and if there would be something that would have some level of integration with Django I would be much interested in learning more about it.</p>
7
2009-01-22T13:56:23Z
471,669
<p>Django has some OLAP features that are nearing release.</p> <p>Read <a href="http://www.eflorenzano.com/blog/post/secrets-django-orm/" rel="nofollow">http://www.eflorenzano.com/blog/post/secrets-django-orm/</a></p> <p><a href="http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html" rel="nofollow">http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html</a>, also</p> <p>If you have a proper star schema design in the first place, then one-dimensional results can have the following form.</p> <pre><code>from myapp.models import SomeFact from collections import defaultdict facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that ) myAggregates = defaultdict( int ) for row in facts: myAggregates[row.dimension3__attribute] += row.someMeasure </code></pre> <p>If you want to create a two-dimensional summary, you have to do something like the following.</p> <pre><code>facts = SomeFact.objects.filter( dimension1__attribute=this, dimension2__attribute=that ) myAggregates = defaultdict( int ) for row in facts: key = ( row.dimension3__attribute, row.dimension4__attribute ) myAggregates[key] += row.someMeasure </code></pre> <p>To compute multiple SUM's and COUNT's and what-not, you have to do something like this.</p> <pre><code>class MyAgg( object ): def __init__( self ): self.count = 0 self.thisSum= 0 self.thatSum= 0 myAggregates= defaultdict( MyAgg ) for row in facts: myAggregates[row.dimension3__attr].count += 1 myAggregates[row.dimension3__attr].thisSum += row.this myAggregates[row.dimension3__attr].thatSum += row.that </code></pre> <p>This -- at first blush -- seems inefficient. You're trolling through the fact table returning lots of rows which you are then aggregating in your application.</p> <p>In some cases, this may be <em>faster</em> than the RDBMS's native sum/group_by. Why? You're using a simple mapping, not the more complex sort-based grouping operation that the RDBMS often has to use for this. Yes, you're getting a lot of rows; but you're doing less to get them.</p> <p>This has the disadvantage that it's not so declarative as we'd like. It has the advantage that it's pure Django ORM.</p>
6
2009-01-23T02:24:53Z
[ "python", "django", "orm", "olap", "mdx" ]
Any Python OLAP/MDX ORM engines?
469,200
<p>I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like Django ORM for Python that would support OLAP.</p> <p>I'm a Python/Django developer and if there would be something that would have some level of integration with Django I would be much interested in learning more about it.</p>
7
2009-01-22T13:56:23Z
2,683,321
<p>I had a similar need - not for a full blown ORM but for a simple OLAP-like data store in Python. After coming up dry searching for existing tools I wrote this little hack:</p> <p><a href="https://github.com/kpwebb/python-cube/blob/master/src/cube.py" rel="nofollow">https://github.com/kpwebb/python-cube/blob/master/src/cube.py</a></p> <p>Even if it doesn't solve your exact need, it might be a good starting place for writing something more sophisticated. </p>
0
2010-04-21T13:33:32Z
[ "python", "django", "orm", "olap", "mdx" ]
Any Python OLAP/MDX ORM engines?
469,200
<p>I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like Django ORM for Python that would support OLAP.</p> <p>I'm a Python/Django developer and if there would be something that would have some level of integration with Django I would be much interested in learning more about it.</p>
7
2009-01-22T13:56:23Z
2,989,623
<p>Same thing as <em>kpw</em>, I write my own stuff, except that it is exclusively for Django :</p> <p><a href="https://code.google.com/p/django-cube/" rel="nofollow">https://code.google.com/p/django-cube/</a></p>
1
2010-06-07T12:53:01Z
[ "python", "django", "orm", "olap", "mdx" ]
Any Python OLAP/MDX ORM engines?
469,200
<p>I'm new to the MDX/OLAP and I'm wondering if there is any ORM similar like Django ORM for Python that would support OLAP.</p> <p>I'm a Python/Django developer and if there would be something that would have some level of integration with Django I would be much interested in learning more about it.</p>
7
2009-01-22T13:56:23Z
19,683,765
<p>There is also <a href="http://cubes.databrewery.org/" rel="nofollow">http://cubes.databrewery.org/</a> . Lightweight OLAP engine in python.</p>
1
2013-10-30T13:35:23Z
[ "python", "django", "orm", "olap", "mdx" ]
adding scrollbars to pythoncard application
469,219
<p>scrollingwindow as main frame for the application is not supported yet for pythoncard. how can i add scrollbars to main frame(background)?</p>
2
2009-01-22T14:02:18Z
540,375
<p>Ive never used pythoncard but in pure wxpython you can just put a ScrolledWindow inside the frame, then use a sizer to controll the scrollbars (asumming the contents of the sizer dont fit in the window). Eg this short code snipit will give you a window with a vertical scrollbar.</p> <pre><code>class Scrolled(wx.ScrolledWindow): def __init__(self, parent): wx.ScrolledWindow.__init__(self, parent, size=(200,200)) self.SetScrollRate(0, 10); sizerV = wx.BoxSizer(wx.VERTICAL) #create a bunch of stuff in the sizer which doesnt fit for i in range(0,50): text = "Line: " + str(i) sizerV.Add(wx.StaticText(self, label=text), 0) self.SetSizer(sizerV) class Frame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, size=(200,200), Scrolled(self) title="Scroll Bars", style=wx.CAPTION) </code></pre>
2
2009-02-12T07:43:20Z
[ "python", "wxpython", "scroll", "pythoncard" ]
How can I listen for 'usb device inserted' events in Linux, in Python?
469,243
<p>I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good example.</p>
28
2009-01-22T14:09:59Z
469,433
<p>I haven't tried writing such a program myself, however I've just looked at the following two links (thanks Google!), which I think will be of help:</p> <ul> <li><a href="http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html" rel="nofollow">dbus-python tutorial</a> (which talks about how to use Python to access D-Bus)</li> <li><a href="http://www.marcuscom.com/hal-spec/hal-spec.html#interfaces" rel="nofollow">HAL 0.5.10 Specification</a> (which talks about how HAL publishes events to D-Bus)</li> </ul> <p>In particular, read about the <code>org.freedesktop.Hal.Manager</code> interface, and its <code>DeviceAdded</code> and <code>DeviceRemoved</code> events. :-)</p> <p>Hope this helps!</p>
7
2009-01-22T14:59:36Z
[ "python", "linux", "usb" ]
How can I listen for 'usb device inserted' events in Linux, in Python?
469,243
<p>I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good example.</p>
28
2009-01-22T14:09:59Z
469,522
<p>I think D-Bus would work as Chris mentioned, but if you're using KDE4, you might use the Solid framework in a manner similar to the KDE4 "New Device Notifier" applet.</p> <p>The C++ source for that applet is <a href="http://kollide.net:8060/browse/Plasma/applets/devicenotifier/devicenotifier.cpp?r=21574" rel="nofollow">here</a>, which shows how to use Solid to detect new devices. Use PyKDE4 for Python bindings to these libraries, as shown <a href="http://techbase.kde.org/Development/Languages/Python/Using_PyKDE_4" rel="nofollow">here</a>.</p>
4
2009-01-22T15:15:46Z
[ "python", "linux", "usb" ]
How can I listen for 'usb device inserted' events in Linux, in Python?
469,243
<p>I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good example.</p>
28
2009-01-22T14:09:59Z
471,099
<p><strong>Update</strong>: As said in comments, Hal is not supported in recent distributions, the standard now is udev, Here is a small example that makes use of glib loop and <strong>udev</strong>, I keep the Hal version for historical reasons.</p> <p>This is basically the <a href="http://pyudev.readthedocs.org/en/latest/api/pyudev.glib.html#pyudev.glib.MonitorObserver">example in the pyudev documentation</a>, adapted to work with older versions, and with the glib loop, notice that the filter should be customized for your specific needing:</p> <pre><code>import glib from pyudev import Context, Monitor try: from pyudev.glib import MonitorObserver def device_event(observer, device): print 'event {0} on device {1}'.format(device.action, device) except: from pyudev.glib import GUDevMonitorObserver as MonitorObserver def device_event(observer, action, device): print 'event {0} on device {1}'.format(action, device) context = Context() monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') observer = MonitorObserver(monitor) observer.connect('device-event', device_event) monitor.start() glib.MainLoop().run() </code></pre> <p><em><strong>Old version with Hal and d-bus:</em></strong></p> <p>You can use D-Bus bindings and listen to <code>DeviceAdded</code> and <code>DeviceRemoved</code> signals. You will have to check the capabilities of the Added device in order to select the storage devices only.</p> <p>Here is a small example, you can remove the comments and try it.</p> <pre><code>import dbus import gobject class DeviceAddedListener: def __init__(self): </code></pre> <p>You need to connect to Hal Manager using the System Bus.</p> <pre><code> self.bus = dbus.SystemBus() self.hal_manager_obj = self.bus.get_object( "org.freedesktop.Hal", "/org/freedesktop/Hal/Manager") self.hal_manager = dbus.Interface(self.hal_manager_obj, "org.freedesktop.Hal.Manager") </code></pre> <p>And you need to connect a listener to the signals you are interested on, in this case <code>DeviceAdded</code>.</p> <pre><code> self.hal_manager.connect_to_signal("DeviceAdded", self._filter) </code></pre> <p>I'm using a filter based on capabilities. It will accept any <code>volume</code> and will call <code>do_something</code> with if, you can read Hal documentation to find the more suitable queries for your needs, or more information about the properties of the Hal devices.</p> <pre><code> def _filter(self, udi): device_obj = self.bus.get_object ("org.freedesktop.Hal", udi) device = dbus.Interface(device_obj, "org.freedesktop.Hal.Device") if device.QueryCapability("volume"): return self.do_something(device) </code></pre> <p>Example function that shows some information about the volume:</p> <pre><code> def do_something(self, volume): device_file = volume.GetProperty("block.device") label = volume.GetProperty("volume.label") fstype = volume.GetProperty("volume.fstype") mounted = volume.GetProperty("volume.is_mounted") mount_point = volume.GetProperty("volume.mount_point") try: size = volume.GetProperty("volume.size") except: size = 0 print "New storage device detectec:" print " device_file: %s" % device_file print " label: %s" % label print " fstype: %s" % fstype if mounted: print " mount_point: %s" % mount_point else: print " not mounted" print " size: %s (%.2fGB)" % (size, float(size) / 1024**3) if __name__ == '__main__': from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) loop = gobject.MainLoop() DeviceAddedListener() loop.run() </code></pre>
45
2009-01-22T22:27:58Z
[ "python", "linux", "usb" ]
How can I listen for 'usb device inserted' events in Linux, in Python?
469,243
<p>I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good example.</p>
28
2009-01-22T14:09:59Z
39,288,660
<p>Here is a solution in 5 lines.</p> <pre><code>import pyudev context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') for device in iter(monitor.poll, None): if device.action == 'add': print('{} connected'.format(device)) # do something very interesting here. </code></pre> <p>Save this to a file say <code>usb_monitor.py</code>, run <code>python monitor.py</code>. Plug any usb and it will print device details</p> <pre><code>→ python usb_monitor.py Device('/sys/devices/pci0000:00/0000:00:14.0/usb1/1-6/1-6:1.0') connected Device('/sys/devices/pci0000:00/0000:00:14.0/usb1/1-1/1-1:1.0') connected </code></pre> <p>Tested on Python 3.5 with <code>pyudev==0.21.0</code>. </p>
0
2016-09-02T09:13:16Z
[ "python", "linux", "usb" ]
deleting rows of a numpy array based on uniqueness of a value
469,931
<p>let's say I have a bi-dimensional array like that</p> <pre><code>numpy.array( [[0,1,1.2,3], [1,5,3.2,4], [3,4,2.8,4], [2,6,2.3,5]]) </code></pre> <p>I want to have an array formed eliminating whole rows based on uniqueness of values of last column, selecting the row to keep based on value of third column. e.g. in this case i would like to keep only one of the rows with 4 as last column, and choose the one which has the minor value of third column, having something like that as a result:</p> <pre><code>array([0,1,1.2,3], [3,4,2.8,4], [2,6,2.3,5]) </code></pre> <p>thus eliminating row [1,5,3.2,4]</p> <p>which would be the best way to do it?</p>
4
2009-01-22T16:54:05Z
470,521
<p>My numpy is way out of practice, but this should work:</p> <pre><code>#keepers is a dictionary of type int: (int, int) #the key is the row's final value, and the tuple is (row index, row[2]) keepers = {} deletions = [] for i, row in enumerate(n): key = row[3] if key not in keepers: keepers[key] = (i, row[2]) else: if row[2] &gt; keepers[key][1]: deletions.append(i) else: deletions.append(keepers[key][0]) keepers[key] = (i, row[2]) o = numpy.delete(n, deletions, axis=0) </code></pre> <p>I've greatly simplified it from my declarative solution, which was getting quite unwieldy. Hopefully this is easier to follow; all we do is maintain a dictionary of values that we want to keep and a list of indexes we want to delete.</p>
1
2009-01-22T19:41:26Z
[ "python", "arrays", "numpy", "unique" ]
deleting rows of a numpy array based on uniqueness of a value
469,931
<p>let's say I have a bi-dimensional array like that</p> <pre><code>numpy.array( [[0,1,1.2,3], [1,5,3.2,4], [3,4,2.8,4], [2,6,2.3,5]]) </code></pre> <p>I want to have an array formed eliminating whole rows based on uniqueness of values of last column, selecting the row to keep based on value of third column. e.g. in this case i would like to keep only one of the rows with 4 as last column, and choose the one which has the minor value of third column, having something like that as a result:</p> <pre><code>array([0,1,1.2,3], [3,4,2.8,4], [2,6,2.3,5]) </code></pre> <p>thus eliminating row [1,5,3.2,4]</p> <p>which would be the best way to do it?</p>
4
2009-01-22T16:54:05Z
27,403,267
<p>This can be achieved efficiently in Numpy by combining <code>lexsort</code> and <code>unique</code> as follows</p> <pre><code>import numpy as np a = np.array([[0, 1, 1.2, 3], [1, 5, 3.2, 4], [3, 4, 2.8, 4], [2, 6, 2.3, 5]]) # Sort by last column and 3rd column when values are equal j = np.lexsort(a.T) # Find first occurrence (=smallest 3rd column) of unique values in last column k = np.unique(a[j, -1], return_index=True)[1] print(a[j[k]]) </code></pre> <p>This returns the desired result</p> <pre><code>[[ 0. 1. 1.2 3. ] [ 3. 4. 2.8 4. ] [ 2. 6. 2.3 5. ]] </code></pre>
1
2014-12-10T14:16:41Z
[ "python", "arrays", "numpy", "unique" ]
problem using an instance in a with_statement
469,950
<p>I've recently started to learn python , and I reached the <strong>with</strong> statement . I've tried to use it with a class instance , but I think I'm doing something wrong . Here is the code :</p> <pre><code> from __future__ import with_statement import pdb class Geo: def __init__(self,text): self.text = text def __enter__(self): print "entering" def __exit__(self,exception_type,exception_value,exception_traceback): print "exiting" def ok(self): print self.text def __get(self): return self.text with Geo("line") as g : g.ok() </code></pre> <p>The thing is that when the interpreter reaches the <strong>ok</strong> method inside the with statement , the following exception is raised :</p> <pre><code> Traceback (most recent call last): File "dec.py", line 23, in g.ok() AttributeError: 'NoneType' object has no attribute 'ok' </code></pre> <p>Why does the g object have the type NoneType ? How can I use an instance with the <strong>with</strong> statement ?</p>
4
2009-01-22T16:58:42Z
469,992
<p>Your <code>__enter__</code> method needs to return the object that should be used for the "<code>as g</code>" part of the with statement. See the <a href="http://docs.python.org/reference/compound_stmts.html#with">documentation</a>, where it states:</p> <ul> <li>If a target was included in the with statement, the return value from <code>__enter__()</code> is assigned to it.</li> </ul> <p>Currently, it has no return statement, so g gets bound to <code>None</code> (the default return value)</p>
12
2009-01-22T17:08:38Z
[ "python", "with-statement" ]
AppEngine and Django: including a template file
470,008
<p>As the title suggests, I'm using Google App Engine and Django.</p> <p>I have quite a bit of identical code across my templates and would like to reduce this by including template files. So, in my main application directory I have the python handler file, the main template, and the template I want to include in my main template.</p> <p>I would have thought that including {% include "fileToInclude.html" %} would work on its own but that simply doesn't include anything. I assume I have to set something up, maybe using TEMPLATE_DIRS, but can't figure it out on my own.</p> <p>EDIT:</p> <p>I've tried:</p> <pre><code>TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'), ) </code></pre> <p>But to no avail. I'll try some other possibilities too.</p>
4
2009-01-22T17:12:54Z
470,233
<p>First, you should consider using <a href="http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance" rel="nofollow">template inheritance</a> rather than the <code>include</code> tag, which is often appropriate but sometimes far inferior to template inheritance.</p> <p>Unfortunately, I have no experience with App Engine, but from my experience with regular Django, I can tell you that you need to set your <code>TEMPLATE_DIRS</code> list to include the folder from which you want to include a template, as you indicated.</p>
3
2009-01-22T18:07:57Z
[ "python", "django", "google-app-engine", "templates", "include" ]
AppEngine and Django: including a template file
470,008
<p>As the title suggests, I'm using Google App Engine and Django.</p> <p>I have quite a bit of identical code across my templates and would like to reduce this by including template files. So, in my main application directory I have the python handler file, the main template, and the template I want to include in my main template.</p> <p>I would have thought that including {% include "fileToInclude.html" %} would work on its own but that simply doesn't include anything. I assume I have to set something up, maybe using TEMPLATE_DIRS, but can't figure it out on my own.</p> <p>EDIT:</p> <p>I've tried:</p> <pre><code>TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'), ) </code></pre> <p>But to no avail. I'll try some other possibilities too.</p>
4
2009-01-22T17:12:54Z
504,733
<p>I found that it works "out of the box" if I don't load Templates first and render them with a Context object. Instead, I use the standard method shown in the <a href="http://code.google.com/appengine/docs/python/gettingstarted/templates.html" rel="nofollow">AppEngine tutorial</a>.</p>
1
2009-02-02T20:25:05Z
[ "python", "django", "google-app-engine", "templates", "include" ]
AppEngine and Django: including a template file
470,008
<p>As the title suggests, I'm using Google App Engine and Django.</p> <p>I have quite a bit of identical code across my templates and would like to reduce this by including template files. So, in my main application directory I have the python handler file, the main template, and the template I want to include in my main template.</p> <p>I would have thought that including {% include "fileToInclude.html" %} would work on its own but that simply doesn't include anything. I assume I have to set something up, maybe using TEMPLATE_DIRS, but can't figure it out on my own.</p> <p>EDIT:</p> <p>I've tried:</p> <pre><code>TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'), ) </code></pre> <p>But to no avail. I'll try some other possibilities too.</p>
4
2009-01-22T17:12:54Z
2,906,723
<p>I've done the following to get around using includes:</p> <pre><code>def render(file, map={}): return template.render( os.path.join(os.path.dirname(__file__), '../templates', file), map) table = render("table.html", {"headers": headers, "rows": rows}) final = render("final.html", {"table": table}) self.response.out.write(final) </code></pre>
0
2010-05-25T16:58:12Z
[ "python", "django", "google-app-engine", "templates", "include" ]
AppEngine and Django: including a template file
470,008
<p>As the title suggests, I'm using Google App Engine and Django.</p> <p>I have quite a bit of identical code across my templates and would like to reduce this by including template files. So, in my main application directory I have the python handler file, the main template, and the template I want to include in my main template.</p> <p>I would have thought that including {% include "fileToInclude.html" %} would work on its own but that simply doesn't include anything. I assume I have to set something up, maybe using TEMPLATE_DIRS, but can't figure it out on my own.</p> <p>EDIT:</p> <p>I've tried:</p> <pre><code>TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'), ) </code></pre> <p>But to no avail. I'll try some other possibilities too.</p>
4
2009-01-22T17:12:54Z
5,761,711
<p>I am having the same problem and tracked it down into the ext.webapp package. In template.py, you'll find this comment on line 33:</p> <p>Django uses a global setting for the directory in which it looks for templates. This is not natural in the context of the webapp module, so our load method takes in a complete template path, and we set these settings on the fly automatically. Because we have to set and use a global setting on every method call, this module is not thread safe, though that is not an issue for applications.</p> <p>See line 92 in the same file. You can see the template dirs being squashed:</p> <pre><code>directory, file_name = os.path.split(abspath) new_settings = { 'TEMPLATE_DIRS': (directory,), 'TEMPLATE_DEBUG': debug, 'DEBUG': debug, } </code></pre> <p>UPDATE: Here is the workaround which worked for me - <a href="http://groups.google.com/group/google-appengine/browse_thread/thread/c3e0e4c47e4f3680/262b517a723454b6?lnk=gst&amp;q=template_dirs#262b517a723454b6" rel="nofollow">http://groups.google.com/group/google-appengine/browse_thread/thread/c3e0e4c47e4f3680/262b517a723454b6?lnk=gst&amp;q=template_dirs#262b517a723454b6</a></p>
1
2011-04-23T02:22:30Z
[ "python", "django", "google-app-engine", "templates", "include" ]
Why does 1+++2 = 3 in python?
470,139
<p>I am from C background and I just started learning python... </p> <p>while trying some programs, I got this doubt...</p> <p>how python evaluates the expression 1+++2?</p> <p>No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior</p> <p>and for 1--2 it is printing 3 and for 1---2 it is printing -1 </p> <p>please clear my doubt.</p> <p>Regards</p> <p>Sunil</p>
16
2009-01-22T17:41:44Z
470,156
<p>Your expression is the same as:</p> <pre><code>1+(+(+2)) </code></pre> <p>Any numeric expression can be preceded by <code>-</code> to make it negative, or <code>+</code> to do nothing (the option is present for symmetry). With negative signs:</p> <pre><code>1-(-(2)) = 1-(-2) = 1+2 = 3 </code></pre> <p>and</p> <pre><code>1-(-(-2)) = 1-(2) = -1 </code></pre> <p>I see you clarified your question to say that you come from a C background. In Python, there are no increment operators like <code>++</code> and <code>--</code> in C, which was probably the source of your confusion. To increment or decrement a variable <code>i</code> or <code>j</code> in Python use this style:</p> <pre><code>i += 1 j -= 1 </code></pre>
47
2009-01-22T17:46:08Z
[ "python", "evaluation" ]
Why does 1+++2 = 3 in python?
470,139
<p>I am from C background and I just started learning python... </p> <p>while trying some programs, I got this doubt...</p> <p>how python evaluates the expression 1+++2?</p> <p>No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior</p> <p>and for 1--2 it is printing 3 and for 1---2 it is printing -1 </p> <p>please clear my doubt.</p> <p>Regards</p> <p>Sunil</p>
16
2009-01-22T17:41:44Z
470,160
<p>1+(+(+2)) = 3</p> <p>1 - (-2) = 3</p> <p>1 - (-(-2)) = -1</p>
3
2009-01-22T17:46:22Z
[ "python", "evaluation" ]
Why does 1+++2 = 3 in python?
470,139
<p>I am from C background and I just started learning python... </p> <p>while trying some programs, I got this doubt...</p> <p>how python evaluates the expression 1+++2?</p> <p>No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior</p> <p>and for 1--2 it is printing 3 and for 1---2 it is printing -1 </p> <p>please clear my doubt.</p> <p>Regards</p> <p>Sunil</p>
16
2009-01-22T17:41:44Z
470,162
<p>The extra +'s are not incrementors (like ++a or a++ in c++). They are just showing that the number is positive.</p> <p>There is no such ++ operator. There is a unary + operator and a unary - operator though. The unary + operator has no effect on its argument. The unary - operator negates its operator or mulitplies it by -1. </p> <pre><code>+1 </code></pre> <p>-> 1</p> <pre><code>++1 </code></pre> <p>-> 1</p> <p>This is the same as +(+(1))</p> <pre><code> 1+++2 </code></pre> <p>-> 3 Because it's the same as 1 + (+(+(2))</p> <p>Likewise you can do --1 to mean - (-1) which is +1.</p> <pre><code> --1 </code></pre> <p>-> 1</p> <p>For completeness there is no * unary opeartor. So *1 is an error. But there is a ** operator which is power of, it takes 2 arguments. </p> <pre><code> 2**3 </code></pre> <p>-> 8</p>
11
2009-01-22T17:47:04Z
[ "python", "evaluation" ]
Why does 1+++2 = 3 in python?
470,139
<p>I am from C background and I just started learning python... </p> <p>while trying some programs, I got this doubt...</p> <p>how python evaluates the expression 1+++2?</p> <p>No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior</p> <p>and for 1--2 it is printing 3 and for 1---2 it is printing -1 </p> <p>please clear my doubt.</p> <p>Regards</p> <p>Sunil</p>
16
2009-01-22T17:41:44Z
470,163
<p>Think it as 1 + (+1*(+1*2))). The first + is operator and following plus signs are sign of second operand (= 2).</p> <p>Just like 1---2 is same as 1 - -(-(2)) or 1- (-1*(-1*(2))</p>
0
2009-01-22T17:47:08Z
[ "python", "evaluation" ]
Why does 1+++2 = 3 in python?
470,139
<p>I am from C background and I just started learning python... </p> <p>while trying some programs, I got this doubt...</p> <p>how python evaluates the expression 1+++2?</p> <p>No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior</p> <p>and for 1--2 it is printing 3 and for 1---2 it is printing -1 </p> <p>please clear my doubt.</p> <p>Regards</p> <p>Sunil</p>
16
2009-01-22T17:41:44Z
470,165
<p>I believe it's being parsed as, the first + as a binary operation (add), and the rest as unary operations (make positive). </p> <pre><code> 1 + (+(+2)) </code></pre>
1
2009-01-22T17:47:36Z
[ "python", "evaluation" ]
Why does 1+++2 = 3 in python?
470,139
<p>I am from C background and I just started learning python... </p> <p>while trying some programs, I got this doubt...</p> <p>how python evaluates the expression 1+++2?</p> <p>No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior</p> <p>and for 1--2 it is printing 3 and for 1---2 it is printing -1 </p> <p>please clear my doubt.</p> <p>Regards</p> <p>Sunil</p>
16
2009-01-22T17:41:44Z
470,168
<p>Trying <a href="http://docs.python.org/reference/expressions.html#unary-arithmetic-operations" rel="nofollow">Unary Plus and Unary minus</a>:</p> <blockquote> <p>The unary - (minus) operator yields the negation of its numeric argument.</p> <p>The unary + (plus) operator yields its numeric argument unchanged.</p> </blockquote> <pre><code>&gt;&gt;&gt; +2 2 &gt;&gt;&gt; ++2 2 &gt;&gt;&gt; +++2 2 &gt;&gt;&gt; -2 -2 &gt;&gt;&gt; --2 2 &gt;&gt;&gt; ---2 -2 &gt;&gt;&gt; 1+(++2) 3 </code></pre>
2
2009-01-22T17:47:47Z
[ "python", "evaluation" ]
Why does 1+++2 = 3 in python?
470,139
<p>I am from C background and I just started learning python... </p> <p>while trying some programs, I got this doubt...</p> <p>how python evaluates the expression 1+++2?</p> <p>No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior</p> <p>and for 1--2 it is printing 3 and for 1---2 it is printing -1 </p> <p>please clear my doubt.</p> <p>Regards</p> <p>Sunil</p>
16
2009-01-22T17:41:44Z
470,178
<p>It's simple. There are no post-incrementation or post-decrementation operators in Python.</p> <p>See here: <a href="http://mail.python.org/pipermail/python-list/2006-January/361771.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2006-January/361771.html</a></p>
0
2009-01-22T17:51:11Z
[ "python", "evaluation" ]
ISO encoded attachment names and python
470,567
<p>First of all i don't have the code example on this computer, but i have an example that is quite similar.</p> <p>(<a href="http://docs.python.org/library/email-examples.html" rel="nofollow">http://docs.python.org/library/email-examples.html</a>)</p> <p>The 4th one.</p> <p>My issue lies within this bit of code</p> <pre><code>counter = 1 for part in msg.walk(): # multipart/* are just containers if part.get_content_maintype() == 'multipart': continue # Applications should really sanitize the given filename so that an # email message can't be used to overwrite important files filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: # Use a generic bag-of-bits extension ext = '.bin' filename = 'part-%03d%s' % (counter, ext) counter += 1 fp = open(os.path.join(opts.directory, filename), 'wb') fp.write(part.get_payload(decode=True)) fp.close() </code></pre> <p>When i fetch emails that do not have iso or utf encoded filenames, this code works fine. But when the attachment name is iso encoded, the filename is not within the get_filename, but the filename is in encoded form within part["Content-type"] (i belive)</p> <p>The above example tries to guess the extension and if it cant find the filename, it just gives it a part filename. What i would like is the filename.</p> <p>Has anyone dealt with issues like these, and what did you do to fix it?</p>
1
2009-01-22T19:54:50Z
479,238
<p>I found the issue, it was with </p> <pre><code>mimetypes.guess_extension(part.get_content_type()) </code></pre> <p>And images with "image/pjpeg" as the content type</p> <p>@S.Lott i have changed the code to resemble the above example, but i added this to fix the pjpeg issue.</p> <pre><code>if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: guess = part["Content-Type"].split(";") if guess[0] == "image/pjpeg": guess[0] = "image/jpeg" ext = mimetypes.guess_extension(guess[0]) if not ext: ext = ".bin" </code></pre>
0
2009-01-26T09:38:26Z
[ "python", "email", "attachment" ]
Jython and python modules
471,000
<p>I've just started using the <code>PythonInterpreter</code> from within my Java classes, and it works great! However, if I try to include python modules (<code>re</code>, <code>HTMLParser</code>, etc.), I'm receiving the following exception (for <code>re</code>):</p> <pre> Exception in thread "main" Traceback (innermost last): File "", line 1, in ? ImportError: no module named re </pre> <p>How could I make the classes from the jython jar "see" the modules python has available?</p>
18
2009-01-22T21:57:46Z
471,143
<p>According to the <a href="http://www.jython.org/Project/userfaq.html#jython-modules" rel="nofollow">FAQ</a>:</p> <blockquote> <h2>4.1 What parts of the Python library are supported?</h2> <p>The good news is that Jython now supports a large majority of the standard Python library. The bad news is that this has moved so rapidly, it's hard to keep the documentation up to date.</p> <p>Built-in modules (e.g. those that are written in C for CPython) are a different story. These would have to be ported to Java, or implemented with a JNI bridge in order to be used by Jython. Some built-in modules have been ported to JPython, most notably cStringIO, cPickle, struct, and binascii. It is unlikely that JNI modules will be included in Jython proper though.</p> <p>If you want to use a standard Python module, just try importing it. If that works, you're probably all set. You can also do a dir() on the modules to check the list of functions it implements.</p> <p>If there is some standard Python module that you have a real need for that doesn't work with Jython yet, please send us mail.</p> </blockquote> <p>In other words, you <em>can</em> directly use Python modules from Jython, unless you're trying to use built-in modules, in which case you're stuck with whatever has been ported to Jython.</p>
7
2009-01-22T22:39:59Z
[ "java", "python", "interop", "jython" ]
Jython and python modules
471,000
<p>I've just started using the <code>PythonInterpreter</code> from within my Java classes, and it works great! However, if I try to include python modules (<code>re</code>, <code>HTMLParser</code>, etc.), I'm receiving the following exception (for <code>re</code>):</p> <pre> Exception in thread "main" Traceback (innermost last): File "", line 1, in ? ImportError: no module named re </pre> <p>How could I make the classes from the jython jar "see" the modules python has available?</p>
18
2009-01-22T21:57:46Z
471,153
<p>Check your jython sys.path . Make sure that the library you want to load are in this path. Look at <a href="http://www.jython.org/cgi-bin/faqw.py?req=show&amp;file=faq02.003.htp" rel="nofollow">jython faq</a> for more details.</p>
1
2009-01-22T22:44:13Z
[ "java", "python", "interop", "jython" ]
Jython and python modules
471,000
<p>I've just started using the <code>PythonInterpreter</code> from within my Java classes, and it works great! However, if I try to include python modules (<code>re</code>, <code>HTMLParser</code>, etc.), I'm receiving the following exception (for <code>re</code>):</p> <pre> Exception in thread "main" Traceback (innermost last): File "", line 1, in ? ImportError: no module named re </pre> <p>How could I make the classes from the jython jar "see" the modules python has available?</p>
18
2009-01-22T21:57:46Z
483,165
<p>You embed jython and you will use some Python-Modules somewere:</p> <p>if you want to set the path (sys.path) in your Java-Code :</p> <pre><code>public void init() { interp = new PythonInterpreter(null, new PySystemState()); PySystemState sys = Py.getSystemState(); sys.path.append(new PyString(rootPath)); sys.path.append(new PyString(modulesDir)); } </code></pre> <p>Py is in org.python.core.</p> <p>rootPath and modulesDir is where YOU want !</p> <p>let rootPath point where you located the standard-jython-lib</p> <p>Have a look at src/org/python/util/PyServlet.java in the Jython-Source-Code for example</p>
14
2009-01-27T12:09:48Z
[ "java", "python", "interop", "jython" ]
Jython and python modules
471,000
<p>I've just started using the <code>PythonInterpreter</code> from within my Java classes, and it works great! However, if I try to include python modules (<code>re</code>, <code>HTMLParser</code>, etc.), I'm receiving the following exception (for <code>re</code>):</p> <pre> Exception in thread "main" Traceback (innermost last): File "", line 1, in ? ImportError: no module named re </pre> <p>How could I make the classes from the jython jar "see" the modules python has available?</p>
18
2009-01-22T21:57:46Z
33,936,241
<p>You can refer here for the solution <a href="http://stackoverflow.com/questions/3256135/importing-python-modules-in-jython/33936158#33936158">Importing python modules in jython</a></p> <p>Download <code>ez_setup.py</code> from here <a href="http://peak.telecommunity.com/dist/ez_setup.py" rel="nofollow">http://peak.telecommunity.com/dist/ez_setup.py</a></p> <p>Then run <code>jython ez_setup.py &lt;any module name&gt;</code>.</p> <p>Running it on any folder path doesn't matter.</p> <p>I could install pymysql with it, no problem.</p>
0
2015-11-26T10:30:07Z
[ "java", "python", "interop", "jython" ]
How do I remove VSS hooks from a VS Web Site?
471,190
<p>I have a Visual Studio 2008 solution with 7 various projects included with it. 3 of these 'projects' are Web Sites (the kind of project without a project file).</p> <p>I have stripped all the various Visual Sourcesafe files from all the directories, removed the Scc references in the SLN file and all the project files that exist. I deleted the SUO file and all the USER files also. Visual Studio still thinks that 2 of the Web Sites are still under source control, and it adds the Scc entries back into the SLN file for me.</p> <p><strong>Does anybody know <em>how</em> VS still knows about the old source control?</strong></p> <p><em>Edit:</em> Another thing that I didn't mention is that the files I'm trying to remove VSS hooks from has been copied outside of VSS's known working directories, the python script run and manual edits to files made before the solution is opened in VS 2008 or VS 2005 (I had the problem with both).</p> <p>Here is a python script that I used to weed out these files and let me know which files needed manually edited.</p> <pre><code>import os, stat from os.path import join def main(): startDir = r"C:\Documents and Settings\user\Desktop\project" manualEdits = [] for root, dirs, files in os.walk(startDir, topdown=False): if '.svn' in dirs: dirs.remove('.svn') for name in files: os.chmod(join(root,name), stat.S_IWRITE) if name.endswith(".vssscc") or name.endswith(".scc") or name.endswith(".vspscc") or name.endswith(".suo") or name.endswith(".user"): print "Deleting:", join(root, name) os.remove(join(root,name)) if name.endswith("sln") or name.endswith("dbp") or name.endswith("vbproj") or name.endswith("csproj"): manualEdits.append(join(root, name)) print "Manual Edits are needed for these files:" for name in manualEdits: print name if __name__ == "__main__": main() </code></pre>
0
2009-01-22T22:56:34Z
471,391
<p>It probably is only trying to add it on your instance of VS. You have to remove the cache so VS thinks its no longer under SS</p> <ol> <li>under file -> SourceControl -> Workspaces</li> <li>Select the SS location</li> <li>Edit</li> <li>Choose the working folder</li> <li>Remove!</li> </ol>
1
2009-01-23T00:11:25Z
[ "python", "visual-studio", "visual-sourcesafe" ]
How do I remove VSS hooks from a VS Web Site?
471,190
<p>I have a Visual Studio 2008 solution with 7 various projects included with it. 3 of these 'projects' are Web Sites (the kind of project without a project file).</p> <p>I have stripped all the various Visual Sourcesafe files from all the directories, removed the Scc references in the SLN file and all the project files that exist. I deleted the SUO file and all the USER files also. Visual Studio still thinks that 2 of the Web Sites are still under source control, and it adds the Scc entries back into the SLN file for me.</p> <p><strong>Does anybody know <em>how</em> VS still knows about the old source control?</strong></p> <p><em>Edit:</em> Another thing that I didn't mention is that the files I'm trying to remove VSS hooks from has been copied outside of VSS's known working directories, the python script run and manual edits to files made before the solution is opened in VS 2008 or VS 2005 (I had the problem with both).</p> <p>Here is a python script that I used to weed out these files and let me know which files needed manually edited.</p> <pre><code>import os, stat from os.path import join def main(): startDir = r"C:\Documents and Settings\user\Desktop\project" manualEdits = [] for root, dirs, files in os.walk(startDir, topdown=False): if '.svn' in dirs: dirs.remove('.svn') for name in files: os.chmod(join(root,name), stat.S_IWRITE) if name.endswith(".vssscc") or name.endswith(".scc") or name.endswith(".vspscc") or name.endswith(".suo") or name.endswith(".user"): print "Deleting:", join(root, name) os.remove(join(root,name)) if name.endswith("sln") or name.endswith("dbp") or name.endswith("vbproj") or name.endswith("csproj"): manualEdits.append(join(root, name)) print "Manual Edits are needed for these files:" for name in manualEdits: print name if __name__ == "__main__": main() </code></pre>
0
2009-01-22T22:56:34Z
471,655
<p>Those things are pernicious! Visual Studio sticks links to SourceSafe in everywhere, including into the XML that makes up your sln file.</p> <p>I wrote an <a href="http://billmill.org/ss2svn.html" rel="nofollow">article</a> about my experiences converting sourcesafe to subversion, and included with it the python script that I used to clean out the junk. Please note:</p> <p>1) This is VERY LIGHTLY TESTED. Make backups so you don't screw up your sln/*proj files. Run your test suite before and after to make sure it didn't screw up something (how could it? Who knows! but stranger things have happened.)</p> <p>2) This may have been with a different version of sourcesafe and visual studio in mind, so you may need to tweak it. Anyway, without further ado:</p> <pre><code>import os, re PROJ_RE = re.compile(r"^\s+Scc") SLN_RE = re.compile(r"GlobalSection\(SourceCodeControl\).*?EndGlobalSection", re.DOTALL) VDPROJ_RE = re.compile(r"^\"Scc") for (dir, dirnames, filenames) in os.walk('.'): for fname in filenames: fullname = os.path.join(dir, fname) if fname.endswith('scc'): os.unlink(fullname) elif fname.endswith('vdproj'): #Installer project has a different format fin = file(fullname) text = fin.readlines() fin.close() fout = file(fullname, 'w') for line in text: if not VDPROJ_RE.match(line): fout.write(line) fout.close() elif fname.endswith('csproj'): fin = file(fullname) text = fin.readlines() fin.close() fout = file(fullname, 'w') for line in text: if not PROJ_RE.match(line): fout.write(line) fout.close() elif fname.endswith('sln'): fin = file(fullname) text = fin.read() fin.close() text = SLN_RE.sub("", text) fout = file(fullname, 'w') fout.write(text) </code></pre>
1
2009-01-23T02:19:56Z
[ "python", "visual-studio", "visual-sourcesafe" ]
How do I remove VSS hooks from a VS Web Site?
471,190
<p>I have a Visual Studio 2008 solution with 7 various projects included with it. 3 of these 'projects' are Web Sites (the kind of project without a project file).</p> <p>I have stripped all the various Visual Sourcesafe files from all the directories, removed the Scc references in the SLN file and all the project files that exist. I deleted the SUO file and all the USER files also. Visual Studio still thinks that 2 of the Web Sites are still under source control, and it adds the Scc entries back into the SLN file for me.</p> <p><strong>Does anybody know <em>how</em> VS still knows about the old source control?</strong></p> <p><em>Edit:</em> Another thing that I didn't mention is that the files I'm trying to remove VSS hooks from has been copied outside of VSS's known working directories, the python script run and manual edits to files made before the solution is opened in VS 2008 or VS 2005 (I had the problem with both).</p> <p>Here is a python script that I used to weed out these files and let me know which files needed manually edited.</p> <pre><code>import os, stat from os.path import join def main(): startDir = r"C:\Documents and Settings\user\Desktop\project" manualEdits = [] for root, dirs, files in os.walk(startDir, topdown=False): if '.svn' in dirs: dirs.remove('.svn') for name in files: os.chmod(join(root,name), stat.S_IWRITE) if name.endswith(".vssscc") or name.endswith(".scc") or name.endswith(".vspscc") or name.endswith(".suo") or name.endswith(".user"): print "Deleting:", join(root, name) os.remove(join(root,name)) if name.endswith("sln") or name.endswith("dbp") or name.endswith("vbproj") or name.endswith("csproj"): manualEdits.append(join(root, name)) print "Manual Edits are needed for these files:" for name in manualEdits: print name if __name__ == "__main__": main() </code></pre>
0
2009-01-22T22:56:34Z
520,070
<p>In your %APPDATA% directory Visual Studio saves a list of websites used in Visual Studio, with some settings of that site:</p> <p>On my Vista Machine the exact location of the file is</p> <pre><code>C:\Users\{name}\AppData\Local\Microsoft\WebsiteCache\Websites.xml </code></pre> <p>This file contains entries like</p> <pre><code>&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;DesignTimeData&gt; &lt;Website RootUrl="e:\Documents\Visual Studio 2008\WebSites\WebSite\" CacheFolder="WebSite" sccprovider="SubversionScc" scclocalpath="Svn" sccauxpath="Svn" addnewitemlang="Visual Basic" sccprojectname="Svn" targetframework="3.5" vwdport="60225" _LastAccess="11-11-2008 10:58:03"/&gt; &lt;Website RootUrl="E:\siteje.webproj\" CacheFolder="siteje.webproj" _LastAccess="11-6-2008 14:43:45"/&gt; &lt;!-- And many more --&gt; &lt;/DesignTimeData /&gt; </code></pre> <p>As you can see it contains the Scc references that are also part of your solution file. (In this case the SCC provider is AnkhSVN 2.0, so it doesn't contain the actual SCC mapping; just some constant strings that tell the SCC provider to look at the working copy).</p> <p>I think tried to fix the missing project file by caching this information in several locations. But it would be welcome if this file was properly documented.</p>
0
2009-02-06T12:11:59Z
[ "python", "visual-studio", "visual-sourcesafe" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
471,217
<p>There's certainly a performance difference when running a compiled script. If you run normal <code>.py</code> scripts, the machine compiles it every time it is run and this takes time. On modern machines this is hardly noticeable but as the script grows it may become more of an issue.</p>
7
2009-01-22T23:02:39Z
[ "python", "compilation" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
471,220
<p>There is a performance increase in running compiled python. However when you run a .py file as an imported module, python will compile and store it, and as long as the .py file does not change it will always use the compiled version.</p> <p>With any interpeted language when the file is used the process looks something like this:<br /> 1. File is processed by the interpeter.<Br /> 2. File is compiled<br /> 3. Compiled code is executed.<br /></p> <p>obviously by using pre-compiled code you can eliminate step 2, this applies python, PHP and others.</p> <p>Heres an interesting blog post explaining the differences <a href="http://julipedia.blogspot.com/2004/07/compiled-vs-interpreted-languages.html" rel="nofollow">http://julipedia.blogspot.com/2004/07/compiled-vs-interpreted-languages.html</a><br /> And here's an entry that explains the Python compile process <a href="http://effbot.org/zone/python-compile.htm" rel="nofollow">http://effbot.org/zone/python-compile.htm</a></p>
8
2009-01-22T23:03:26Z
[ "python", "compilation" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
471,222
<p>Yep, performance is the main reason and, as far as I know, the only reason.</p> <p>If some of your files aren't getting compiled, maybe Python isn't able to write to the .pyc file, perhaps because of the directory permissions or something. Or perhaps the uncompiled files just aren't ever getting loaded... (scripts/modules only get compiled when they first get loaded)</p>
2
2009-01-22T23:03:58Z
[ "python", "compilation" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
471,227
<p>It's compiled to bytecode which can be used much, much, much faster.</p> <p>The reason some files aren't compiled is that the main script, which you invoke with <code>python main.py</code> is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.</p> <p><em>Important addition by <a href="http://stackoverflow.com/users/46387/ben-blank">Ben Blank</a>:</em></p> <blockquote> <p>It's worth noting that while running a compiled script has a faster <em>startup</em> time (as it doesn't need to be compiled), it doesn't <em>run</em> any faster.</p> </blockquote>
175
2009-01-22T23:06:13Z
[ "python", "compilation" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
471,242
<p>As already mentioned, you can get a performance increase from having your python code compiled into bytecode. This is usually handled by python itself, for imported scripts only.</p> <p>Another reason you might want to compile your python code, could be to protect your intellectual property from being copied and/or modified.</p> <p>You can read more about this in the <a href="http://docs.python.org/tutorial/modules.html#compiled-python-files">Python documentation</a>.</p>
7
2009-01-22T23:09:53Z
[ "python", "compilation" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
471,252
<p>The .pyc file is Python that has already been compiled to byte-code. Python automatically runs a .pyc file if it finds one with the same name as a .py file you invoke.</p> <p>"An Introduction to Python" <a href="http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html">says</a> this about compiled Python files:</p> <blockquote> <p>A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.</p> </blockquote> <p>The advantage of running a .pyc file is that Python doesn't have to incur the overhead of compiling it before running it. Since Python would compile to byte-code before running a .py file anyway, there shouldn't be any performance improvement aside from that.</p> <p>How much improvement can you get from using compiled .pyc files? That depends on what the script does. For a very brief script that simply prints "Hello World," compiling could constitute a large percentage of the total startup-and-run time. But the cost of compiling a script relative to the total run time diminishes for longer-running scripts.</p> <p>The script you name on the command-line is never saved to a .pyc file. Only modules loaded by that "main" script are saved in that way.</p>
57
2009-01-22T23:14:33Z
[ "python", "compilation" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
20,998,077
<p>Beginners assume Python is compiled because of .pyc files. The .pyc file is the compiled bytecode, which is then interpreted. So if you've run your Python code before and have the .pyc file handy, it will run faster the second time, as it doesn't have to re-compile the bytecode</p> <p><strong>compiler:</strong> A compiler is a piece of code that translates the high level language into machine language</p> <p><strong>Interpreters:</strong> Interpreters also convert the high level language into machine readable binary equivalents. Each time when an interpreter gets a high level language code to be executed, it converts the code into an intermediate code before converting it into the machine code. Each part of the code is interpreted and then execute separately in a sequence and an error is found in a part of the code it will stop the interpretation of the code without translating the next set of the codes. </p> <p><strong>Sources:</strong> <a href="http://www.toptal.com/python/why-are-there-so-many-pythons" rel="nofollow">http://www.toptal.com/python/why-are-there-so-many-pythons</a> <a href="http://www.engineersgarage.com/contribution/difference-between-compiler-and-interpreter" rel="nofollow">http://www.engineersgarage.com/contribution/difference-between-compiler-and-interpreter</a></p>
3
2014-01-08T14:13:34Z
[ "python", "compilation" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
23,256,357
<p><strong>Pluses:</strong></p> <p>First: mild, defeatable obfuscation.</p> <p>Second: if compilation results in a significantly smaller file, you will get faster load times. Nice for the web.</p> <p>Third: Python can skip the compilation step. Faster at intial load. Nice for the CPU and the web.</p> <p>Fourth: the more you comment, the smaller the <code>.pyc</code> or <code>.pyo</code> file will be in comparison to the source <code>.py</code> file.</p> <p>Fifth: an end user with only a <code>.pyc</code> or <code>.pyo</code> file in hand is much less likely to present you with a bug they caused by an un-reverted change they forgot to tell you about.</p> <p>Sixth: if you're aiming at an embedded system, obtaining a smaller size file to embed may represent a significant plus, and the architecture is stable so drawback one, detailed below, does not come into play.</p> <p><strong>Top level compilation</strong></p> <p>It is useful to know that you can compile a top level python source file into a <code>.pyc</code> file this way:</p> <pre><code>python -m py_compile myscript.py </code></pre> <p>This removes comments. It leaves <code>docstrings</code> intact. If you'd like to get rid of the <code>docstrings</code> as well (you might want to seriously think about why you're doing that) then compile this way instead...</p> <pre><code>python -OO -m py_compile myscript.py </code></pre> <p>...and you'll get a <code>.pyo</code> file instead of a <code>.pyc</code> file; equally distributable in terms of the code's essential functionality, but smaller by the size of the stripped-out <code>docstrings</code> (and less easily understood for subsequent employment if it had decent <code>docstrings</code> in the first place). But see drawback three, below.</p> <p>Note that python uses the <code>.py</code> file's date, if it is present, to decide whether it should execute the <code>.py</code> file as opposed to the <code>.pyc</code> or <code>.pyo</code> file --- so edit your .py file, and the <code>.pyc</code> or <code>.pyo</code> is obsolete and whatever benefits you gained are lost. You need to recompile it in order to get the <code>.pyc</code> or <code>.pyo</code> benefits back again again, such as they may be.</p> <p><strong>Drawbacks:</strong></p> <p>First: There's a "magic cookie" in <code>.pyc</code> and <code>.pyo</code> files that indicates the system architecture that the python file was compiled in. If you distribute one of these files into an environment of a different type, it will break. If you distribute the <code>.pyc</code> or <code>.pyo</code> without the associated <code>.py</code> to recompile or <code>touch</code> so it supersedes the <code>.pyc</code> or <code>.pyo</code>, the end user can't fix it, either.</p> <p>Second: If <code>docstrings</code> are skipped with the use of the <code>-OO</code> command line option as described above, no one will be able to get at that information, which can make use of the code more difficult (or impossible.)</p> <p>Third: Python's <code>-OO</code> option also implements some optimizations as per the <code>-O</code> command line option; this may result in changes in operation. Known optimizations are:</p> <ul> <li><code>sys.flags.optimize</code> = 1</li> <li><code>assert</code> statements are skipped</li> <li><code>__debug__</code> = False</li> </ul> <p>Fourth: if you had intentionally made your python script executable with something on the order of <code>#!/usr/bin/python</code> on the first line, this is stripped out in <code>.pyc</code> and <code>.pyo</code> files and that functionality is lost.</p> <p>Fifth: somewhat obvious, but if you compile your code, not only can its use be impacted, but the potential for others to learn from your work is reduced, often severely.</p>
20
2014-04-23T22:26:10Z
[ "python", "compilation" ]
Why compile Python code?
471,191
<p>Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? </p> <p>I also notice that some files in my application get compiled into .pyc while others do not, why is this?</p>
160
2009-01-22T22:57:34Z
30,850,028
<p>We use compiled code to distribute to users who do not have access to the source code. Basically to stop inexperienced programers accidentally changing something or fixing bugs without telling us.</p>
2
2015-06-15T16:14:32Z
[ "python", "compilation" ]
What is the best way to extract load average float values from a string in Python?
471,211
<p>If I have a string such as</p> <p>"17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10"</p> <p>what is the best way to extract just the x3 load average values at the end? I have written a regexp that does this but is this the most efficient / fastest method?</p> <pre><code>&gt;&gt;&gt; s = "17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10" &gt;&gt;&gt; print re.findall(r"([0-9]\.\d+)", s) ['0.22', '0.15', '0.10'] </code></pre>
1
2009-01-22T23:01:19Z
471,235
<p>This should work:</p> <pre><code># s is the string to parse loadavg = [float(x) for x in s.rsplit('load average: ', 1)[1].split(', ')] </code></pre>
5
2009-01-22T23:08:04Z
[ "python", "string", "floating-point" ]
What is the best way to extract load average float values from a string in Python?
471,211
<p>If I have a string such as</p> <p>"17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10"</p> <p>what is the best way to extract just the x3 load average values at the end? I have written a regexp that does this but is this the most efficient / fastest method?</p> <pre><code>&gt;&gt;&gt; s = "17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10" &gt;&gt;&gt; print re.findall(r"([0-9]\.\d+)", s) ['0.22', '0.15', '0.10'] </code></pre>
1
2009-01-22T23:01:19Z
471,237
<p>You have the same information in <code>/proc/loadavg</code> special file, so you can do:</p> <pre><code>&gt;&gt;&gt; open("/proc/loadavg").readline().split(" ")[:3] </code></pre>
5
2009-01-22T23:08:32Z
[ "python", "string", "floating-point" ]
What is the best way to extract load average float values from a string in Python?
471,211
<p>If I have a string such as</p> <p>"17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10"</p> <p>what is the best way to extract just the x3 load average values at the end? I have written a regexp that does this but is this the most efficient / fastest method?</p> <pre><code>&gt;&gt;&gt; s = "17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10" &gt;&gt;&gt; print re.findall(r"([0-9]\.\d+)", s) ['0.22', '0.15', '0.10'] </code></pre>
1
2009-01-22T23:01:19Z
471,239
<p>Your way seems fine. If you want to avoid regexps you could do something like</p> <pre><code>&gt;&gt;&gt; print s.split(': ')[1].split(', ') ['0.22', '0.15', '0.10'] </code></pre>
0
2009-01-22T23:08:51Z
[ "python", "string", "floating-point" ]
What is the best way to extract load average float values from a string in Python?
471,211
<p>If I have a string such as</p> <p>"17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10"</p> <p>what is the best way to extract just the x3 load average values at the end? I have written a regexp that does this but is this the most efficient / fastest method?</p> <pre><code>&gt;&gt;&gt; s = "17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10" &gt;&gt;&gt; print re.findall(r"([0-9]\.\d+)", s) ['0.22', '0.15', '0.10'] </code></pre>
1
2009-01-22T23:01:19Z
471,240
<p>I'd use a regex, definitely. You could perhaps increase efficiency a bit by first calling <code>s.find('load average')</code> and starting the regexp match from that position instead of at the beginning of the string (which is the default).</p>
0
2009-01-22T23:09:07Z
[ "python", "string", "floating-point" ]
What is the best way to extract load average float values from a string in Python?
471,211
<p>If I have a string such as</p> <p>"17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10"</p> <p>what is the best way to extract just the x3 load average values at the end? I have written a regexp that does this but is this the most efficient / fastest method?</p> <pre><code>&gt;&gt;&gt; s = "17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10" &gt;&gt;&gt; print re.findall(r"([0-9]\.\d+)", s) ['0.22', '0.15', '0.10'] </code></pre>
1
2009-01-22T23:01:19Z
471,245
<p>A regular expression is the way. But maybe more robustly:</p> <pre><code>re.search(r"load average: (\d+.\d\d), (\d+.\d\d), (\d+.\d\d)$", s).groups() </code></pre> <p>Unless you're doing this really often in a tight loop or some such you needn't worry about performance. Clarity is what's most important. And there I'd say this regexp is hard to beat.</p>
0
2009-01-22T23:11:09Z
[ "python", "string", "floating-point" ]
What is the best way to extract load average float values from a string in Python?
471,211
<p>If I have a string such as</p> <p>"17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10"</p> <p>what is the best way to extract just the x3 load average values at the end? I have written a regexp that does this but is this the most efficient / fastest method?</p> <pre><code>&gt;&gt;&gt; s = "17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10" &gt;&gt;&gt; print re.findall(r"([0-9]\.\d+)", s) ['0.22', '0.15', '0.10'] </code></pre>
1
2009-01-22T23:01:19Z
12,470,834
<p>Or if you are actually looking for the load averages then in Python 2.3+ you have:</p> <pre><code>import os os.getloadavg() </code></pre>
3
2012-09-18T05:22:11Z
[ "python", "string", "floating-point" ]
Organising a GUI application
471,279
<p>This is going to be a generic question.</p> <p>I am struggling in designing a GUI application, esp. with dealing with interactions between different parts.</p> <p>I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the other hand, not having shared state introduces unwanted coupling between components.</p> <p>An example:</p> <p>I want my application to be extendable in an Emacs/Vim sort of way, via scripts. Clearly, some sort of shared state needs to be modified, so that the GUI will use it. My initial plan was having a global "session" that is accessible from everywhere, but I'm not so sure about it.</p> <p>One tricky use case is key bindings. I want the user to be able to specify custom keybindings from a script. Each keybinding maps to an arbitrary command, that receives the session as the only argument.</p> <p>Now, the editor component captures keypresses. It has to have access to the keymappings, which are per-session, so it needs access to the session. Is coupling the editor to the session a good idea? Other components will also need to access the keybindings, so the session now becomes shared and can be a singleton...</p> <p>Is there any good reading about designing GUI applications that goes beyond MVC?</p> <p>This is Python and wxPython, FWIW.</p> <p>[EDIT]: Added concrete usecase.</p>
9
2009-01-22T23:25:40Z
471,297
<p>If you've looked at MVC you're probably moving in the right direction. MVC, MVP, Passive View, Supervising Controller. Those are all different ways, each with their own pros and cons, of accomplishing what you're after. I find that Passive View is the "ideal", but it causes you to introduce far too many widgets into your GUI interfaces (i.e. IInterface). In general I find that Supervising Controller is a good compromise.</p>
2
2009-01-22T23:36:00Z
[ "python", "model-view-controller", "user-interface", "architecture", "wxpython" ]
Organising a GUI application
471,279
<p>This is going to be a generic question.</p> <p>I am struggling in designing a GUI application, esp. with dealing with interactions between different parts.</p> <p>I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the other hand, not having shared state introduces unwanted coupling between components.</p> <p>An example:</p> <p>I want my application to be extendable in an Emacs/Vim sort of way, via scripts. Clearly, some sort of shared state needs to be modified, so that the GUI will use it. My initial plan was having a global "session" that is accessible from everywhere, but I'm not so sure about it.</p> <p>One tricky use case is key bindings. I want the user to be able to specify custom keybindings from a script. Each keybinding maps to an arbitrary command, that receives the session as the only argument.</p> <p>Now, the editor component captures keypresses. It has to have access to the keymappings, which are per-session, so it needs access to the session. Is coupling the editor to the session a good idea? Other components will also need to access the keybindings, so the session now becomes shared and can be a singleton...</p> <p>Is there any good reading about designing GUI applications that goes beyond MVC?</p> <p>This is Python and wxPython, FWIW.</p> <p>[EDIT]: Added concrete usecase.</p>
9
2009-01-22T23:25:40Z
471,307
<p>In MVC, the Model stuff <em>is</em> the shared state of the information.</p> <p>The Control stuff is the shared state of the GUI control settings and responses to mouse-clicks and what-not.</p> <p>Your scripting angle can </p> <p>1) Update the Model objects. This is good. The Control can be "Observers" of the model objects and the View be updated to reflect the observed changes.</p> <p>2) Update the Control objects. This is not so good, but... The Control objects can then make appropriate changes to the Model and/or View.</p> <p>I'm not sure what the problem is with MVC. Could you provide a more detailed design example with specific issues or concerns?</p>
1
2009-01-22T23:40:19Z
[ "python", "model-view-controller", "user-interface", "architecture", "wxpython" ]
Organising a GUI application
471,279
<p>This is going to be a generic question.</p> <p>I am struggling in designing a GUI application, esp. with dealing with interactions between different parts.</p> <p>I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the other hand, not having shared state introduces unwanted coupling between components.</p> <p>An example:</p> <p>I want my application to be extendable in an Emacs/Vim sort of way, via scripts. Clearly, some sort of shared state needs to be modified, so that the GUI will use it. My initial plan was having a global "session" that is accessible from everywhere, but I'm not so sure about it.</p> <p>One tricky use case is key bindings. I want the user to be able to specify custom keybindings from a script. Each keybinding maps to an arbitrary command, that receives the session as the only argument.</p> <p>Now, the editor component captures keypresses. It has to have access to the keymappings, which are per-session, so it needs access to the session. Is coupling the editor to the session a good idea? Other components will also need to access the keybindings, so the session now becomes shared and can be a singleton...</p> <p>Is there any good reading about designing GUI applications that goes beyond MVC?</p> <p>This is Python and wxPython, FWIW.</p> <p>[EDIT]: Added concrete usecase.</p>
9
2009-01-22T23:25:40Z
505,858
<p>Sorry to jump on this question so late, but nothing, I mean <em>nothing</em> can beat looking at the source of an application that does something similar. (I might recommend something like <a href="http://pida.co.uk" rel="nofollow">http://pida.co.uk</a>, but there are plenty of extensible wx+Python IDEs out there as that sounds like what you are making).</p> <p>If I might make a few notes:</p> <ol> <li><p>message passing is not inherently bad, and it doesn't necessarily cause coupling between components as long as components adhere to interfaces.</p></li> <li><p>shared state is not inherently bad, but I would go with your gut instinct and use as little as possible. Since the universe itself is stateful, you can't really avoid this entirely. I tend to use a shared "Boss" object which is usually a non-singleton single instance per application, and is responsible for brokering other components.</p></li> <li><p>For keybindings, I tend to use some kind of "Action" system. Actions are high level things which a user can do, for example: "Save the current buffer", and they can be conveniently represented in the UI by toolbar buttons or menu items. So your scripts/plugins create actions, and register them with something central (eg some kind of registry object - see 1 and 2). And their involvement ends there. On top of this you have some kind of key-binding service that maps keys to actions (which it lists from the registry, per session or otherwise). This way you have achieved separation of the plugin and keybinding code, separation of the editor and the action code. As an added bonus your task of "Configuring shortcuts" or "User defined key maps" is made particularly easier.</p></li> </ol> <p>I could go on, but most of what I have to say is in the PIDA codebase, so back to my original point...</p>
3
2009-02-03T02:39:33Z
[ "python", "model-view-controller", "user-interface", "architecture", "wxpython" ]
Is there a Term::ANSIScreen equivalent for Python?
471,463
<p>Perl has the excellent module <code>Term::ANSIScreen</code> for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aware of an equivalent?</p>
3
2009-01-23T00:43:24Z
471,467
<p>While I haven't used it myself, I believe the curses library is commonly used for this:</p> <p><a href="http://docs.python.org/library/curses.html" rel="nofollow">http://docs.python.org/library/curses.html</a></p> <p>And the How-to:</p> <p><a href="http://docs.python.org/howto/curses.html#curses-howto" rel="nofollow">http://docs.python.org/howto/curses.html#curses-howto</a></p> <p>Unfortunatly, this module doesn't appear to be available in the standard library for windows. This site apparently has a windows solution:</p> <p><a href="http://adamv.com/dev/python/curses/" rel="nofollow">http://adamv.com/dev/python/curses/</a></p>
2
2009-01-23T00:48:12Z
[ "python", "perl", "ansi" ]
Is there a Term::ANSIScreen equivalent for Python?
471,463
<p>Perl has the excellent module <code>Term::ANSIScreen</code> for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aware of an equivalent?</p>
3
2009-01-23T00:43:24Z
471,512
<p>Here's a <a href="http://code.activestate.com/recipes/574451/" rel="nofollow">cookbook recipe</a> on ActiveState to get you started. It covers colors and positioning.</p> <p><em>[Edit: The pygments code submitted above by Jorge Vargas is a better approach. ]</em></p>
3
2009-01-23T01:19:26Z
[ "python", "perl", "ansi" ]
Is there a Term::ANSIScreen equivalent for Python?
471,463
<p>Perl has the excellent module <code>Term::ANSIScreen</code> for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aware of an equivalent?</p>
3
2009-01-23T00:43:24Z
1,977,010
<p>If you only need colors You may want to borrow the implementation from pygments. IMO it's much cleaner than the one from ActiveState</p> <p><a href="http://dev.pocoo.org/hg/pygments-main/file/b2deea5b5030/pygments/console.py">http://dev.pocoo.org/hg/pygments-main/file/b2deea5b5030/pygments/console.py</a></p>
8
2009-12-29T21:18:25Z
[ "python", "perl", "ansi" ]
Is there a Term::ANSIScreen equivalent for Python?
471,463
<p>Perl has the excellent module <code>Term::ANSIScreen</code> for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aware of an equivalent?</p>
3
2009-01-23T00:43:24Z
2,257,128
<p>There is also the <a href="http://pypi.python.org/pypi/termcolor" rel="nofollow">termcolor</a> and the <a href="https://github.com/gfxmonk/termstyle" rel="nofollow">termstyle</a> packages. The latter is capable of disabling colour output if stdout is not a terminal.</p> <p>See also <a href="http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python">this question</a>.</p>
3
2010-02-13T09:56:43Z
[ "python", "perl", "ansi" ]
Any way to override the and operator in Python?
471,546
<p>I tried overriding <code>__and__</code>, but that is for the &amp; operator, not <em>and</em> - the one that I want. Can I override <em>and</em>?</p>
18
2009-01-23T01:36:42Z
471,559
<p>Not really. There's no special method name for the short-circuit logic operators.</p>
1
2009-01-23T01:41:49Z
[ "python" ]
Any way to override the and operator in Python?
471,546
<p>I tried overriding <code>__and__</code>, but that is for the &amp; operator, not <em>and</em> - the one that I want. Can I override <em>and</em>?</p>
18
2009-01-23T01:36:42Z
471,561
<p>You cannot override the <code>and</code>, <code>or</code>, and <code>not</code> boolean operators.</p>
14
2009-01-23T01:42:34Z
[ "python" ]
Any way to override the and operator in Python?
471,546
<p>I tried overriding <code>__and__</code>, but that is for the &amp; operator, not <em>and</em> - the one that I want. Can I override <em>and</em>?</p>
18
2009-01-23T01:36:42Z
471,567
<p>No you can't override <code>and</code> and <code>or</code>. With the behavior that these have in Python (i.e. short-circuiting) they are more like control flow tools than operators and overriding them would be more like overriding <code>if</code> than + or -.</p> <p>You <em>can</em> influence the truth value of your objects (i.e. whether they evaluate as true or false) by overriding <code>__nonzero__</code> (or <code>__bool__</code> in Python 3).</p>
29
2009-01-23T01:44:25Z
[ "python" ]
Customizing an Admin form in Django while also using autodiscover
471,550
<p>I want to modify a few tiny details of Django's built-in <code>django.contrib.auth</code> module. Specifically, I want a different form that makes username an email field (and email an alternate email address. (I'd rather not modify <code>auth</code> any more than necessary -- a simple form change <em>seems</em> to be all that's needed.)</p> <p>When I use <code>autodiscover</code> with a customized <code>ModelAdmin</code> for <code>auth</code> I wind up conflicting with <code>auth</code>'s own admin interface and get an "already registered" error.</p> <p>It looks like I have to create my own admin site, enumerating all of my Models. It's only 18 classes, but it seems like a DRY problem -- every change requires both adding to the Model <strong>and</strong> adding to the customized admin site.</p> <p>Or, should I write my own version of "<code>autodiscover</code> with exclusions" to essentially import all the <code>admin</code> modules <strong>except</strong> <code>auth</code>?</p>
22
2009-01-23T01:38:17Z
471,661
<p>None of the above. Just use admin.site.unregister(). Here's how I recently added filtering Users on is_active in the admin (<strong>n.b.</strong> is_active filtering is now on the User model by default in Django core; still works here as an example), all DRY as can be:</p> <pre><code>from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User class MyUserAdmin(UserAdmin): list_filter = UserAdmin.list_filter + ('is_active',) admin.site.unregister(User) admin.site.register(User, MyUserAdmin) </code></pre>
43
2009-01-23T02:22:18Z
[ "python", "django", "forms", "django-admin", "customization" ]
Customizing an Admin form in Django while also using autodiscover
471,550
<p>I want to modify a few tiny details of Django's built-in <code>django.contrib.auth</code> module. Specifically, I want a different form that makes username an email field (and email an alternate email address. (I'd rather not modify <code>auth</code> any more than necessary -- a simple form change <em>seems</em> to be all that's needed.)</p> <p>When I use <code>autodiscover</code> with a customized <code>ModelAdmin</code> for <code>auth</code> I wind up conflicting with <code>auth</code>'s own admin interface and get an "already registered" error.</p> <p>It looks like I have to create my own admin site, enumerating all of my Models. It's only 18 classes, but it seems like a DRY problem -- every change requires both adding to the Model <strong>and</strong> adding to the customized admin site.</p> <p>Or, should I write my own version of "<code>autodiscover</code> with exclusions" to essentially import all the <code>admin</code> modules <strong>except</strong> <code>auth</code>?</p>
22
2009-01-23T01:38:17Z
472,602
<p>I think it might be easier to do this with a custom auth backend and thus remove the need for a customized ModelAdmin.</p> <p>I did something similar with this snippet: <a href="http://www.djangosnippets.org/snippets/74/" rel="nofollow">http://www.djangosnippets.org/snippets/74/</a></p>
2
2009-01-23T11:30:25Z
[ "python", "django", "forms", "django-admin", "customization" ]
Python/Twisted multiuser server - what is more efficient?
471,660
<p>In Python, if I want my server to scale well CPU-wise, I obviously need to spawn multiple processes. I was wondering which is better (using Twisted):</p> <p>A) The manager process (the one who holds the actual socket connections) puts received packets into a shared queue (the one from the multiprocessing module), and worker processes pull the packets out of the queue, process them and send the results back to the client.</p> <p>B) The manager process (the one who holds the actual socket connections) launches a deferred thread and then calls the apply() function on the process pool. Once the result returns from the worker process, the manager sends the result back to the client.</p> <p>In both implementations, the worker processes use thread pools so they can work on more than one packet at once (since there will be a lot of database querying).</p>
2
2009-01-23T02:21:45Z
474,353
<p>I think that B is problematic. The thread would only run on one CPU, and even if it runs a process, the thread is still running. A may be better.</p> <p>It is best to try and measure both in terms of time and see which one is faster and which one scales well. However, I'll reiterate that I highly doubt that B will scale well.</p>
2
2009-01-23T20:17:42Z
[ "python", "twisted", "multi-user" ]
Python/Twisted multiuser server - what is more efficient?
471,660
<p>In Python, if I want my server to scale well CPU-wise, I obviously need to spawn multiple processes. I was wondering which is better (using Twisted):</p> <p>A) The manager process (the one who holds the actual socket connections) puts received packets into a shared queue (the one from the multiprocessing module), and worker processes pull the packets out of the queue, process them and send the results back to the client.</p> <p>B) The manager process (the one who holds the actual socket connections) launches a deferred thread and then calls the apply() function on the process pool. Once the result returns from the worker process, the manager sends the result back to the client.</p> <p>In both implementations, the worker processes use thread pools so they can work on more than one packet at once (since there will be a lot of database querying).</p>
2
2009-01-23T02:21:45Z
500,624
<p>I think that "A" is the answer you want, but you don't have to do it yourself.</p> <p>Have you considered <a href="https://launchpad.net/ampoule" rel="nofollow">ampoule</a>?</p>
1
2009-02-01T11:20:45Z
[ "python", "twisted", "multi-user" ]
Pros and cons of IronPython and IronPython Studio
471,712
<p>We are ready in our company to move everything to Python instead of C#, we are a consulting company and we usually write small projects in C# we don't do huge projects and our work is more based on complex mathematical models not complex software structures. So we believe IronPython is a good platform for us because it provides standard GUI functionality on windows and access to all of .Net libraries. </p> <p>I know Ironpython studio is not complete, and in fact I had a hard time adding my references but I was wondering if someone could list some of the pros and cons of this migration for us, considering Python code is easier to read by our clients and we usually deliver a proof-of-concept prototype instead of a full-functional code, our clients usually go ahead and implement the application themselves</p>
16
2009-01-23T02:49:32Z
471,725
<p>The way you describe things, it sounds like you're company is switching to Python simple for the sake of Python. Is there some specific reason you want to use Python? Is a more dynamic language necessary? Is the functional programming going to help you at all? If you've got a perfectly good working set of tools in C#, why bother switching?</p> <p>If you're set on switching, you may want to consider starting with standard Python unless you're specifically tied to the .NET libraries. You can write cross platform GUIs using a number of different frameworks like wxPython, pyQt, etc. That said, Visual Studio has a far superior GUI designer to just about any of the tools out there for creating Python windowed layouts.</p>
5
2009-01-23T02:59:23Z
[ "python", "ironpython", "ironpython-studio" ]
Pros and cons of IronPython and IronPython Studio
471,712
<p>We are ready in our company to move everything to Python instead of C#, we are a consulting company and we usually write small projects in C# we don't do huge projects and our work is more based on complex mathematical models not complex software structures. So we believe IronPython is a good platform for us because it provides standard GUI functionality on windows and access to all of .Net libraries. </p> <p>I know Ironpython studio is not complete, and in fact I had a hard time adding my references but I was wondering if someone could list some of the pros and cons of this migration for us, considering Python code is easier to read by our clients and we usually deliver a proof-of-concept prototype instead of a full-functional code, our clients usually go ahead and implement the application themselves</p>
16
2009-01-23T02:49:32Z
472,312
<p>There are a lot of reasons why you want to switch from C# to python, i did this myself recently. After a lot of investigating, here are the reasons why i stick to CPython:</p> <ul> <li>Performance: There are some articles out there stating that there are always cases where ironpython is slower, so if performance is an issue</li> <li>Take the original: many people argue that new features etc. are always integrated in CPython first and you have to wait until they are implemented in ironpython.</li> <li>Licensing: Some people argue this is a timebomb: nobody knows how the licensing of ironpython/mono might change in near future</li> <li>Extensions: one of the strengths of python are the thousands of extensions which are all usable by CPython, as you mentioned mathematical problems: numpy might be a suitable fast package for you which might not run as expected under IronPython (although <a href="http://www.resolversystems.com/documentation/index.php/Ironclad">Ironclad</a>)</li> <li>Especially under Windows you have a native GUI-toolkit with wxPython which also looks great under several other platforms and there are pyQT and a lot of other toolkits. They have nice designer like wxGlade, but here VisualStudio C# Designer is easier to use.</li> <li>Platform independence (if this is an issue): CPython is ported to really a lot of platforms, whereas ironpython can only be used on the major platforms (recently read a developer was sad that he couldn't get mono to run under his AIX)</li> </ul> <p>Ironpython is a great work, and if i had a special .NET library i would have to use, IronPython might be the choice, but for general purpose problems, people seem to suggest using the original CPython, unless Guido changes his mind.</p>
8
2009-01-23T09:06:35Z
[ "python", "ironpython", "ironpython-studio" ]
Pros and cons of IronPython and IronPython Studio
471,712
<p>We are ready in our company to move everything to Python instead of C#, we are a consulting company and we usually write small projects in C# we don't do huge projects and our work is more based on complex mathematical models not complex software structures. So we believe IronPython is a good platform for us because it provides standard GUI functionality on windows and access to all of .Net libraries. </p> <p>I know Ironpython studio is not complete, and in fact I had a hard time adding my references but I was wondering if someone could list some of the pros and cons of this migration for us, considering Python code is easier to read by our clients and we usually deliver a proof-of-concept prototype instead of a full-functional code, our clients usually go ahead and implement the application themselves</p>
16
2009-01-23T02:49:32Z
472,355
<p>My company, Resolver Systems, develops what is probably the biggest application written in IronPython yet. (It's called Resolver One, and it's a Pythonic spreadsheet). We are also hosting the Ironclad project (to run CPython extensions under IronPython) and that is going well (we plan to release a beta of Resolver One &amp; numpy soon).</p> <p>The reason we chose IronPython was the .NET integration - our clients want 100% integration on Windows and the easiest way to do that right now is .NET. </p> <p>We design our GUI (without behaviour) in Visual Studio, compile it into a DLL and subclass it from IronPython to add behaviour.</p> <p>We have found that IronPython is faster at some cases and slower at some others. However, the IronPython team is very responsive, whenever we report a regression they fix it and usually backport it to the bugfix release. If you worry about performance, you can always implement a critical part in C# (we haven't had to do that yet).</p> <p>If you have experience with C#, then IronPython will be natural for you, and easier than C#, especially for prototypes.</p> <p>Regarding IronPython studio, we don't use it. Each of us has his editor of choice (TextPad, Emacs, Vim &amp; Wing), and everything works fine.</p>
17
2009-01-23T09:29:31Z
[ "python", "ironpython", "ironpython-studio" ]
Way to have compiled python files in a separate folder?
471,928
<p>Is it possible to have Python save the <code>.pyc</code> files to a separate folder location that is in <code>sys.path</code>?</p> <pre><code>/code foo.py foo.pyc bar.py bar.pyc </code></pre> <p>To:</p> <pre><code>/code foo.py bar.py /code_compiled foo.pyc bar.pyc </code></pre> <p>I would like this because I feel it'd be more organized. Thanks for any help you can give me.</p>
25
2009-01-23T05:02:12Z
471,985
<p>There is <a href="http://www.python.org/dev/peps/pep-0304/">PEP 304: Controlling Generation of Bytecode Files</a>. Its status is <code>Withdrawn</code> and corresponding <a href="http://bugs.python.org/issue677103">patch</a> rejected. Therefore there might be no direct way to do it. </p> <p>If you don't need source code then you may just delete <code>*.py</code> files. <code>*.pyc</code> files can be used as is or packed in an egg. </p>
16
2009-01-23T05:26:17Z
[ "python", "file", "compiled" ]
Way to have compiled python files in a separate folder?
471,928
<p>Is it possible to have Python save the <code>.pyc</code> files to a separate folder location that is in <code>sys.path</code>?</p> <pre><code>/code foo.py foo.pyc bar.py bar.pyc </code></pre> <p>To:</p> <pre><code>/code foo.py bar.py /code_compiled foo.pyc bar.pyc </code></pre> <p>I would like this because I feel it'd be more organized. Thanks for any help you can give me.</p>
25
2009-01-23T05:02:12Z
472,583
<p>"I feel it'd be more organized" Why? How? What are you trying to accomplish?</p> <p>The point of saving the compiler output is to save a tiny bit of load time when the module gets imported. Why make this more complex? If you don't like the .pyc's, then run a "delete all the .pyc's" script periodically.</p> <p>They aren't essential; they're helpful. Why turn off that help?</p> <p>This isn't C, C++ or Java where the resulting objects are essential. This is just a cache that Python happens to use. We mark them as "ignored" in Subversion so they don't accidentally wind up getting checked in.</p>
0
2009-01-23T11:20:21Z
[ "python", "file", "compiled" ]
Way to have compiled python files in a separate folder?
471,928
<p>Is it possible to have Python save the <code>.pyc</code> files to a separate folder location that is in <code>sys.path</code>?</p> <pre><code>/code foo.py foo.pyc bar.py bar.pyc </code></pre> <p>To:</p> <pre><code>/code foo.py bar.py /code_compiled foo.pyc bar.pyc </code></pre> <p>I would like this because I feel it'd be more organized. Thanks for any help you can give me.</p>
25
2009-01-23T05:02:12Z
472,862
<p>I agree, distributing your code as an egg is a great way to keep it organized. What could be more organized than a single-file containing all of the code and meta-data you would ever need. Changing the way the bytecode compiler works is only going to cause confusion.</p> <p>If you really do not like the location of those pyc files, an alternative is to run from a read-only folder. Since python will not be able to write, no pyc files ever get made. The hit you take is that every python file will have to be re-compiled as soon as it is loaded, regardless of whether you have changed it or not. That means your start-up time will be a lot worse.</p>
3
2009-01-23T13:23:25Z
[ "python", "file", "compiled" ]
Way to have compiled python files in a separate folder?
471,928
<p>Is it possible to have Python save the <code>.pyc</code> files to a separate folder location that is in <code>sys.path</code>?</p> <pre><code>/code foo.py foo.pyc bar.py bar.pyc </code></pre> <p>To:</p> <pre><code>/code foo.py bar.py /code_compiled foo.pyc bar.pyc </code></pre> <p>I would like this because I feel it'd be more organized. Thanks for any help you can give me.</p>
25
2009-01-23T05:02:12Z
2,036,126
<p>I disagree. The reasons are wrong or at least not well formulated; but the direction is valid. There are good reasons for being able to segregate source code from compiled objects. Here are a few of them (all of them I have run into at one point or another):</p> <ul> <li>embedded device reading off a ROM, but able to use an in memory filesystem on RAM.</li> <li>multi-os dev environment means sharing (with samba/nfs/whatever) my working directory and building on multiple platforms.</li> <li>commercial company wishes to only distribute pyc to protect the IP</li> <li>easily run test suite for multiple versions of python using the same working directory</li> <li>more easily clean up transitional files (rm -rf $OBJECT_DIR as opposed to find . -name '*.pyc' -exec rm -f {} \;)</li> </ul> <p>There are workarounds for all these problems, BUT they are mostly workarounds NOT solutions. The proper solution in most of these cases would be for the software to accept an alternative location for storing and lookup of these transitional files.</p>
2
2010-01-10T04:49:45Z
[ "python", "file", "compiled" ]
Way to have compiled python files in a separate folder?
471,928
<p>Is it possible to have Python save the <code>.pyc</code> files to a separate folder location that is in <code>sys.path</code>?</p> <pre><code>/code foo.py foo.pyc bar.py bar.pyc </code></pre> <p>To:</p> <pre><code>/code foo.py bar.py /code_compiled foo.pyc bar.pyc </code></pre> <p>I would like this because I feel it'd be more organized. Thanks for any help you can give me.</p>
25
2009-01-23T05:02:12Z
2,985,939
<p>If you're willing to sacrifice bytecode generation altogether for it, there's a command line flag:</p> <pre><code>python -B file_that_imports_others.py </code></pre> <p>Can be put into IDE's build/run preferences</p>
2
2010-06-06T21:19:39Z
[ "python", "file", "compiled" ]
Way to have compiled python files in a separate folder?
471,928
<p>Is it possible to have Python save the <code>.pyc</code> files to a separate folder location that is in <code>sys.path</code>?</p> <pre><code>/code foo.py foo.pyc bar.py bar.pyc </code></pre> <p>To:</p> <pre><code>/code foo.py bar.py /code_compiled foo.pyc bar.pyc </code></pre> <p>I would like this because I feel it'd be more organized. Thanks for any help you can give me.</p>
25
2009-01-23T05:02:12Z
11,849,405
<p>There is ongoing pep that will <a href="http://www.python.org/dev/peps/pep-3147/" rel="nofollow">enable building bytecode to magic directory</a>. </p> <p>Basically all python files will be compiled to directory <code>__pythoncache__</code>.</p>
1
2012-08-07T15:40:23Z
[ "python", "file", "compiled" ]
Way to have compiled python files in a separate folder?
471,928
<p>Is it possible to have Python save the <code>.pyc</code> files to a separate folder location that is in <code>sys.path</code>?</p> <pre><code>/code foo.py foo.pyc bar.py bar.pyc </code></pre> <p>To:</p> <pre><code>/code foo.py bar.py /code_compiled foo.pyc bar.pyc </code></pre> <p>I would like this because I feel it'd be more organized. Thanks for any help you can give me.</p>
25
2009-01-23T05:02:12Z
15,776,555
<p>Since Python 3.2 has been implemented <a href="http://www.python.org/dev/peps/pep-3147/" rel="nofollow">PEP 3147</a>: this means that all .pyc files are generated inside a <strong>__<em>pycache</em>__</strong> directory (there will be a <strong>__<em>pycache</em>__</strong> directory for each directory where you have Python files, and it will hold .pyc files for each version of Python used on the sources)</p>
1
2013-04-02T23:54:50Z
[ "python", "file", "compiled" ]
Way to have compiled python files in a separate folder?
471,928
<p>Is it possible to have Python save the <code>.pyc</code> files to a separate folder location that is in <code>sys.path</code>?</p> <pre><code>/code foo.py foo.pyc bar.py bar.pyc </code></pre> <p>To:</p> <pre><code>/code foo.py bar.py /code_compiled foo.pyc bar.pyc </code></pre> <p>I would like this because I feel it'd be more organized. Thanks for any help you can give me.</p>
25
2009-01-23T05:02:12Z
16,476,434
<p><em>In the dark and ancient days of 2003, PEP 304 came forth to challenge this problem. Its patch was found wanting. Environment variable platform dependencies and version skews ripped it to shreds and left its bits scattered across the wastelands.</em></p> <p><em>After years of suffering, a new challenger rose in the last days of 2009. Barry Warsaw summoned PEP 3147 and sent it to do battle, wielding a simple weapon with skill. The PEP crushed the cluttering PYC files, silenced the waring Unladen Swallow and CPython interpreter each trying to argue its PYC file should be triumphant, and allowed Python to rest easy with its dead ghosts occasionally running in the dead of night. PEP 3147 was found worthy by the dictator and was knighted into the official roles in the days of 3.2.</em></p> <p>As of 3.2, Python stores a module's PYC files in <code>__pycache__</code> under the module's directory. Each PYC file contains the name and version of the interpreter, e.g., <code>__pycache__/foo.cpython-33.pyc</code>. You might also have a <code>__pycache__/foo.cpython-32.pyc</code> compiled by an earlier version of Python. The right magic happens: the correct one is used and recompiled if out of sync with the source code. At runtime, look at the module's <code>mymodule.__cached__</code> for the pyc filename and parse it with <code>imp.get_tag()</code>. See <a href="http://docs.python.org/3/whatsnew/3.2.html#pep-3147-pyc-repository-directories">the What's New section</a> for more information.</p> <p>TL;DR - Just works in Python 3.2 and above. Poor hacks substitute for versions before that.</p>
7
2013-05-10T06:30:04Z
[ "python", "file", "compiled" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
472,017
<p>You would want to use <code>__slots__</code> if you are going to instantiate a lot (hundreds, thousands) of objects of the same class. <code>__slots__</code> only exists as a memory optimization tool.</p> <p>It's highly discouraged to use <code>__slots__</code> for constraining attribute creation, and in general you want to avoid it because it breaks pickle, along with some other introspection features of python.</p>
105
2009-01-23T05:50:21Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
472,024
<p>Quoting <a href="http://code.activestate.com/lists/python-list/531365/">Jacob Hallen</a>:</p> <blockquote> <p>The proper use of <code>__slots__</code> is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overhead of one dict for every object that uses slots. While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.</p> <p>Unfortunately there is a side effect to slots. They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the control freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python, there should be only one obvious way of doing something.</p> <p>Making CPython smart enough to handle saving space without <code>__slots__</code> is a major undertaking, which is probably why it is not on the list of changes for P3k (yet).</p> </blockquote>
243
2009-01-23T05:54:46Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
472,570
<p>You have — essentially — no use for <code>__slots__</code>. </p> <p>For the time when you think you might need <code>__slots__</code>, you actually want to use <strong>Lightweight</strong> or <strong>Flyweight</strong> design patterns. These are cases when you no longer want to use purely Python objects. Instead, you want a Python object-like wrapper around an array, struct, or numpy array.</p> <pre><code>class Flyweight(object): def get(self, theData, index): return theData[index] def set(self, theData, index, value): theData[index]= value </code></pre> <p>The class-like wrapper has no attributes — it just provides methods that act on the underlying data. The methods can be reduced to class methods. Indeed, it could be reduced to just functions operating on the underlying array of data.</p>
2
2009-01-23T11:15:19Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
472,899
<p>Each python object has a <code>__dict__</code> atttribute which is a dictionary containing all other attributes. e.g. when you type <code>self.attr</code> python is actually doing <code>self.__dict__['attr']</code>. As you can imagine using a dictionary to store attribute takes some extra space &amp; time for accessing it.</p> <p>However, when you use <code>__slots__</code>, any object created for that class won't have a <code>__dict__</code> attribute. Instead, all attribute access is done directly via pointers.</p> <p>So if want a C style structure rather than a full fledged class you can use <code>__slots__</code> for compacting size of the objects &amp; reducing attribute access time. A good example is a Point class containing attributes x &amp; y. If you are going to have a lot of points, you can try using <code>__slots__</code> in order to conserve some memory.</p>
48
2009-01-23T13:38:21Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
13,547,906
<p>Slots are very useful for library calls to eliminate the "named method dispatch" when making function calls. This is mentioned in the SWIG <a href="http://www.swig.org/Doc2.0/Python.html#Python_builtin_types">documentation</a>. For high performance libraries that want to reduce function overhead for commonly called functions using slots is much faster.</p> <p>Now this may not be directly related to the OPs question. It is related more to building extensions than it does to using the <strong>slots</strong> syntax on an object. But it does help complete the picture for the usage of slots and some of the reasoning behind them.</p>
10
2012-11-25T03:06:11Z
[ "python" ]