Showing posts with label Decorators. Show all posts
Showing posts with label Decorators. Show all posts

Monday, April 9, 2012

[Python] How to use Decorators for Functions and Methods


When list_ports() is executed, Class ApiCall will be created for becoming a decorator to examine the arguments as follows:


import sys class ApiCall(object): """A Decorator to add support for format and tenant overriding""" def __init__(self, function): self.function = function def __get__(self, instance, owner): def with_params(*args, **kwargs): """ Temporarily sets the format and tenant for this request """ (format, tenant) = (instance.format, instance.tenant) if 'format' in kwargs: instance.format = kwargs['format'] if 'tenant' in kwargs: instance.tenant = kwargs['tenant'] ret = self.function(instance, *args) (instance.format, instance.tenant) = (format, tenant) return ret return with_params class Client(object): def __init__(self, tenant=None, format="xml"): self.tenant = tenant self.format = format @ApiCall def list_ports(self, network): """ Fetches a list of ports on a given network """ return network def main(): client = Client(tenant="AAA",format="xml") client.list_ports('my network') sys.exit(0) if __name__ == "__main__": main()