Search code examples
pythonpython-3.xfunctional-programmingglobal-variables

global variable vs getter functions vs function variable


I have a scenario that can be implemented in multiple ways. I need suggestion which is more optimized / python way of implementing and why ?

lets consider nested function calls as funca1 -> funca2 -> funca3 ->funca4 funcb1 -> funcb2 -> funcb3 ->funcb4

if __name__ == "__main__":
    funca1()
    funcb1()

and varx variable is only used / or needed by funca4 and funcb3. then we have below options

  1. create varx as global variable and use it funca4 and funcb3 with out passing through all the functions
  2. pass the varx variable across all the functions even through its used only in two functions
  3. create another functions get_varx() function and only use this inside funca4, funcb4.

This can also be achieved by creating class and assigning varx as property . But current design of the project doesn't allow this


Solution

  • I ran a demo code with the scenarios you gave, and timed the execution time using the time module and obtained the following results:

    Fastest Execution Rankings:

    1. Creating another function to get the value.
    2. Creating varx as a global variable.
    3. Passing the varx variable accross all the functions.