Skip to content

Instantly share code, notes, and snippets.

@Wilfred
Last active November 22, 2023 16:01
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Wilfred/49b0409c6489f1bdf5a5c98a488b31b5 to your computer and use it in GitHub Desktop.
Save Wilfred/49b0409c6489f1bdf5a5c98a488b31b5 to your computer and use it in GitHub Desktop.
dynamically defined properties in python
def attach_dyn_prop(instance, prop_name, prop_fn):
"""Attach prop_fn to instance with name prop_name.
Assumes that prop_fn takes self as an argument.
Reference: https://stackoverflow.com/a/1355444/509706
"""
class_name = instance.__class__.__name__ + 'Child'
child_class = type(class_name, (instance.__class__,), {prop_name: property(prop_fn)})
instance.__class__ = child_class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment