Thursday 15 January 2015

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


I realized that I have some mysterious (at least for me) the way you code the top instructions in Kivy > With Python statement. For example, the way the is used with is something like this:

  ... some code class MyWidget ... Code def some_method (self): with self.canvas: rectangle (pos = self.pos, size = self.size)   

In the beginning I thought it was just With the Python statement that I have used sometimes but suddenly I know that it is not. Usually this looks like this (taken from the example):

  with open ('output.txt', 'w') f: f.write ('Hi is!' )   

Typically, after the example as an and there is some more nickname like the object. In Kivy example we are not defined and the nickname which is still fine. But the part of the puzzle I have is that the instruction rectangle is still linked to itself. After reading about the statement with , I'm quite confident that the Kivy code should be written like this:

  class MyWidget (widget) ... some code Def some_method (self): canvas c: c.add as its own (rectangle (size = self.pos, size = self.size))   

I'm assuming that the internal form Calling method adding is based on the assumption that we can only add references to self.add (rectangle = self.pos, size = self.size) Are)

Am I about it A. I'm missing something with Python statement? Or is it any kind of Kiwi tool?

I do not know Kiwi, but I think I can guess how this specific construction work .

Rather than keeping the object that you are interacting with (canvas?), With the statement statement it is programmed to store it in some global variable After that, hidden for you, you use the statement with to use that global variable to retrieve the object. At the end of the block, the global variable is approved as part of cleaning.

The result is a trade off: the code is less clear (which is usually the desired feature in Python). However, the code is small, which can easily be understood (with the perception that how the reader knows how it works). This is actually one of the techniques to create embedded DSL in Python.

It contains some technical examples, for example, if you want to be able to create nests in such a construction (with a inserting inside each other) Instead of a global global variable, you want to use a global variable that keeps a heap of such objects. In addition, if you need to deal with threading, then you will use a thread-local variable instead of global one, but this is still the generic system. Kiwi uses some state that is kept in a place outside your direct control.

No comments:

Post a Comment