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

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!

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.

Related

Define variables as variables in Robot Framework with Python file

This works
<<file1.robot>>
**Setting**
Resource file2.robot
**Variables**
${file1_var1} ${file2_var1}
**Keyword**
Check It
Click ${file1_var1}
where
<<file2.robot>>
**Settings**
Variables file2Locator.py
<<file2Locator.py>>
file2_var1 = "id=Clickable"
Click id=Clickable is called successfully, with keyword "Click It"
However, the following FAILS:
<<file1Fail.robot>>
**Setting**
Resource file2.robot
Variables file1Fail.py firstSet
**Keyword**
Check It
Click ${file1_var1}
Where
<<file1Fail.py>>
SetOneVar = {'file1_var1': "${file2_var1}"}
def get_variables(arg):
if arg == 'firstSet': return SetOneVar
else return
due to the error where UiSelector[DESCRIPTION=${file2_var1}] clearly does not work.
In other words, upon getting variables from a python file 1, Click ${file2_var1} is literally called, instead of Click id=Clickable. "${file2_var1}" is not being replaced by "id=Clickable" anymore.
Any solution to this? How to call define a variable as another variable imported at another resource file
In the python file the value of the variable you've defined (file1_var1) is set to the string ${file2_var1} (which looks like a RF variable definition due to the $ and {}, but it's just a string). When the framework imports it as a variable file, it does not automatically substitute it - "you set the value to be a string, you're getting a string".
Later on, after it's imported you can substitute/replace it with the value behind ${file2_var1} - as long as that file2_var1 is defined in the current scope. That's done by calling Replace Variables which returns the substituted version (e.g. doesn't modify the original variable):
${file2_var1}= Replace Variables ${file2_var1}

Python tkinter app requires a variable that doesn't exist at the moment

At the moment, I am trying to program a python application that tracks my consumed time on different projects. I also use the following modules: Sqlite3 and tkinter.
APP-GUI
On the right side in the image you can see the list of my current example projects I would like to track. The issue I have right now is that I have to choose a project in the list in order to pass the variable to the fetch_times function that requests the corresponding times from the database. However, I need kind of a default variable that is activated before I get the chance to select a project in the list.
The code below defines at first the function to select a project in my list on the right side in the image. The other function is a loop that should print the requested data in the list on the left side.
def selected_project(event):
global selected_project
index = project_list.curselection()[0]
selected_project = project_list.get(index)
def show_times(selected_project):
for row in db.fetch_times(selected_project):
times_list.insert(END, row)
The following code is part of a second python file that contains database functions.
def fetch_times(self, selected_project):
self.cur.execute("SELECT date_day, start_time, stop_time FROM projects WHERE project_name=?",(selected_project,))
rows = self.cur.fetchall()
return rows
I already tried to generate a default selected_project variable but then I got the error message that the "function is already defined". I also thought about to implement an IF-statement that checks if the variable exists but I am just not sure what the best solution is. This is my first post here so I hope this overview describes my problem well enough.
Thank you for you help!
I got the error message that the "function is already defined"
As Cool Cloud said:
You have a function named selected_project and a variable named selected_project too. Change your function name or variable name and it will be fixed.You declared selected_project as a None but after that, you declared selected_project as a function. so selected_project is a function and it's not a value anymore, and you are trying to change your function name inside your function and it's impossible.

List object is not callable IN PYTHON

def new(l):
return l%2==0
list(filter(new,range(4,31)))
please someone resolve this. I am getting a error that list object is not callable
This one will work. Only reason it will fail because you have declared list as a variable somewhere in your code like list = ...., so the builtin type gets overwritten. If you are doing from script change the variable name using Find and Replace in Text editor, or if you are in python shell then use del list, or restart the shell but you have to re-do things (but python history file will help you to restore)

Django: "referenced before assignment" but only for some variables

I'm writing a small app in Django and I'm keeping the state saved in a few variables I declare out of the methods in views.py. Here is the important part of this file:
from app.playerlist import fullList
auc_unsold = fullList[:]
auc_teams = []
auc_in_progress = []
auc_current_turn = -1
print(auc_in_progress)
def auc_action(request):
data = json.loads(request.GET["data"])
# ...
elif data[0] == "start":
random.shuffle(auc_teams)
print(auc_unsold)
print(auc_in_progress)
auc_in_progress = [None, 0, None]
print(auc_in_progress)
The auc_unsold and auc_teams variables work fine; the auc_in_progress variable is not seen by this method, though, giving the error in the title. If I take out the print statement and let this code assign a value to it, the exception will be thrown somewhere else in the code as soon as I use that variable again.
I have tried making another variable and this new one seems to suffer from this problem as well.
What is happening?
Edit: I found a solution: if I write global auc_in_progress just before the print statements, then everything works fine. If I try writing that as I declare the variable above it doesn't work, though, for some reason.
I am unsatisfied with this, because I don't know why this happens and because I dislike using global like that, but eh. Someone has an explanation?
You should absolutely not be doing this, either your original code or your proposed solution with global.
Anything at module level will be shared across requests, not only for the current user but for all users for that process. So everyone will see the same auction, etc.
The reason for your error is because you assign to that variable within your function, which automatically makes it a local variable: see this question for more details. But the solution recommended there, which is the same as your workaround - ie use global - is not appropriate here; you should store the data somewhere specifically associated with the user, eg the session.

Python Error: local variable 'last_card' referenced before assignment

The program keeps on telling me that 'last_card' is referenced before the assignment and it is. However, how can I by pass this error. If you look at the code, last_card is referenced in the first if statement. I want to use its value from the first "IF" statement and use it in the second. How can I do that?
if region == "showCardHistory":
temp = re.search(r'Card History for Slot (A|B|\d+)(.*)',line)
if temp:
last_card = temp.group(1)
temp = re.search(r'Secs since boot\s+:\s+(\d+)',line)
if temp:
card_slot_string = re.match(r'(A|B)',line)," CPM ",last_card,":"," IOM ",last_card
Python doesn't know for sure that the 1st if clause will be called. So, in order to be safe, it will assume at compile-time that last_card hasn't yet been declared. When you reference it in your 2nd if clause, the case may happen that the 1st if clause didn't evaluate True, and then it will have an UnassignedError.

Categories

Resources