Call a function defined in another function - python

Can I call a function nested inside another function from the global scope in python3.2?
def func1():
def func2():
print("Hello")
return
return
Is ther a way to call func2() from outside func1()?

No, unless you return the function:
def func1():
def func2():
print("Hello")
return func2
innerfunc = func1()
innerfunc()
or even
func1()()

You want to use #larsmans' solution, but theoretically you can cut yourself into the code object of the locally accessible func1 and slice out the code object of func2 and execute that:
#!/usr/bin/env python
def func1():
def func2():
print("Hello")
# => co_consts is a tuple containing the literals used by the bytecode
print(func1.__code__.co_consts)
# => (None, <code object func2 at 0x100430c60, file "/tmp/8457669.py", line 4>)
exec(func1.__code__.co_consts[1])
# => prints 'Hello'
But again, this is nothing for production code.
Note: For a Python 2 version replace __code__ with func_code (and import the print_function from the __future__).
Some further reading:
http://web.archive.org/web/20081122090534/http://pyref.infogami.com/type-code
http://docs.python.org/reference/simple_stmts.html#exec
http://lucumr.pocoo.org/2011/2/1/exec-in-python/

This is based on eyquem's solution.
def func1():
global func2 # put it in global scope
def func2():
print("Hello")
Now you can invoke func2 directly.
But func1() would have to be called before you can call func2() otherwise it will not have been defined yet.

def func1():
def func2():
global fudu
fudu = func2
print("Hello")
func2()
func1()
fudu()
print 'fudu' in dir()
print 'func2' in dir()
result
Hello
Hello
True
False
Also:
def func1():
global func2
def func2():
print("Hello")
func2()
func1()
print 'func2' in dir()
func2()
result
Hello
True
Hello
What's the interest?

Related

Global variables in imported modules python

When global variables are all on one script, things work smoothly.
def foo():
global x
x = 'bar'
goo()
def goo()
global x
print(x)
foo()
would print bar as expected.
However, it does not work when I have to import goo from another file, for example
file1.py
from file2 import goo
def foo():
global x
x = 'bar'
goo()
foo()
file2.py
def goo()
global x
print(x)
results in NameError. How can x be passed to the imported function like in the first case without passing it explicitly as an argument?
you have to set <module_name>.<variable_name> = 'bar' for it to work like so:
import file2
def foo():
file2.x = 'bar'
file2.goo()
foo()
file1 is the same

How do I Create a global class variable in Python

I want to use a class in Python to simulate a 'struct' in C++. Also, I need it in global form as I am using it in many functions and I do not want to pass parameters.
How do I do this(create global objects of a class).
My attempt was :
class MyClass():
//Class Constuctor
global ob1 = Myclass()
def func1():
ob1.name = "Hello World"
def func2():
print(ob1.name)
func1()
func2()
This gives me an 'Invalid Syntax' error, how did I go wrong, or is there a more efficient method to do this?
Note that I have like 10 values, so the class is going to be a pain anyway.
In your code it is not necessary to explicitly place the global modifier, this variable is global by default.
class MyClass():
def __init__(self):
self.name = ""
ob1 = MyClass()
def func1():
ob1.name = "Hello World"
def func2():
print(ob1.name)
func1()
func2()
Output:
Hello World
In addition the use of global is as follows:
global variable
variable = your_value

A per-activation "global" variable in Python?

This might seem like a rather weird thing to do, but I was curious if it was possible to implicitly pass a variable down a call chain in Python without passing it as an argument. To better illustrate here is an example:
Here is the "normal" way:
def three(something):
print(something)
def two(something):
# ...
three(something)
def one(something):
# ...
two(something)
And here is what I want to be able to do:
def three():
# something is defined implicitly
print(something)
def two():
# ...
three()
def one(something):
# somehow define something inside a context
# for this activation
two()
For the purpose of this, one, two and three are not in the same class or even the same module.
You don't want to do this.
If you are really convinced that you want to torture yourself, then you could create a separate thread and run the call to one() in that thread. Then just use threading.local for the shared state.
You really don't want to do this.
Here's how you can use thread local storage:
import threading
state = threading.local()
def three():
# something is defined implicitly
print(state.something)
def two():
# ...
three()
def one(something):
# somehow define something inside a context
# for this activation
def inner():
state.something = something
two()
t = threading.Thread(target=inner)
t.start()
t.join()
if __name__=='__main__':
one(42)
one(24)
If you must, you can assign values to the function object itself. Ideally, both three() and two() would perform checks that would raise better exceptions than an AttributeError if 'something' is not set correctly.
def three():
print(three.something)
def two():
three.something = two.something
three()
def one(something):
two.something = something
two()
You could take advantage of lexical closures - define two() and three() within the definition of one().
>>> def one(something):
... def two():
... three()
... def three():
... print something
... two()
...
>>> one(1)
1
You can use __builtins__ to hold your "global variables".
>>> __builtins__.something = "Hello world!"
>>> def foo():
print something
>>> foo()
Hello world!
This can help you avoid passing variables explicitly.
This is a terrible hack. IMHO, you really don't need to do that.

Calling a function within a closure in python

I'm trying to do something like this:
import threading
def func1(a,b):
def func2():
t=threading.Thread(target=func3)
return t
return func2
func2=func1(a,b)
func2()
I have a restriction(the language I'm using is python with some restricted functions) not to use the args parameter for the Thread function instead I want to pass a and b as parameters to func3. How can I do this using closures?
You can use a lambda:
t=threading.Thread(target=lambda: func3(a,b))
The values of a and b will be held in a closure, even after func1 exits.
Instead of a lambda, you can create a named function:
def thread_func():
func3(a,b)
t = threading.Thread(target=thread_func)
In the absence of lambda I might look into functools.partial. If that isn't allowed, you could probably do:
import threading
def func1(a,b):
def func2():
def func4():
return func3(a,b)
return threading.Thread(target=func4)
return func2
func2=func1(a,b)
func2()

Learning Python: print variable inside a function from another function

I want to do the following in python:
def func1():
var1 = "something"
def func2():
print var1
What is the correct mode to do this ? I've not found in documentation at all
PS. If possible, it's not my plan to make that 'var1' a global variable.
Thanks.
I assume you don't want to pass the variable as a parameter between the function calls. The normal way to share state between functions would be to define a class. It may be overkill for your particular problem, but it lets you have shared state and keep it under control:
class C:
def func1(self):
self.var1 = "something"
def func2(self):
print self.var1
foo = C()
foo.func1()
foo.func2()
No, it is not possible to do things like that. This is because of something called "scope". You can either create a module-level variable or place it in an OOP construct.
Well your func2() is trying to print a variable in the scope of another function. You can either
Return the value of var1 when calling func1 (eg. def func2(): print func1() }
Call func2 from func1 and pass the value of var1
You could try something like
def func1():
var1 = "something"
return var1
def func2():
print func1()
If you need func1 to do more things than just define var1, then maybe what you need is to define a class and create objects? See http://docs.python.org/tutorial/classes.html
You could try:
filename.py:
def func1():
var1 = "something"
def func2():
var = __ import__('filename').var1
print var

Categories