While learning scopes in python, I come across the below simple code. My doubt is how can I pass the parameter to outer_var and inner_var in the function.
def outerfunc(outer_var):
def innerfunc(inner_var):
return outer_var * inner_var
return innerfunc
Basically, yeah, it's like #jonrsharpe said: it's because of closures.
Closures "close" around the state within a function that can be used later. Every time you run outerfunc(), the code will define a new version of innerfunc() that has access to outer_var that was passed in that time.
Closures are what make parameterized decorators work.
Related
I am a newbie with the tkinter library and I don't understand how to pass arguments from a combobox to a method I would like to bind on event action?
Example:
class Controller():
def __init__(self):
self.root = tk.Tk()
self.view = View(self.root)
self.view.sidepanel.motor_sel_combo.bind("<<ComboboxSelected>>", lambda event, arg=self.view.sidepanel.motor_sel_combo.get(): self.motor_selection(event, arg))
def motor_selection(self,event, mot_selected):
#print(event) #--> would only print <VirtualEvent event x=0 y=0> #????
#print(event.widget.get())
print(mot_selected)
The output for print(mot_selected) is empty. The tkinter manual does not show a good example.
self.view.sidepanel.motor_sel_combo.get() contains the imho the selected value of the combobox.
I tried as well with functools.partial instead of lambda, but I don't get it to work.
Could you show me the correct syntax with lambda and functools.partial, please?
Thank you.
You're calling self.view.sidepanel.motor_sel_combo.get() at the time you create the lambda, not at the time the combobox value has changed.
You should call the get() method inside the function instead of trying to pass it to the function. The use of lambda here does nothing but make the code unnecessarily complex.
class Controller():
def __init__(self):
self.root = tk.Tk()
self.view = View(self.root)
self.view.sidepanel.motor_sel_combo.bind("<<ComboboxSelected>>",
self.motor_selection)
def motor_selection(self,event):
mot_selected = self.view.sidepanel.motor_sel_combo.get()
...
It was pointed out in a comment by #acw1668 that the function should use event.widget.get() instead of self.view.sidepanel.motor_sel_combo.bet() and that is true. Since we want to call get() on the widget that was bound, using the shorter version is the better solution. It is better for two reasons: because it makes the function loosely coupled to the other code, and because it makes it more clear that the function is operating on the widget it was bound to. That means that the other code could rename that variable and the function will continue to work without having to also be modified.
For such a small program, whether the function is loosely coupled or tightly coupled isn't that big of a deal. I would argue, though, that using event.widget in a callback is a best practice that one should get in the habit of doing.
The OP indicated in comments they want to see a version that uses lambda. I don't recommend it, but the root of the problem with lambda is that the OP was calling the get() method when defining the lambda rather than when it is called. To call the get() method when the lambda runs, the call must be moved inside the body:
self.view.sidepanel.motor_sel_combo.bind(
"<<ComboboxSelected>>",
lambda event: self.motor_selection(event, self.view.sidepanel.motor_sel_combo.get())
)
In this case, motor_selection must be like in the OP's original code and accept two parameters.
I am aware that a variable can be dynamically typed with the def keyword in Groovy. But I have also noticed that in some circumstances it can be left out, such as when defining method parameters, eg func(p1, p2) instead of func(def p1, def p2). The latter form is discouraged.
I have noticed that this is extendable to all code - anytime you want to define a variable and set its value, eg var = 2 the def keyword can be safely left out. It only appears to be required if not instantiating the variable on creation, ie. def var1 so that it can be instantiated as a NullObject.
Is this the only time def is useful? Can it be safely left out in all other declarations, for example, of classes and methods?
Short answer: you can't. There are some use cases where skipping the type declaration (or def keyword) works, but it is not a general rule. For instance, Groovy scripts allow you to use variables without specific type declaration, e.g.
x = 10
However, it works because groovy.lang.Script class implements getProperty and setProperty methods that get triggered when you access a missing property. In this case, such a variable is promoted to be a global binding, not a local variable. If you try to do the same on any other class that does not implement those methods, you will end up getting groovy.lang.MissingPropertyException.
Skipping types in a method declaration is supported, both in dynamically compiled and statically compiled Groovy. But is it useful? It depends. In most cases, it's much better to declare the type for a better readability and documentation purpose. I would not recommend doing it in the public API - the user of your API will see Object type, while you may expect some specific type. It shows that this may work if your intention is to receive any object, no matter what is its specific type. (E.g. a method like dump(obj) could work like that.)
And last but not least, there is a way to skip type declaration in any context. You can use a final keyword for that.
class Foo {
final id = 1
void bar(final name) {
final greet = "Hello, "
println greet + name + "!"
}
}
This way you can get a code that compiles with dynamic compilation, as well as with static compilation enabled. Of course, using final keyword prevents you from re-assigning the variable, but for the compiler, this is enough information to infer the proper type.
For more information, you can check a similar question that was asked on SO some time ago: Groovy: "def" keyword vs concrete type
in Groovy it plays an important role in Global and Local variable
if the variable name is same with and without def
def is considered local and without def its global
I have explained here in detail https://stackoverflow.com/a/45994227/2986279
So if someone use with and without it will make a difference and can change things.
I am trying to create a Node module (using harmony) that upon loading by another module/application, has to be yielded to so that things in it's construct can be executed and loaded before any of it's exposed functions can be called.
The issue I am having is that I cannot seem to yield to the internal function that is being executed, using module.exports. An example would help.
module.exports = function*(s_id){
console.log('loading the module lets it execute up till here');
if (!(this instanceof Tester)) return yield new Tester();
}
function* Tester(){
console.log('but we never execute this generator function');
}
Tester.prototype = {
model : function*(){
// other functions
}
}
It's been stumping me for hours now! I feel like the solution is super simple but I cannot seem to wrap my head around it. I have tried to simply make the Tester() function the export, but am still having the same issue. Why can't I seem to yield to the Tester() function?
Also, what may an alternative be to this approach? I want to maintain the Object nature of the module so that the module can be loaded with different inputs, such as the s_id variable/object in the example above.
a Node module (using harmony) that upon loading by another module/application, has to be yielded to so that things in it's construct can be executed and loaded before any of it's exposed functions can be called
Don't do that. Generators are not made for asynchrony. yield doesn't do what you want here. A module is not "yielded" to await something in it to load. yield is magic, but not async magic.
If you must use an asynchronous module loading process, export a promise for your actual module. That is a standard interface for something to await, and can be consumed using a standardized approach that does not rely on internals of your module.
You still can use yield syntax for constructing that promise, just use your favorite coroutine library.
return yield new Tester();
…
function* Tester(){…}
Uh oh. Well yes, apparently it is possible to call generator functions as constructors. But believe me, it is not what you want. A constructor for an arbitrary object should return that object, instead of an iterator (just like it shouldn't return a promise). If some of your object methods are generator methods, that's fine, but your constructor should be not.
If you really want to use a generator function in your code like that (and it's not meant to be a constructor), you
will need to yield* the iterator you've created (tester()) instead of yielding it
must not overwrite its .prototype property like you did, as that causes the iterator to malfunction. (Of course you should never do that at all, even though most of the time it works)
I'm not even sure about how to title this qn. But, hope there is an easy way to do it in dynamic language like groovy.
say I have a class Service, where I delegate the business logic. the methods in it are
funA(), funB()... funX().
Now I have a controller class, where I call the service closure, which can be invoked like service.funA() . Now based on a variable (which can have values A, B ... X), I need to cal the correct service closure. Basically to avoid writing lot of if conditional statements. Something like service."fun+var"() would do. I'm not sure whether it is possible to substitute variable in closure (function)name. or any way by passing function (name) as a parameter...not sure
I think PHP has a similar feature http://php.net/manual/en/functions.variable-functions.php
thanks for any pointer..
Yes, this is possible. This should do what you want:
service."fun${var}"()
The correct title is dynamic method invocation.
The following example is adapted from 'Groovy in Action'
class Mother {
Closure birth() {
def closure = { caller ->
[this, caller]
}
return closure
}
}
Mother julia = new Mother()
closure = julia.birth()
context = closure.call(this)
println context[0].class.name // Will print the name of the Script class
assert context[1] instanceof Script
According to the book, the value of this inside the closure is the outermost scope (i.e. the scope in which julia is declared). Am I right in assuming that
this inside a closure evaluates to the scope in which the closure is called?
within the closure shown above, this and caller refer to the same scope?
Thanks,
Don
"this" in a block mean in Groovy always (be it a normal Java-like block or a Closure) the surrounding class (instance). "owner" is a property of the Closure and points to the embedding object, which is either a class (instance), and then then same as "this", or another Closure. I would forget about the scope thing totally for this part. So in the case above it is correct, that "this" refers to a mother.
And now to make things complicated... "this" and the implicit this are not the same in Groovy. So if you have a Closure {foo()} and {this.foo()} you can get differing results. this.foo() will always be resolved to the embedding class, while only foo() will be resolved using the Groovy meta object protocol (MOP) and can point to something entirely different. A builder may for example set a delegate on that Closure and catch the method invocation, for a Groovy builder that is standard. Anyway... that is why this part is called dynamic scoping.
Historic background:
Before Groovy 1.0 "this" was the Closure object itself. But was changed because actually calling this.foo() became impossible if a builder did capture all calls. then you had no way to call local methods from within the builder anymore. There was a lot of tries with changing the standard resolve strategy - and big emotional discussions too. But in the end, changing "this" to refer to the embedding class was a simple solution to the problem and is more in line with people coming from Java plus it let's you easily bypass the MOP if you insist.
Take a look at page 144
...this refers to the closure, not to
the declaring object. At this point,
closures play a trick for us. They
delegate all method calls to a
so-called delegate object, which by
default happends to be the declaring
object (that is, the owner). This make
the closure appear as if the enclosed
code runs in the birthday context.
For your questions;
this inside a closure evaluates to the scope in which the closure is called?
from the book they state that "this refer to the closure, not to the declaring object"
But from bertport and my experiment, it seems "this" is actually the declaring object.
Either ways, the answer is still "no" for your question.
within the closure shown above, this and caller refer to the same scope?
I'm afraid not.
Be aware that page 143 and 144 in Groovy in Action need some corrections
http://groovy.canoo.com/errata/erratum/show/5
http://groovy.canoo.com/errata/erratum/show/8
{
def self = ({ owner })()
}
owner: the enclosing object (this or a surrounding Closure).
Sake says, "this is the closure not the object where the closure [is] constructed." But when we run this script, we find that this is a Mother, not a Closure.