Python call inner function - python

I have the following problem:
I have a function that holds another function inside (see code bellow). I need to call the function getFastaEntry with a parameter filename set in the top level function.I tried to call it with generate_fasta_reader(filename).getFastaEntry(), but I get the error message "function object has no attribute getFastaEntry()". Can anybody tell me how I can call the inner function?
def generate_fasta_reader(filename, gzipped=False, strip=True):
def getFastaEntry():
filehandle = None

You must return the inner function. It's not accessible otherwise and in fact ceases to exist as soon as the function ends, because there are no references to it at that point. The parameters of the outer function are available to the inner function via a closure. (I assume your actual getFastaEntry() function actually does something besides assign a local variable that goes out of scope almost immediately.)
def generate_fasta_reader(filename, gzipped=False, strip=True):
def getFastaEntry():
filehandle = None
return getFastaEntry
Calling:
getter = generate_fasta_reader("foo.txt")
getter()
Or in one step (if you only need it call the inner function once per outer function call):
generate_fasta_reader("foo.txt")()

Related

use of function , in python decorator

can someone explain how this code is working?
I mean I didn't execute the inner() function after I defined it.
So how was it executed?
I mean I did execute the hi() function, but how does it translate to the inner() function being executed?
def outer(msg):
text = msg
def inner():
print(text)
return inner
hi = outer('hi')
hi()
Your outer function returns inner. Hence hi = inner, and when you call hi() you're calling inner().
You have to realise that functions often have a return at the end. In this case your outer() function has: return inner which is the inner function defined there.
Also you must know that when you call a function which has a return, you can get hold of what is returned by assigning a variable to take that value.
Your code does this also with: hi = outer('hi'). Now your hi variable holds the reference to inner, which being a function can be called.
Your code does this also with: hi() which invokes inner() which executes and calls print(text).
The function outer is basically building a new function called inner (with a proloaded text message), and returning its handle. This construction is sometimes called "factory", because you are creating a new function with pre-loaded arguments.
The code is perfectly functional. However, it's usually considered better to define a class initialized with all the desired parameters, such as text. This helps others to understand the code better, and it looks more professional.
PS. Beware that factory functions, such as outer->inner, can easily introduce bugs. For example, consider this code:
def outer(msg):
text = msg
def inner():
print(text)
text = 'bug'
return inner
hi = outer('hi')
hi()
# prints "bug"
The meaning of text was changed after the function inner was created, but it was still affected. This is because the variable text is read from the dictionary of variables defined for the parent function (outer) at runtime. Thus, in complex applications, it can be stressing to ensure that a function such as inner is working properly.

Calling variables in Python (local vs global)

The below works and gives 8:
def mypow(a,b):
c=a**b
print (c)
mypow(2,3)
But the below doesn't:
def mypow(a,b):
c=a**b
mypow(2,3)
I understand that in the former we print but since the latter doesn't give an error message (nor does it give a result), what is actually happening in the latter?
in
def mypow(a,b):
c=a**b
mypow(2,3)
after function executed; all data inside the function destroy. if you want to see anything on your screen after function is executed; either use print or return.
In the end of any function you have multiple choices.
1- return. return the output. when you return the output you receive it after function executed without error eg: d = func(any_value), if you specified the return value in func you will receive it and store it in d. if you don't specify the return statement in the function the function will return None.
2- print. print anything. this is what you did in your first function. in this case you get printed stuff in your screen, and you function return None, so you can't hold the output (a printed value) in any variable or use it anywhere else.
3- global. assign to global. when you need this option you create a variable outside of your function say my_variale=5, and in the first line of your function you write gloabl my_variable. say the function contain 5 lines, in line #3 you did my_variable=7. after function is executed and destroyed all values within the function; when you check my_variable you will see it contains value of 5.
You can replace print with return for your function and get the same result
def mypow(a,b):
c=a**b
return c
mypow(2,3)
Variables nested in functions are treated as local variables unless you add global before the variable name.

Why is there no error when the returned function is not being assigned?

I'm learning the concept of first class functions in Python (using Python 3.6.8) and couldn't figure out why code below doesn't show any errors.
def outer_fn(msg):
def inner_fn():
print(msg)
return inner_fn
outer_fn("text")
Because it's a perfectly fine thing to do.
Sometimes you call a function for its side effects (it prints something, saves something to a database, changes some variable) and aren't interested in the return value. Python does not tell you to do anything with the return value, it just calls the function for you.
It's not showing an error because your code doesnt have any errors,you need to call your inner function like:
outer = outer_fn("text")
outer() # call inner_fn
full code:
def outer_fn(msg): #outer function
def inner_fn(): #inner function
print(msg) #able to acces the variable of outer function
return inner_fn
outer = outer_fn("text")
outer() # call inner_fn
output:
text

How do I pass a variable to createfunc in Beaker

In the Beaker documentation, they talk about not passing a parameter directly in the createfunc call but use a closure.
The creation function must not accept any arguments as it won’t be called with any. Options affecting the created value can be passed in by using closure scope on the creation function:
All examples and documentation I can find on closure hint toward a nested function call with the first taking in a variable. In this case I don't understand how to write the closure since its not a function but a key value variable.
results = tmpl_cache.get(key=search_param, createfunc=get_results)
How would I pass variable_a into get_results(variable_a) in the createfunc?
Like so, or similar?
get_results_func returns a function pointer that, because it's in a closure, will call get_results correctly.
def get_results_func(variable_a):
def call_get_results():
return get_results(variable_a)
return call_get_results # note the absence of brackets here.
results = tmpl_cache.get(key=search_param, createfunc=get_results_func(variable_a))

In python, when you pass internally defined functions into other functions, how does it keep the variables?

For example, why does this work?
def func1(func1var):
def innerfunc(innerfuncvar):
if func1var == 1:
print innerfuncvar
else:
print 5
func2(innerfunc)
def func2(function):
function(9)
When innerfunc is called in func2, how does it know the values of func1var?
You've created a closure. Basically, think of it like this, from the point of view of the inner function:
func1var = whatever
def func2(function):
function(9)
def innerfunc(innerfuncvar):
if func1var = 1:
print innerfuncvar
else:
print 5
func2(innerfunc)
It doesn't care whether func1var is in an outer or global scope -- it just looks for it in each scope outward, starting with it's own local scope. It's just like when you reference a module global variable from inside a class or function in that module.
Python actually goes to some lengths to do this for you. When you define a function inside a function, you may use variables from the outer function in the inner function. This is true for any depth of nesting (that is, you can have a function inside a function inside a function inside a function... to any depth... and the innermost function can use variables from any of the enclosing functions). If there are conflicting names, the innermost variable with the name requested is used.
What's more, Python actually captures any variables you use from the outer function and stores them in the inner function, which is called a closure. So you can not only pass a function to another function, as you are doing, but you can return a function from a function, and variables you use from the outer function that were in effect when the function was defined will still be accessible from the returned function, even though the outer function isn't running any more. This is a fairly advanced feature, but it lets you do something like this:
def make_adder(increment):
def adder(number):
return number + increment
adder.__name__ = "adder(%s)" % increment
return adder
This function is a function that creates a function that adds the specified value to it. For example:
add1 = make_adder(1)
add5 = make_adder(5)
print add1(10) # 11
print add5(10) # 15
In this case, the value you pass to make_adder is captured and stored in the function that gets returned. This allows you to create a bunch of functions that add any number to their arguments. Which is a trivial example that isn't actually very useful in real life, but serves to illustrate the feature.
Each time you call func1(func1var), Python actually builds a new function innerfunc(). Since func1var is perfectly defined when innerfunc() is created, the code of the new innerfunc() function contains the correct value of func1var.

Categories