For the past two day's, I have been exploring decorators and how they can be used to create and modify classes without difficulty or effort. This exploration lead to this piece of code.
Factory.py
#!/usr/bin/env python
import sys
import functools
class Factory(object):
def with_callback(self, func):
postname = func.func_name
def wraped(callback, *args, **kw):
cbname = callback.func_name
print 'Passing {post} to {cb}'.format(post=postname, cb=cbname)
premute = func(*args, **kw)
return callback(premute)
return wraped
def __str__(self):
return str(self.__dict__)
def register(self, name):
def func_wrapper(func):
self.__dict__[name] = func
return func
return func_wrapper
def __getitem__(self, name):
return self.__dict__.get(name, None)
def __setitem__(self, name):
self.register(name)
def __call__(self, name=None, *args, **kw):
return self.__dict__.get(name, None)(*args, **kw)
def copy(self, old):
class DerivedFactory(self.__class__):
def __init__(self):
self.__dict__ = old.__dict__
self.__class__ = old.__class__
return DerivedFactory()
if __name__ == '__main__':
import requests
app = Factory()
@app.register('process_response')
def process_response(response):
print response.content
@app.register('get')
@app.with_callback
def get(url):
return requests.get(url)
x = app('get', app.process_response, 'http://www.google.com')
print x
Here is a example use of Factory.py
#!/usr/bin/env python
import Factory
import requests
from bs4 import BeautifulSoup as bs
class App(Factory.Factory):
pass
Parser = App()
@Parser.register('get_soup')
@Parser.with_callback
def _get(url, *req_args, **req_kw):
response = requests.get(url, *req_args, **req_kw)
return bs(response.content)
@Parser.register('get_links')
def _getlinks(soup):
return soup.find_all('', {'href':True})
print Parser('get_soup', Parser.get_links, 'http://www.google.com')
There are six main programming paradigms:
- imperative
- declarative
- functional
- object-oriented
- logic
- symbolic
Which of these paradigms best describe Factory.py ?