Reputation: 287
I am trying to write a function that can define functions.
I tried this:
def function_writer():
print "I am a function writer"
def new_function():
print "I am a new function"
pass
pass
function_writer()
new_function()
However, my debugger complains that new_function is not defined and so this obviously is not the way to do it.
Does anyone know how to do this?
Thanks.
Upvotes: 1
Views: 4779
Reputation: 113940
def function_writer():
print "I am a function writer"
def new_function():
print "I am a new function"
return new_function
fn_dynamic = function_writer()
fn_dynamic() #call new_function
maybe what you are looking for? (this is almost what decorators do ... except they modify a passed in method)
another solution (this is not a good suggestion but answers the question)
def function_writer():
print "I am a function writer"
def new_function():
print "I am a new function"
globals()['new_function'] = new_function
function_writer()
new_function()
this type of functionality is typically avoided in python unless you have a VERY COMPELLING reason why this is absolutely what you need ...
Upvotes: 3
Reputation: 3056
If you want to create a function factory, just return the created function!
def factory():
def new_func():
print 'Hello!'
return new_func
f = factory()
f()
Upvotes: 1
Reputation: 279225
Your code fails for for exactly the same reason that the following code complains that i
is not defined:
def integer_writer():
i = 0
integer_writer()
i
i
is a local variable in the function integer_writer
, and new_function
is a local variable in the function function_writer
.
You could do the following:
def function_writer():
print "I am a function writer"
def new_function():
print "I am a new function"
return new_function
new_function = function_writer()
new_function()
In this case there doesn't seem to be much point (just as there wouldn't normally be much point defining a function that always returns 0
), but if function_writer
were to take some parameters, and if those parameters were used in the function it returns, then you'd be in business.
Upvotes: 5
Reputation: 91017
It depends what you plan to do with it.
You can call it inside the function.
That may be the case if the inner function needs to access local variables of the outer one.
You can return it in order to be called from outside.
That is quite usual e. g. in the case of decorators.
Upvotes: 1
Reputation:
Of course it will result in an error because new_function
is limited to function_writer
scope.
def function_writer():
print "I am a function writer"
def new_function():
print "I am a new function"
pass
return new_function
a = function_writer()
#output: "I am a function writer"
a()
#output: "I am a new function"
Upvotes: 1