tkinter command to call function from another Python script - function

I am having a few issues, calling Python functions defined in another script using tkinter. I would prefer to have a separate script for my functions that the GUI uses when needed. At the moment I am doing it like this.
ttk.Button(mainframe, text="1", command=one).grid(column=1, row=1, sticky=NW)
def one():
code_entry.insert(END,"1")
The above calls the command one on a button click, which will print the character one in a entry field with the GUI. I thought I could create a separate script to hold my functions and call them like this:
ttk.Button(mainframe, text="1", command=functions.one()).grid(column=1, row=1, sticky=NW)
And then simply add an import statement at the top of my GUI, like below:
import functions
This doesn't work and looking for some advice on how to approach this.

You didn't specify any error messages, but it's most likely that you're doing fuctions.one() - actually calling the one() function of that module before the Button is created. It's simply fixed by removing the () part - when you specify a function without (), you are passing a reference of the function object.
Also keep in mind the scope of the code_entry variable - if you were using it as a module level global before (or function local, if one() was inside the same function as your ttk.Button call), it won't be available when you move it to a new namespace without code_entry.
To solve this you should pass code_entry as a parameter to the callback without calling one() at first. The usual approach for this is creating a lambda - essentially creating a function that works on the same scope of the original one(), having access to variables like code_entry, but also calling a function in a different module.
ttk.Button(mainframe, text="1", command=lambda: functions.one(code_entry))
Note that this is basically the same as:
def some_anonymous_function():
functions.one(code_entry)
ttk.Button(mainframe, text="1", command=some_anonymous_function)
Both examples create a function object and pass that object as reference - the functions.one() call of the lambda is actually inside the body of the lambda function, to be called later by tkinter.
Of course you also have to redefine one() to accept this new parameter:
def one(code_entry):
code_entry.insert(END,"1")

Related

How to pass a function AND its parameters into another function

My use case is this: a function called 'time' that will return how long it takes to run any function you give it.
So the time function needs to know all the parameters to pass into the function when it calls it.
I know how to pass a function into another function, but how can I pass all its parameters, without knowing in advance how many and what type they are, so they can be used when calling the function?
For example, if I pass in an array of all the parameters I need to send, is there some Dart way to call a function by expanding an array into a list of parameters? Or perhaps there's another way to capture and pass a function call, including all parameters, as one executable object?
I'm also interested in knowing if there's a more Dartful way to accomplish what I'm trying to do re: timing function calls.
I believe using a List of parameters with the apply method is the most common way and practical of doing this and I have seen something similar used to pass parameters for JS interop. As far as I know, there isn't a way to expand an array into a list of parameters like you can for javascript. You could of course create your own object to pass arguments, but I think it would add unnecessary complexity and end up being more difficult.
Example of passing parameters to function in dart:js here.

Call a function that is not on the Matlab path WITHOUT ADDING THAT PATH

I have been searching an entire afternoon and have found no solution to call in matlab a function by specifying its path and not adding its directory to the path.
This question is quite similar to Is it possible to call a function that is not in the path in MATLAB?, but in my case, I do not want to call a built-in function, but just a normal function as defined in an m-file.
I think handles might be a solution (because apparently they can refer to functions not on the path), but I again found no way to create a handle without cd-ing to the directory, creating it there and the cd-ing back. Trying to 'explore' what a function handle object is and how to make one with a reference to a specific function not on the path has led me nowhere.
So the solution might come from two angles:
1) You know how to create a handle for an m-file in a specific directory.
2) You know a way to call a function not on the matlab path.
EDIT: I have just discovered the function functions(myhandle) which actually lets you see the filepath to which the handle is referring. But still no way to modify it though...
This is doable, but requires a bit of parsing, and a call to evalin.
I added (many years ago!) a function to the MATLAB Central File Exchange called externalFcn
http://www.mathworks.com/matlabcentral/fileexchange/4361-externalfcn
that manages calls to off-path functions. For instance, I have a function called offpathFcn that simply returns a structure with a success message, and the value of an input. Storing that function off my MATLAB path, I can call it using:
externalfcn('out = C:\MFILES_OffPath\offpathFcn(''this is a test'')');
This returns:
out =
success: 1
input: 'this is a test'
(Note that my implementation is limited, and improvable; you have to include an output with an equal sign for this to work. But it should show you how to achieve what you want.)
(MathWorks application engineer)
The solution as noted in the comment 1 to create a function handle before calling the function is nicely implemented by #Rody Oldenhuis' FEX Contribution:
http://www.mathworks.com/matlabcentral/fileexchange/45941-constructor-for-functionhandles
function [varargout]=funeval(fun,varargin)
% INPUT:
% fun: (char) full path to function file
curdir=cd;
[fundir,funname]=fileparts(fun);
cd(fundir);
[varargout{1:nargout}] =feval(funname,varargin{:})
cd(curdir);
I've modified Thierry Dalon's code to avoid the use of feval, which I always feel uncomfortable with. Note this still doesn't get around cd-ing to the directory in question, but well, it happens behind the scenes, so pretend it doesn't happen :-)
Also note what Ben Voigt pointed out above: calls to helper functions off the path will fail.
function [varargout]=funeval(FunctionHandle, FunctionPath, varargin)
% INPUT:
% FunctionHandle: handle to the function to be called; eg #MyFunction
% FunctionPath: the path to that function
% varargin: the arguments to be passed to Myfunction
curdir=cd;
cd(FunctionPath)
[varargout{1:nargout}] = FunctionHandle(varargin{:});
cd(curdir);
end
and calling it would look like
Output = funeval(#MyFunction, 'c:\SomeDirOffMatlabsPath\', InputArgToMyFunc)
The run command can run a script file from any directory, but it can't call a function (with input and output arguments).
Neither feval nor str2func permit directory information in the function string.
I suggest writing your own wrapper for str2func that:
saves the working directory
changes directory to the script directory
creates a function handle
restores the original working directory
Beware, however, that a handle to a function not in the path is likely to break, because the function will be unable to invoke any helper code stored in other files in its directory.

Function calling variable output number

I've found myself trying to interface a custom class with builtin functions, and I've encoutered a situation I could only solve with eval, I'd like a "cleaner" way.
Basically, the builtin function is defined as varargout=blabla(varargin)
I defined an overriden function in the custom class, as varargout=blabla(varargin). The function looks like:
function varargout=blabla(varargin)
varargout=blabla(function_of_varargin)
end
The function of varargin transforms it from the custom class to the builtin clas.
But it doesn't work as-is: Basically when the builtin function is called inside the overriden function, it sees only one output parameter (varargout), even if the custom overriden function is called with more than one output parameter.
I solved it by basically calling this :
[varargout{1},varargout{2},...,varargout{nargout}]=blabla(function_of_varargin)
Constructing the LHS with a loop and eval-ing.
Have you tried this:
[varargout{1:nargout}] = blabla(varargin{:})
?

View nested private function definitions in PowerShell

PowerShell provides a simple technique to view the contents of a function, e.g.
Get-Content function:MyFuncName # (A)
or equivalently
(Get-ChildItem function:MyFuncName).definition # (B)
where MyFuncName is the name of my function. That is great for simple functions (i.e. functions that use only base language constructs and do not call other functions). But consider the function foo shown below that contains a call to the function bar. In a typical scenario these would both be contained in the same module whose public API consists solely of the function foo and thus it is the only function exported.
function foo ()
{
$p = bar "here"
"result is '$p'"
}
function bar ([string] $s)
{
$s + $s
}
Export-ModuleMember foo
Is there any way to view the nested, non-exported functions (like function bar) within another function in a fashion comparable to (A) or (B) above? (That is, without opening the .psm1 file in an editor :-)
I'm not sure if you can do it for a particular function in a module but you can do it for the whole module:
Import-Module C:\Test.psm1
(Get-Module Test).Definition
I think the fact that function foo calls function bar is not known until runtime.
Update
Where there's a will, there's a way :-) Here's how you can access private module members. Invoke the module with a scriptblock. Inside the scriptblock the private members are visible.
Import-Module C:\Test.psm1
$module = Get-Module Test
& $module { (get-item function:bar).Definition }
Thanks to PowerTips :-) http://powershell.com/cs/blogs/tips/archive/2009/09/18/accessing-hidden-module-members.aspx
Update 2
After finding the little PowerTip snippet I was kinda curious what was really going on... The snippet uses the call operator & with two arguments.
The module object (System.Management.Automation.PSModuleInfo)
A script block
So what's really going on is the Invoke method of the PSModuleInfo type is being called. The code in the script block runs within the same session state as the rest of the module code so it has access to the private members. This code does the exact same thing as the PowerTip snippet:
$module = Get-Module Test
$module.Invoke( { (get-item function:bar).Definition } )
Check out the invoke method here: http://msdn.microsoft.com/en-us/library/system.management.automation.psmoduleinfo.invoke(v=vs.85).aspx
No. The method you're using is getting the definition of the function via the function provider in the local scope. It will only see functions that have been defined in the local scope or that are visible in parent scopes.
When you call a function, it runs in it's own scope. Any functions the function creates will be created in that child scope, and only exist during the time that function is running. When the function is done, the scope it was running it gets disposed of, and all the functions it created go with it.

Accessing the Body of a Function with Lua

I'm going back to the basics here but in Lua, you can define a table like so:
myTable = {}
myTable [1] = 12
Printing the table reference itself brings back a pointer to it. To access its elements you need to specify an index (i.e. exactly like you would an array)
print(myTable ) --prints pointer
print(myTable[1]) --prints 12
Now functions are a different story. You can define and print a function like so:
myFunc = function() local x = 14 end --Defined function
print(myFunc) --Printed pointer to function
Is there a way to access the body of a defined function. I am trying to put together a small code visualizer and would like to 'seed' a given function with special functions/variables to allow a visualizer to 'hook' itself into the code, I would need to be able to redefine the function either from a variable or a string.
There is no way to get access to body source code of given function in plain Lua. Source code is thrown away after compilation to byte-code.
Note BTW that function may be defined in run-time with loadstring-like facility.
Partial solutions are possible — depending on what you actually want to achieve.
You may get source code position from the debug library — if debug library is enabled and debug symbols are not stripped from the bytecode. After that you may load actual source file and extract code from there.
You may decorate functions you're interested in manually with required metadata. Note that functions in Lua are valid table keys, so you may create a function-to-metadata table. You would want to make this table weak-keyed, so it would not prevent functions from being collected by GC.
If you would need a solution for analyzing Lua code, take a look at Metalua.
Check out Lua Introspective Facilities in the debugging library.
The main introspective function in the
debug library is the debug.getinfo
function. Its first parameter may be a
function or a stack level. When you
call debug.getinfo(foo) for some
function foo, you get a table with
some data about that function. The
table may have the following fields:
The field you would want is func I think.
Using the debug library is your only bet. Using that, you can get either the string (if the function is defined in a chunk that was loaded with 'loadstring') or the name of the file in which the function was defined; together with the line-numbers at which the function definition starts and ends. See the documentation.
Here at my current job we have patched Lua so that it even gives you the column numbers for the start and end of the function, so you can get the function source using that. The patch is not very difficult to reproduce, but I don't think I'll be allowed to post it here :-(
You could accomplish this by creating an environment for each function (see setfenv) and using global (versus local) variables. Variables created in the function would then appear in the environment table after the function is executed.
env = {}
myFunc = function() x = 14 end
setfenv(myFunc, env)
myFunc()
print(myFunc) -- prints pointer
print(env.x) -- prints 14
Alternatively, you could make use of the Debug Library:
> myFunc = function() local x = 14 ; debug.debug() end
> myFunc()
> lua_debug> _, x = debug.getlocal(3, 1)
> lua_debug> print(x) -- prints 14
It would probably be more useful to you to retrieve the local variables with a hook function instead of explicitly entering debug mode (i.e. adding the debug.debug() call)
There is also a Debug Interface in the Lua C API.