Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active December 6, 2019 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/c57f94b07b32b851c491e889571ad450 to your computer and use it in GitHub Desktop.
Save gsscoder/c57f94b07b32b851c491e889571ad450 to your computer and use it in GitHub Desktop.
Dynamic calls in Python
import sys
def say_something(text):
print(f'I say: {text}...')
class simple:
def hello(self, text):
print(f'Hello, {text}!')
@staticmethod
def hello_again(text):
print(f'Hello again, {text}!')
# function
# mode 1
func = getattr(sys.modules[__name__], 'say_something')
func('I love dynamic stuff')
# mode 2
func2 = locals()['say_something']
func2('I love dynamic stuff too')
# class
# mode 1
class_ = getattr(sys.modules[__name__], 'simple')
class_().hello('dynamic world')
class_.hello_again('dynamic world')
# mode 2
class2 = locals()['simple']
class2().hello('dynamic world!!')
class2().hello_again('dynamic world!!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment