Select to view content in your preferred language

python-toolbox: is it possible to define a function wihtin __init__ or execute?

507
2
08-10-2023 08:02 AM
nadja_swiss_parks
Occasional Contributor II

is it possible to define a function wihtin __init__ or execute? if yes, how?

like this doesnot work:

class Toolbox(object):
def __init__(self):
self.label = "Toolbox"
self.alias = "toolbox"

self.tools = [Tool]


def myfunction():
[...]

 

 

also this doesnot work:

def execute(self, parameters, messages):
def myfunction():
[...]

0 Kudos
2 Replies
DavidSolari
Occasional Contributor III

I strongly suggest learning how Python classes are written, the official docs are a good reference and there are many tutorials online that can walk you through creating your first class.

That said, there's nothing stopping you from defining functions within another function or method and then calling them. The catch is functions are bound to the scope they're defined in, which means you can't call an inner function outside of the method/function/etc. it's defined within.

The most likely reason your first example is failing is because you defined a method with no "self" parameter or no "@staticmethod" decorator, which makes it useless. Instance methods need self as the first parameter, decorated static methods do not.

0 Kudos
Luke_Pinner
MVP Regular Contributor

Yes. But you need to understand scope.  At it's simplest, functions (and variables) are objects and objects are only "visible" at (or below) the scope in which they are created.

So by creating a function inside the local scope of a method (e.g. __init__ or execute), you can only use that function inside the method you defined it in.

E.g.

class Tool(object):
    def __init__(self):
        def func_in_init():
            return "init"
    def execute(self):
        def func_in_exec():
            return "exec" 
        
        print(func_in_exec())  # this will work
        print(func_in_init())  # this will raise NameError
        

If you want to use a function anywhere, define it globally, if you want to use it anywhere in your Tool class and not outside the class, make it a method.

 

0 Kudos