Package pytilities :: Package overloading :: Module overloader
[hide private]
[frames] | no frames]

Source Code for Module pytilities.overloading.overloader

 1  # Copyright (C) 2010 Tim Diels <limyreth@users.sourceforge.net> 
 2  #  
 3  # This file is part of pytilities. 
 4  #  
 5  # pytilities is free software: you can redistribute it and/or modify 
 6  # it under the terms of the GNU General Public License as published by 
 7  # the Free Software Foundation, either version 3 of the License, or 
 8  # (at your option) any later version. 
 9  #  
10  # pytilities is distributed in the hope that it will be useful, 
11  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
12  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
13  # GNU General Public License for more details. 
14  #  
15  # You should have received a copy of the GNU General Public License 
16  # along with pytilities.  If not, see <http://www.gnu.org/licenses/>. 
17  # 
18   
19  __docformat__ = 'reStructuredText' 
20   
21  import logging 
22   
23  from .parameter import Param 
24   
25  _logger = logging.getLogger("pytilities.overloading.overloader") 
26   
27 -class Overloader(object):
28 """ 29 A collection of `Overload`s that can process calls. 30 31 Tool for overloading operations. 32 33 Has an ordered collection of overloads which serve as rules, the operation 34 of the matching overload is called. If none match, an assertion error is 35 raised. 36 37 Methods: 38 39 - `process_call`: Process a call with given args and keyword args 40 """ 41
42 - def __init__(self, overloads, add_self = True):
43 """ 44 Construct an `Overloader`. 45 46 Parameters: 47 48 `overloads` :: (Overload...) 49 a collection of rules indicating which operation to call for 50 which combination of arguments/parameters. Note: the order can 51 effect which overload is matched as the first matching overload 52 is used. Must specify at least one overload. 53 54 `add_self` :: bool = True 55 if True, a "self" parameter is inserted at the beginning of the 56 parameter list of each overload 57 """ 58 59 assert overloads, "Must specify at least one overload" 60 61 self.__overloads = overloads 62 63 if add_self: 64 self_param = Param("self") 65 for overload in overloads: 66 overload.insert_params(0, self_param)
67
68 - def process_call(self, args, kwargs):
69 """ 70 Process a call with given args and keyword args. 71 72 The matching overload is called. 73 74 Parameters: 75 76 `args`, `kwargs' 77 arguments of the call 78 79 Returns the return value of the called operation 80 """ 81 82 _logger.debug("Processing call") 83 84 for overload in self.__overloads: 85 (matched, return_value) = overload.process_call(args, kwargs) 86 if matched: 87 return return_value 88 89 assert False, "Failed to find matching overload for given"
90