python

Python PIL and StringIO

I'm trying to download images from URLs and pass them to PIL. I would like to use less resources as possible, especially RAM. What would the best way of dealing with this? I've had suggestions to use cStringIO. ...

Why doesn't import prevent NameError in a python script run with execfile()?

I looked at a number of existing questions about NameError exceptions when scripts are run with exec statements or execfile() in Python, but haven't found a good explanation yet of the following behavior. I want to make a simple game that creates script objects at runtime with execfile(). Below are 4 modules that demonstrate the proble...

Mocking imported modules in Python

I'm trying to implement unit tests for function that uses imported external objects. For example helpers.py is: import os import pylons def some_func(arg): ... var1 = os.path.exist(...) var2 = os.path.getmtime(...) var3 = pylons.request.environ['HTTP_HOST'] ... So when I'm creating unit test for it I do some mocking (...

Display value in Charfield for foreign key in django on error

Let's say I've got a model and it has a foreign key to another one. class ModelA(models.Model): field = models.CharField(max_length=100) class ModelB(models.Model): model_a = models.ForeignKey(ModelA) Than I've got this form: class FormB(models.ModelForm): model_a = forms.CharField(required=True) def clean(self): ...

python single configuration file

I am developing a project that requires a single configuration file whose data is used by multiple modules. My question is: what is the common approach to that? should i read the configuration file from each of my modules (files) or is there any other way to do it? I was thinking to have a module named config.py that reads the configura...

Unable to get custom context processor to be invoked

I am trying to create a custom context processor which will render a list of menu items for a logged in user. I have done the following:- Within my settings.py I have TEMPLATE_CONTEXT_PROCESSOR = ( 'django.contrib.auth.context_processors.auth', 'mysite.accounts.context_processors.user_menu', ) Under the accounts submodule ...

How can I use Boost::Python to add a method to an exported class without modifying the base class?

I have a class in C++ that I can't modify. However, that class holds an std::list<> of items that I need to be able to access in a Python extension. Since Boost::Python doesn't seem to have a built-in conversion between an std::list and a Python list, I was hoping to be able to write a method in C++ that could do this conversion for me...

Accessing Lower Triangle of a Numpy Matrix?

Okay, so basically lets say i have a matrix: matrix([[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]) Is it possible to get the area below the diagonal easily when working with numpy matrixs? I looked around and could not find anything. I can do the standard, for loo...

What can I do if django runserver seems to be caching my urls.py and settings.py?

I detected this problem when updating the patterns in URLConf and seeing that the new pattern wasn't matched anywhere. So, with urls.py I don't get anywhere when writing random lines on it, I mean, invalid code, and django doesn't throw any exception and serves the urls just fine. So I checked ROOT_URLCONF in settings.py, and it points...

Why am I getting an AttributeError when I have the attribute?

Hi, I keep getting the following error: AttributeError: Caribou instance has no attribute 'on_key_up' The problem is, I'm pretty sure I do have that attribute... Here are some excerpts from my code (from caribou.py): def on_key_up(self, event): if event.event_string == "Shift_R": _r_shift_down = False elif event.event_string...

Looping Redirect with PyFacebook and Google App Engine

I have a Python Facebook project hosted on Google App Engine and use the following code to handle initialization of the Facebook API using PyFacebook. # Facebook Initialization def initialize_facebook(f): # Redirection handler def redirect(self, url): logger.info('Redirecting the user to: ' + url) self.response....

How many private variables are too many? Capsulizing classes? Class Practices?

Okay so i am currently working on an inhouse statistics package for python, its mainly geared towards a combination of working with arcgis geoprocessor, for modeling comparasion and tools. Anyways, so i have a single class, that calculates statistics. Lets just call it Stats. Now my Stats class, is getting to the point of being very lar...

Attempting to insert an integer from a list into datetime object...

Hi all, What I am trying to accomplish is very simple: creating a loop from a range (pretty self explanatory below) that will insert the month into the datetime object. I know %d requires an integer, and I know that 'month' type is int...so I'm kind of stuck as to why I can't substitute my month variable. Here is my code: all_months=...

Unable to access database from within a method

I keep receiving the error, "TypeError: 'Shard' object is unsubscriptable." #Establish an on-demand connection to the central database def connectCentral(): engine = engine_from_config(config, 'sqlalchemy.central.') central.engine = engine central.Session.configure(bind=engine) #Establish an on-demand connection to a shard ...

Process for converting python program into threaded application?

I have a code-base that I'm looking to split up and add to by using threading, however I'm relatively new on how to handle it. Please before reading further respect my wish of NOT just re-writing this code and tossing it back at me with the problem solved. I would much rather work the problem out by someone pointing me in the right dir...

How to import other Python files in Python

Hey , I have a newbie question about importing in Python First : How exactly can I import a specific python file .. import file.py sometimes doesn't work Second : How to import a folder .. instead of a specific file Third ( and the most important ) : I want to load a Python file dynamically in runtime, based on user input Thanks ...

python csv header error

Trying to read headers for a csv file with: reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True) headers = reader.fieldnames for header in sorted(set(headers)): It worked on development server, throws this error on production 'NoneType' object is not iterable Debug shows headers has None value while the csv file has head...

How to build a web crawler based on Scrapy to run forever?

I want to build a web crawler based on Scrapy to grab news pictures from several news portal website. I want to this crawler to be: Run forever Means it will periodical re-visit some portal pages to get updates. Schedule priorities. Give different priorities to different type of URLs. Multi thread fetch I've read the Scrapy docum...

Python: does the set class "leak" when items are removed, like a dict?

I know that Python dicts will "leak" when items are removed (because the item's slot will be overwritten with the magic "removed" value)… But will the set class behave the same way? Is it safe to keep a set around, adding and removing stuff from it over time? Edit: Alright, I've tried it out, and here's what I found: >>> import gc >>>...

Custom data types in numpy arrays

I'm creating a numpy array which is to be filled with objects of a particular class I've made. I'd like to initialize the array such that it will only ever contain objects of that class. For example, here's what I'd like to do, and what happens if I do it. class Kernel: pass >>> L = np.empty(4,dtype=Kernel) TypeError: data type n...