Skip to main content

An instance method decorator that also works as a classmethod.

Project description

This simple module creates a class method that will also work as an instance method.

import dynamicmethod

class Example(object):

    x = 1  # Default classmethod value

    def __init__(self, x=0):
        self.x = x

    def get_x(self):
        return self.x

ex = Example()
ex.x = 5

I have grown to use this module quite a bit. Mostly I make a default class level dictionary where each instance can be customized.

from dynamicmethod import dynamicmethod

class Lookup(object):

    lookup_type = {'type1': 1, 'mytype2': 2}

    def __init__(self):
        # Save an instance variable so the class variable does not change.
        self.lookup_type = self.__class__.lookup_type.copy()

    def add_type(self, name, value):
        self.lookup_type[name] = value

    def get_type(self, name):
        return self.lookup_type.get(name, None)

Lookup.add_type('New Type', 3)
print(Lookup.get_type('New Type'))

specific_lookup = Lookup()
print(specific_lookup.get_type('New Type'))

specific_lookup.add_type('hello', 'world!')
# print(Lookup.get_type('hello'))  # This would be None since the class lookup does not contain 'hello'

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for dynamicmethod, version 1.0.4
Filename, size File type Python version Upload date Hashes
Filename, size dynamicmethod-1.0.4-py3-none-any.whl (13.1 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size dynamicmethod-1.0.4.tar.gz (4.3 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page