THIS IS NOT SOMETHING YOU SHOULD DO, but you could create a nested function attribute like so:
def foo():
# for closures or strictly local function
# then this is useful!
# ugly hack other wise to try and create methods.
def bar():
print('bar')
# if there are multiple function, return a container...
return bar
Then:
foo.bar=foo()
foo.bar()
# prints 'bar'
BUT, this is far easier with a class:
class Foo:
# class can hold related methods, setters and getters,
# protected variables, etc.
# Python is DESIGNED to do this.
def bar(self):
print('bar')
Then:
f=Foo()
f.bar()
# prints 'bar'
Why is it easier?
- Because Python is designed to use the second example, a class, but the first example is a hack. The ways to use classes are well documented and tested.
- It does not scale well. Each function attribute needs to be added from the OUTSIDE of the function.
- You will run into local vs global namespace issues if you try and change variables. Classes gracefully support both instance and class data.
It is horrible -- don't do it. Use a class or a module to hold methods.
After a morning coffee, you can potentially do something like this if you really want to add function attributes -- Use a decorator to monkey patch a function:
def add_func_to(function):
# decorator to add function attributes
def attr_f(new_func):
setattr(function, new_func.__name__, new_func)
return new_func
return attr_f
# some function to add an attribute function to:
def foo():
pass
@add_func_to(foo)
# added attribute function below
def attr_f(string):
print(string)
Test it:
>>> foo.attr_f('test')
test
This is still limited vs a class or module since you will be limited to using global or passed variables. It is more applicable if you just want to add a function attribute to an existing function and be done with it...
form_fillanderrorare local variables withmodel1(). They don't even exist except during a call to the outer function.