Updating a binding that is bound to object[property] (Binding.IndexerName weirdness) - python

This emerged from my related question. I currently have the following binding:
myBinding = Binding("[foo]")
myBinding.Mode = System.Windows.Data.BindingMode.TwoWay
myBinding.Source = obj
acheckbox.SetBinding(CheckBox.IsCheckedProperty, myBinding)
acheckbox.DataContext = obj
This will look at obj[foo]. The UI will update the source just fine - I can check the checkbox and obj[foo] is changed. However, the reverse is not working. Changing obj[foo] in code does not update the UI, even with this code manually calling OnPropertyChanged:
obj[foo] = False
obj._OnPropertyChanged(obj, System.ComponentModel.PropertyChangedEventArgs("[foo]"))
The problem likely lies with the arguments to OnPropertyChanged. Some digging (and help from H.B.) revealed this post:
http://10rem.net/blog/2010/03/08/wpf---silverlight-quick-tip-inotifypropertychanged-for-indexer
If you're creating the data source for
those (for example, you are building
your own ObservableDictionary), you
may wonder how on earth you fire the
appropriate
INotifyPropertyChanged.PropertyChanged
event to let the binding system know
that the item with that field name or
index has changed.
The binding system
is looking for a property named
"Item[]", defined by the constant
string Binding.IndexerName.
In other words, Binding.IndexerName is a constant, "Item[]", that tells the binding engine to rescan the whole source dictionary.
obj._OnPropertyChanged(obj, System.ComponentModel.PropertyChangedEventArgs(Binding.IndexerName))
# equivalent to:
obj._OnPropertyChanged(obj, System.ComponentModel.PropertyChangedEventArgs("Item[]"))
Unfortunately, scanning the entire source dictionary happens to be an expensive operation in my code; so that post also talks about using "Item[foo]" as the argument. This is exactly what I need - and it doesn't work! Only Item[] works. Why?

According to mamadero2 in this thread Item[index] only works in Silverlight 4.
(I never would have imagined that Silverlight supports something that WPF does not)

Related

What does 'state' mean regarding Django apps?

I'm new to django (and programming in general) and I am trying to create a Reviewboard extension.
This extension will display the fullname of the user in a column. The code works for the most part, however I don't understand what the state variable in this method does.
# renders column to display
def render_data(self, state, review_request):
# returns user's fullname (or username if fullname does not exist)
user = review_request.submitter
return user.get_full_name() or user.username
This code works, however when I remove the 'state' argument, the field shows 'None' instead of the fullname of the user. I tried looking online but I could not find an explanation for what that variable does.
I dont even call it in my method, yet it still affects the result.
I don't like having code that I don't fully understand (harder to debug), so could someone shed some light on this?
What I think it means
I think state refers to the instance of the object. In this case it would be the review_request that the fullname is being rendered for. Without this instance, one review request can't be differentiated from all of them. I still don't know how it affects the code without me even calling it.
Edit: C14L was right, I renamed state to foobar and my code still functioned properly. I dug a bit more into the source of the djblets/django code where it calls the function.
rendered_data = self.render_data(state, obj)
In the code you posted, state isn't used at all. But, if you remove it, then review_request will be the second argument. But this function is called, expecting review_request to be the third argument. You can't just change the number or order of arguments, because the callers don't know about that. Try renaming state to foobar and the function will still work as before.
You can just leave state there, that's perfectly fine. The interface of the function/method shouldn't change only because one of the arguments isn't used (anymore) inside the function or method.

Python "with" statement but no "as" [duplicate]

I just realized there is something mysterious (at least for me) in the way you can add vertex instructions in Kivy with the with Python statement. For example, the way with is used goes something like this:
... some code
class MyWidget(Widget)
... some code
def some_method (self):
with self.canvas:
Rectangle(pos=self.pos, size=self.size)
At the beginning I thought that it was just the with Python statement that I have used occasionally. But suddenly I realize it is not. Usually it looks more like this (example taken from here):
with open('output.txt', 'w') as f:
f.write('Hi there!')
There is usually an as after the instance and something like and alias to the object. In the Kivy example we don't define and alias which is still ok. But the part that puzzles me is that instruction Rectangle is still associated to the self.canvas. After reading about the with statement, I am quite convinced that the Kivy code should be written like:
class MyWidget(Widget)
... some code
def some_method (self):
with self.canvas as c:
c.add (Rectangle(pos=self.pos, size=self.size))
I am assuming that internally the method add is the one being called. The assumption is based that we can simply add the rectangles with self.add (Rectangle(pos=self.pos, size=self.size))
Am I missing something about the with Python statement? or is this somehow something Kivy implements?
I don't know Kivy, but I think I can guess how this specific construction work.
Instead of keeping a handle to the object you are interacting with (the canvas?), the with statement is programmed to store it in some global variable, hidden to you. Then, the statements you use inside with use that global variable to retrieve the object. At the end of the block, the global variable is cleared as part of cleanup.
The result is a trade-off: code is less explicit (which is usually a desired feature in Python). However, the code is shorter, which might lead to easier understanding (with the assumption that the reader knows how Kivy works). This is actually one of the techniques of making embedded DSLs in Python.
There are some technicalities involved. For example, if you want to be able to nest such constructions (put one with inside another), instead of a simple global variable you would want to use a global variable that keeps a stack of such objects. Also, if you need to deal with threading, you would use a thread-local variable instead of a global one. But the generic mechanism is still the same—Kivy uses some state which is kept in a place outside your direct control.
There is nothing extra magical with the with statement, but perhaps you are unaware of how it works?
In order for any object to be used in a with statement it must implement two methods: __enter__ and __exit__. __enter__ is called when the with block is entered, and __exit__ is called when the block is exited for any reason.
What the object does in its __enter__ method is, of course, up to it. Since I don't have the Kivy code I can only guess that its canvas.__enter__ method sets a global variable somewhere, and that Rectangle checks that global to see where it should be drawing.

Python 3.3 - Game - Hint System

I want to make it so it prints different hints dependent on where the player is in the game. I tried it by setting the value of 'Hint' every time the player went somewhere. Obviously I came across a flaw (as I'm here). The value of Hint = 1 was first in one def and I couldn't manage to summon it when writing the Help/Hint def. My pathetic example:
def Room_Choice():
Hint = 1
(60 lines down)
def Hint():
Choice = input("What would you like?\n")
if Choice == ("Hint"):
if Room_Choice(Hint = 1):
print_normal("blah blah blah\n")
else:
print_normal("HINT-ERROR!\n")
Help_Short()
And obviously as the game developed more and more values of hint would be added.
As you can see I'm relatively new to Python and need help.
You are trying to reach a value that exists in a function scope, and you're doing it wrong (as you're here).
Imagine scopes as boxes of one-way mirrors : when you're inside one, you can see what's in the box and what's outside of the box. But you can't see what's in a box you are not in.
Here, Hint exists within the box of Room_Choice, but not in the box of H... oh wait.
You've called your function Hint too ! If you want to reach Hint in a function called Hint with no Hint defined inside the function, you'll probably get the function. Let's call the function DoHint()
So you can't see Hint from within DoHint, because it's in another box. You have to put it somewhere (over the rainboooow... sorry for that) you can see it.
You might want to put it at the module level (not within a def), or make it an object's attribute (but you'll have to know bits of Oriented Object Programming to understand that).
This is really basic programming skills, I can't really explain further without knowing what you're trying to do and showing you how I would do it, but I hope that helped.
Just one more thing on this line : if Room_Choice(Hint = 1):, here you're trying to check if the result of the Room_Choice function with a value of 1 for the Hint parameter is True. I don't know what you wanted to do, but the Room_Choice function doesn't show it can handle any parameters (you should get an error on that), and will not return a boolean value (it will implicitly return None, which is evaluated as a logical False).

Is it better to assign a name to a throwaway object in Python, or not?

This is not a "why doesn't my code run" question. It is a "how / why does my code work" question. I am looking to generalize from this specific case to learn what broad rules apply to similar situations in the future.
I have done some searching (Google and StackOverflow) for this, but haven't seen anything that answers this question directly. Of course, I'm not entirely sure how best to ask this question, and may be using the wrong terms. I welcome suggested edits for the question title and labels.
I have the following function (which makes use of the requests module):
def make_session(username,password,login_url):
#The purpose of this function is to create a requests.Session object,
#update the state of the object to have all of the cookies and other
#session data necessary to act as a logged in user at a website, and
#return the session to the calling function.
new_session = requests.Session()
login_page = new_session.get(login_url)
#The function get_login_submit_page takes the previously
#created login_page, extracts the target of the login form
#submit, and returns it as a unicode string.
submit_page_URL = get_login_submit_page_URL(login_page)
payload = {u'session_name': username, u'session_password': password}
new_session.post(submit_page_URL,data=payload,allow_redirects=True)
return new_session
And what I really want to know is whether or not how I do this line matters:
new_session.post(submit_page_URL,data=payload,allow_redirects=True)
According to the requests documentation, the Session.post method returns a Response object.
However, this method also has side-effects which update the Session object. It is those side effects that I care about. I have no use for the Response object this method creates.
I have tested this code in practice, both assigning the Response to a label, and leaving it as presented above. Both options appear to work equally well for my purposes.
The actual question I am asking is: since, reasonably, whether I assign a label or not, the Requests object created by my call to Session.post falls out of scope as soon as the Session is returned to the calling function, does it matter whether I assign a label or not?
Rather, do I save any memory/processing time by not making the assignment? Do I create potential unforeseen problems for myself by not doing so?
If you are not using the return value of a call, there is little point in assigning it to a local name.
The returned response object will then not be referenced anywhere and freed two bytecodes earlier than if you assigned it to a name, and ignored that name before returning from the function.

how does `with canvas:` (Python `with something() as x:`) works implicitly in Kivy?

I just realized there is something mysterious (at least for me) in the way you can add vertex instructions in Kivy with the with Python statement. For example, the way with is used goes something like this:
... some code
class MyWidget(Widget)
... some code
def some_method (self):
with self.canvas:
Rectangle(pos=self.pos, size=self.size)
At the beginning I thought that it was just the with Python statement that I have used occasionally. But suddenly I realize it is not. Usually it looks more like this (example taken from here):
with open('output.txt', 'w') as f:
f.write('Hi there!')
There is usually an as after the instance and something like and alias to the object. In the Kivy example we don't define and alias which is still ok. But the part that puzzles me is that instruction Rectangle is still associated to the self.canvas. After reading about the with statement, I am quite convinced that the Kivy code should be written like:
class MyWidget(Widget)
... some code
def some_method (self):
with self.canvas as c:
c.add (Rectangle(pos=self.pos, size=self.size))
I am assuming that internally the method add is the one being called. The assumption is based that we can simply add the rectangles with self.add (Rectangle(pos=self.pos, size=self.size))
Am I missing something about the with Python statement? or is this somehow something Kivy implements?
I don't know Kivy, but I think I can guess how this specific construction work.
Instead of keeping a handle to the object you are interacting with (the canvas?), the with statement is programmed to store it in some global variable, hidden to you. Then, the statements you use inside with use that global variable to retrieve the object. At the end of the block, the global variable is cleared as part of cleanup.
The result is a trade-off: code is less explicit (which is usually a desired feature in Python). However, the code is shorter, which might lead to easier understanding (with the assumption that the reader knows how Kivy works). This is actually one of the techniques of making embedded DSLs in Python.
There are some technicalities involved. For example, if you want to be able to nest such constructions (put one with inside another), instead of a simple global variable you would want to use a global variable that keeps a stack of such objects. Also, if you need to deal with threading, you would use a thread-local variable instead of a global one. But the generic mechanism is still the same—Kivy uses some state which is kept in a place outside your direct control.
There is nothing extra magical with the with statement, but perhaps you are unaware of how it works?
In order for any object to be used in a with statement it must implement two methods: __enter__ and __exit__. __enter__ is called when the with block is entered, and __exit__ is called when the block is exited for any reason.
What the object does in its __enter__ method is, of course, up to it. Since I don't have the Kivy code I can only guess that its canvas.__enter__ method sets a global variable somewhere, and that Rectangle checks that global to see where it should be drawing.

Categories