def board_topics(request,id):
try:
x=Board.objects.get(pk=id)
except x.DoesNotExist:
raise Http404
why x cannot be seen in the except ? and why it works why i put
def board_topics(request,id):
try:
x=Board.objects.get(pk=id)
except Board.DoesNotExist:
raise Http404
why when i put Board.doesnotexist it works??!! i mean Boards are in object x and logically i can put x instead of Boards in except block
In the statement:
“x” is not an object here. x is not a “Board”, because the assignment statement failed to complete, because the get failed, which caused the exception.
okay a question please is X IN the TRY block an object? its for sure an object right ? but i dont’t get why in except won’t be an object?
i mean if the id exist and everything right in the try block it reads x as an object right?
First, let’s be precise here in Python terms. The symbol “x” is never an object. If an assignment statement executes, “x” is a reference to an object. If no assignment statement executes, then “x” is undefined.
There are some languages where you might define “x” as being an instance of an object, such as Java. Python is more dynamic that that. Variable names are assigned to whatever objects you wish, and are created and deleted at-will. The variable “x” in Python has no meaning until it is assigned.
So, the answer to your question is that “x” is a reference to an object only if the query works.
If the query fails, the assignment statement does not complete - no object is assigned to “x”, and so “x” remains None.
Ask yourself this question - if the query fails, what instance of “Board” is “x” assigned to? (Answer: None, there isn’t one.)
1 Like
Thanks got the logic… is there any way to assign a variable directly as an object to a class in python so it a make algorithms easier in future ?
I’m sorry, I’m not understanding what you’re asking for.
What specifically you do think would “make algorithms easier”? Can you explain in more detail what it is you’re trying to do, that you think Python is inhibiting?
(I switched from other languages to Python precisely because of how it’s architected, and how its flexibility generally makes algorithms easier.)