Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python range() builtin function, erm... malfunctioning with Django

What, if anything, is wrong with this line of python code:

daterange = [begin + timedelta(n) for n in range((end - begin).days)]

Where begin and end are datetime.date objects with valid values.

I'm using this in a Django view to process some data, but everytime the view this is in gets called I get the following error with the aforementioned line highlighted:

UnboundLocalError at /url/of/error/creating/view/here/
local variable 'range' referenced before assignment

If I execute this line inside the interpreter it works fine, but somehow it doesn't fly inside a Django view. I don't understand why range is being interpreted as a variable name at all. Is there actually something wrong with this line, or is it something else in the code that's making Django complain?

Help!

like image 721
chandsie Avatar asked Apr 09 '26 18:04

chandsie


1 Answers

There's nothing wrong with Django. You create a local variable range in the same scope (by assigning one). For instance range = None in the very last line of a function makes Python consider an occurrence of range in the first line of the same function a reference to that local variable. Since it doesn't have a value assigned at that point, you get an UnboundLocalError.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!