Calling a function of a module by using its name (a string)
Invoke a function in a module using its string name through the built-in function getattr
. Make sure that your module is already imported and double-check the function name to evade any hassles. Here’s a quick demonstration:
Exploring Python’s dynamic nature
The usage of getattr
is only a single aspect of Python’s capabilities to dynamically invoke functions. Let’s explore more!
Dynamic Invocations in Global and Local Scopes
Ever heard of globals()
and locals()
?
Global Scope
globals()
offers a dictionary reflecting the current global symbol table. Yes, Python’s dictionary of secrets!
Local Scope
On the flip side, locals()
returns a dictionary representing the current local symbol table, kind of like a private diary!
Dynamic Import of Modules and Function Calling
Need to import modules dynamically and call their functions? Python says, "No problem!"
Dynamically Invoking Class Methods
Creating class instances and calling methods can be dynamic too, thanks to Python’s versatility!
Dealing with Complex Structures
Hey, it’s Python! Dealing with complexities is just another day at the office!
Dynamically Executing Design Patterns
Capabilities extend to executing Singleton and Factory patterns dynamically too:
The efficiency at which Python uses to execute powerful patterns optimises development speed and productivity.
Was this article helpful?