Python types.MethodType() Examples
The following are 30
code examples of types.MethodType().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
types
, or try the search function
.

Example #1
Source File: log_api.py From mlimages with MIT License | 6 votes |
def create_file_logger(root, name, file_name="log.txt", timestamp_format="", debug=False): file_api = FileAPI(root) timestamp = "" if timestamp_format: timestamp = datetime.now().strftime(timestamp_format) else: timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") folder = name + "_" + timestamp # prepare folder and file with file_api.open_with_mkdir(folder + "/" + file_name) as f: f.write("".encode("utf-8")) log_root = os.path.join(root, folder) logger = create_logger(name, debug) fh = FileHandler(os.path.join(log_root, file_name), encoding="utf-8") fh.setLevel(_bool_2_level(debug)) logger.addHandler(fh) # add close method to release resource logger.close = types.MethodType(__close, logger) return logger, log_root
Example #2
Source File: csv.py From CAMISIM with Apache License 2.0 | 6 votes |
def forEachLine(filePath, parser): """ For each line of the file call the parser, at the end call the finalize method of the parser if it`s defined. """ try: f = open(os.path.normpath(filePath), 'r') except Exception: sys.stderr.write('Cannot open a file for reading: ' + filePath) raise else: try: for line in f: parser.parse(noNewLine(line)) except Exception: sys.stderr.write('Cannot read from file: ' + filePath) raise finally: f.close() try: if isinstance(parser.finalize, types.MethodType): parser.finalize() except Exception: pass return parser
Example #3
Source File: yacc.py From SublimeKSP with GNU General Public License v3.0 | 6 votes |
def validate_error_func(self): if self.error_func: if isinstance(self.error_func,types.FunctionType): ismethod = 0 elif isinstance(self.error_func, types.MethodType): ismethod = 1 else: self.log.error("'p_error' defined, but is not a function or method") self.error = 1 return eline = func_code(self.error_func).co_firstlineno efile = func_code(self.error_func).co_filename module = inspect.getmodule(self.error_func) self.modules[module] = 1 argcount = func_code(self.error_func).co_argcount - ismethod if argcount != 1: self.log.error("%s:%d: p_error() requires 1 argument",efile,eline) self.error = 1 # Get the tokens map
Example #4
Source File: yacc.py From SublimeKSP with GNU General Public License v3.0 | 6 votes |
def get_pfunctions(self): p_functions = [] for name, item in self.pdict.items(): if not name.startswith('p_'): continue if name == 'p_error': continue if isinstance(item,(types.FunctionType,types.MethodType)): line = func_code(item).co_firstlineno module = inspect.getmodule(item) p_functions.append((line,module,name,item.__doc__)) # Sort all of the actions by line number p_functions.sort() self.pfuncs = p_functions # Validate all of the p_functions
Example #5
Source File: config.py From python-esppy with Apache License 2.0 | 6 votes |
def subscribe(func): ''' Add a subscriber function to option events Parameters ---------- func : callable A callable object that takes two parameters: key and value. This function is called with the name and value of any option that is set. Returns ------- None ''' if isinstance(func, types.MethodType): obj = six.get_method_self(func) func = six.get_method_function(func) _subscribers[func] = (weakref.ref(func), weakref.ref(obj)) else: _subscribers[func] = (weakref.ref(func), None)
Example #6
Source File: __init__.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
def bind_method(cls, name, func): """Bind a method to class, python 2 and python 3 compatible. Parameters ---------- cls : type class to receive bound method name : basestring name of method on class instance func : function function to be bound as method Returns ------- None """ # only python 2 has an issue with bound/unbound methods if not PY3: setattr(cls, name, types.MethodType(func, None, cls)) else: setattr(cls, name, func)
Example #7
Source File: runtime.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, environment, parent, name, blocks): self.parent = parent self.vars = {} self.environment = environment self.eval_ctx = EvalContext(self.environment, name) self.exported_vars = set() self.name = name # create the initial mapping of blocks. Whenever template inheritance # takes place the runtime will update this mapping with the new blocks # from the template. self.blocks = dict((k, [v]) for k, v in iteritems(blocks)) # In case we detect the fast resolve mode we can set up an alias # here that bypasses the legacy code logic. if self._fast_resolve_mode: self.resolve_or_missing = MethodType(resolve_or_missing, self)
Example #8
Source File: yacc.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def validate_error_func(self): if self.error_func: if isinstance(self.error_func, types.FunctionType): ismethod = 0 elif isinstance(self.error_func, types.MethodType): ismethod = 1 else: self.log.error("'p_error' defined, but is not a function or method") self.error = True return eline = self.error_func.__code__.co_firstlineno efile = self.error_func.__code__.co_filename module = inspect.getmodule(self.error_func) self.modules.add(module) argcount = self.error_func.__code__.co_argcount - ismethod if argcount != 1: self.log.error('%s:%d: p_error() requires 1 argument', efile, eline) self.error = True # Get the tokens map
Example #9
Source File: __init__.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def bind_method(cls, name, func): """Bind a method to class, python 2 and python 3 compatible. Parameters ---------- cls : type class to receive bound method name : basestring name of method on class instance func : function function to be bound as method Returns ------- None """ # only python 2 has an issue with bound/unbound methods if not PY3: setattr(cls, name, types.MethodType(func, None, cls)) else: setattr(cls, name, func)
Example #10
Source File: yacc.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def validate_error_func(self): if self.error_func: if isinstance(self.error_func, types.FunctionType): ismethod = 0 elif isinstance(self.error_func, types.MethodType): ismethod = 1 else: self.log.error("'p_error' defined, but is not a function or method") self.error = True return eline = self.error_func.__code__.co_firstlineno efile = self.error_func.__code__.co_filename module = inspect.getmodule(self.error_func) self.modules.add(module) argcount = self.error_func.__code__.co_argcount - ismethod if argcount != 1: self.log.error('%s:%d: p_error() requires 1 argument', efile, eline) self.error = True # Get the tokens map
Example #11
Source File: yacc.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def get_pfunctions(self): p_functions = [] for name, item in self.pdict.items(): if not name.startswith('p_') or name == 'p_error': continue if isinstance(item, (types.FunctionType, types.MethodType)): line = getattr(item, 'co_firstlineno', item.__code__.co_firstlineno) module = inspect.getmodule(item) p_functions.append((line, module, name, item.__doc__)) # Sort all of the actions by line number; make sure to stringify # modules to make them sortable, since `line` may not uniquely sort all # p functions p_functions.sort(key=lambda p_function: ( p_function[0], str(p_function[1]), p_function[2], p_function[3])) self.pfuncs = p_functions # Validate all of the p_functions
Example #12
Source File: decorators.py From django-rest-registration with MIT License | 6 votes |
def api_view_serializer_class_getter(serializer_class_getter): def _get_serializer_class(self): return serializer_class_getter() def _get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() return serializer_class(*args, **kwargs) def decorator(func): if not hasattr(func, 'cls'): raise Exception( '@api_view_serializer_class_getter can only decorate' ' @api_view decorated functions') apiview_cls = func.cls apiview_cls.get_serializer_class = types.MethodType( _get_serializer_class, apiview_cls) if not hasattr(apiview_cls, 'get_serializer'): # In case get_serializer() method is missing. apiview_cls.get_serializer = types.MethodType( _get_serializer, apiview_cls) return func return decorator
Example #13
Source File: test_websocket_exceptions.py From gql with MIT License | 5 votes |
def test_websocket_sending_invalid_payload( event_loop, client_and_server, query_str ): session, server = client_and_server # Monkey patching the _send_query method to send an invalid payload async def monkey_patch_send_query( self, document, variable_values=None, operation_name=None, ) -> int: query_id = self.next_query_id self.next_query_id += 1 query_str = json.dumps( {"id": str(query_id), "type": "start", "payload": "BLAHBLAH"} ) await self._send(query_str) return query_id session.transport._send_query = types.MethodType( monkey_patch_send_query, session.transport ) query = gql(query_str) with pytest.raises(TransportQueryError) as exc_info: await session.execute(query) exception = exc_info.value assert isinstance(exception.errors, List) error = exception.errors[0] assert error["message"] == "Must provide document"
Example #14
Source File: _cptools.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _getargs(func): """Return the names of all static arguments to the given function.""" # Use this instead of importing inspect for less mem overhead. import types if isinstance(func, types.MethodType): func = func.__func__ co = func.__code__ return co.co_varnames[:co.co_argcount]
Example #15
Source File: fasta.py From CAMISIM with Apache License 2.0 | 5 votes |
def _forEachRecord(filePath, parser, formatName="fasta"): """ Call the parser for each record in the file. """ try: if isinstance(parser.getFormatName, types.MethodType): formatName = parser.getFormatName() except Exception: pass try: f = open(os.path.normpath(filePath), 'r') except Exception: sys.stderr.write('Cannot open a ' + formatName + ' file for reading: ' + filePath + '\n') raise else: try: readBuffer = SeqIO.parse(f, parser.getFormatName()) for record in readBuffer: parser.parse(record) except Exception: sys.stderr.write('Cannot read from a ' + formatName + ' file: ' + filePath + '\n') raise finally: f.close() try: if isinstance(parser.finalize, types.MethodType): parser.finalize() except Exception: pass return parser
Example #16
Source File: lex.py From SublimeKSP with GNU General Public License v3.0 | 5 votes |
def _form_master_re(relist,reflags,ldict,toknames): if not relist: return [] regex = "|".join(relist) try: lexre = re.compile(regex,re.VERBOSE | reflags) # Build the index to function map for the matching engine lexindexfunc = [ None ] * (max(lexre.groupindex.values())+1) lexindexnames = lexindexfunc[:] for f,i in lexre.groupindex.items(): handle = ldict.get(f,None) if type(handle) in (types.FunctionType, types.MethodType): lexindexfunc[i] = (handle,toknames[f]) lexindexnames[i] = f elif handle is not None: lexindexnames[i] = f if f.find("ignore_") > 0: lexindexfunc[i] = (None,None) else: lexindexfunc[i] = (None, toknames[f]) return [(lexre,lexindexfunc)],[regex],[lexindexnames] except Exception: m = int(len(relist)/2) if m == 0: m = 1 llist, lre, lnames = _form_master_re(relist[:m],reflags,ldict,toknames) rlist, rre, rnames = _form_master_re(relist[m:],reflags,ldict,toknames) return llist+rlist, lre+rre, lnames+rnames # ----------------------------------------------------------------------------- # def _statetoken(s,names) # # Given a declaration name s of the form "t_" and a dictionary whose keys are # state names, this function returns a tuple (states,tokenname) where states # is a tuple of state names and tokenname is the name of the token. For example, # calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM') # -----------------------------------------------------------------------------
Example #17
Source File: __init__.py From aws-ops-automator with Apache License 2.0 | 5 votes |
def make_method_with_retries(boto_client_or_resource, name, service_retry_strategy=None, method_suffix=DEFAULT_SUFFIX): """ Creates a wrapper for a boto3 method call that handles boto_retry in case of an exception from which it can recover. Situations in which case this is possible are defined in the service specific service_retry_strategy class :param boto_client_or_resource: boto client or resource to add method to :param name: Name of the boto call :param service_retry_strategy: Strategy that implements the logic that determines if boto_retry are possible in case of an exception :param method_suffix: suffix for wrapped boto method :return: """ # default strategy retry_strategy = service_retry_strategy if service_retry_strategy is not None else AwsApiServiceRetry() # new method name method_name = name + method_suffix # closure function def wrapped_api_method(client_or_resource, **args): return retry_strategy.call(client_or_resource, name, args) # add closure function to the client or resource # noinspection PyArgumentList setattr(boto_client_or_resource, method_name, types.MethodType(wrapped_api_method, boto_client_or_resource)) # return the method, but it can also be called directly as method of the boto client return wrapped_api_method
Example #18
Source File: utils.py From contextualbandits with BSD 2-Clause "Simplified" License | 5 votes |
def _convert_decision_function_w_sigmoid(classifier): if 'decision_function' in dir(classifier): classifier.decision_function_w_sigmoid = types.MethodType(_decision_function_w_sigmoid, classifier) #### Note: the weird name is to avoid potential collisions with user-defined methods elif 'predict' in dir(classifier): classifier.decision_function_w_sigmoid = types.MethodType(_decision_function_w_sigmoid_from_predict, classifier) else: raise ValueError("Classifier must have at least one of 'predict_proba', 'decision_function', 'predict'.") return classifier
Example #19
Source File: utils.py From contextualbandits with BSD 2-Clause "Simplified" License | 5 votes |
def _add_method_predict_robust(classifier): if 'predict_proba' in dir(classifier): classifier.predict_proba_robust = types.MethodType(_robust_predict_proba, classifier) if 'decision_function_w_sigmoid' in dir(classifier): classifier.decision_function_robust = types.MethodType(_robust_decision_function_w_sigmoid, classifier) elif 'decision_function' in dir(classifier): classifier.decision_function_robust = types.MethodType(_robust_decision_function, classifier) if 'predict' in dir(classifier): classifier.predict_robust = types.MethodType(_robust_predict, classifier) return classifier
Example #20
Source File: bot_app.py From botbuilder-python with MIT License | 5 votes |
def __init__(self): # Create the loop and Flask app self.loop = asyncio.get_event_loop() self.flask = Flask(__name__, instance_relative_config=True) self.flask.config.from_object(DefaultConfig) # Create adapter. # See https://aka.ms/about-bot-adapter to learn more about how bots work. self.settings = BotFrameworkAdapterSettings( self.flask.config["APP_ID"], self.flask.config["APP_PASSWORD"] ) self.adapter = BotFrameworkAdapter(self.settings) # Catch-all for errors. async def on_error(adapter, context: TurnContext, error: Exception): # This check writes out errors to console log .vs. app insights. # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error]: {error}", file=sys.stderr) # Send a message to the user error_message_text = "Sorry, it looks like something went wrong." error_message = MessageFactory.text( error_message_text, error_message_text, InputHints.expecting_input ) await context.send_activity(error_message) # pylint: disable=protected-access if adapter._conversation_state: # If state was defined, clear it. await adapter._conversation_state.delete(context) self.adapter.on_turn_error = MethodType(on_error, self.adapter) # Create the main dialog self.bot = MyBot()
Example #21
Source File: objgraph.py From rtp_cluster with BSD 2-Clause "Simplified" License | 5 votes |
def short_repr(obj): if isinstance(obj, (type, types.ModuleType, types.BuiltinMethodType, types.BuiltinFunctionType)): return obj.__name__ if isinstance(obj, types.MethodType): if obj.im_self is not None: return obj.im_func.__name__ + ' (bound)' else: return obj.im_func.__name__ if isinstance(obj, (tuple, list, dict, set)): return '%d items' % len(obj) if isinstance(obj, weakref.ref): return 'all_weakrefs_are_one' return repr(obj)[:40]
Example #22
Source File: cloudpickle.py From pywren-ibm-cloud with Apache License 2.0 | 5 votes |
def save_instancemethod(self, obj): # Memoization rarely is ever useful due to python bounding if obj.__self__ is None: self.save_reduce(getattr, (obj.im_class, obj.__name__)) else: if PY3: # pragma: no branch self.save_reduce(types.MethodType, (obj.__func__, obj.__self__), obj=obj) else: self.save_reduce( types.MethodType, (obj.__func__, obj.__self__, type(obj.__self__)), obj=obj)
Example #23
Source File: util.py From pymoo with Apache License 2.0 | 5 votes |
def decompose(problem, decomposition, weights, return_copy=True): if return_copy: problem = copy.deepcopy(problem) problem._multi_evaluate = problem._evaluate def _evaluate(self, x, out, *args, **kwargs): self._multi_evaluate(x, out, *args, **kwargs) out["F"] = decomposition.do(out["F"], weights, _type="many_to_one") problem._evaluate = types.MethodType(_evaluate, problem) problem.n_obj = 1 return problem
Example #24
Source File: interface.py From pymoo with Apache License 2.0 | 5 votes |
def ask(self): # if the initial population has not been generated yet if self.get_population() is None: self.algorithm.initialize(self.problem) # deactivate the survival because no values have been set yet survival = self.algorithm.survival self.algorithm.survival = None self.problem._evaluate = types.MethodType(evaluate_to_nan, self.problem) self.algorithm._initialize() # activate the survival for the further runs self.algorithm.survival = survival return self.get_population().get("X") # usually the case - create the next output else: # if offsprings do not exist set the pop - otherwise always offsprings if self.get_offsprings() is not None: self.set_population(Population.merge(self.get_population(), self.get_offsprings())) # execute a survival of the algorithm survivors = self.algorithm.survival.do(self.problem, self.get_population(), self.algorithm.pop_size, algorithm=self.algorithm) self.set_population(survivors) # execute the mating using the population off = self.algorithm.mating.do(self.algorithm.problem, self.get_population(), n_offsprings=self.algorithm.n_offsprings, algorithm=self.algorithm) # execute the fake evaluation of the individuals self.problem._evaluate = types.MethodType(evaluate_to_nan, self.problem) self.algorithm.evaluator.eval(self.problem, off, algorithm=self.algorithm) self.set_offsprings(off) return off.get("X")
Example #25
Source File: interface.py From pymoo with Apache License 2.0 | 5 votes |
def tell(self, F, G=None, X=None): # if offsprings do not exist set the pop - otherwise always offsprings pop_to_evaluate = self.get_offsprings() if self.get_offsprings() is not None else self.get_population() # if the user changed the design space values for whatever reason if X is not None: pop_to_evaluate.set("X") # do the function evaluations self.problem._evaluate = types.MethodType(evaluate_to_value(F.copy(), G.copy()), self.problem) self.algorithm.evaluator.eval(self.problem, pop_to_evaluate, algorithm=self.algorithm)
Example #26
Source File: random.py From jawfish with MIT License | 5 votes |
def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type, Method=_MethodType, BuiltinMethod=_BuiltinMethodType): "Return a random int in the range [0,n). Raises ValueError if n==0." getrandbits = self.getrandbits # Only call self.getrandbits if the original random() builtin method # has not been overridden or if a new getrandbits() was supplied. if type(self.random) is BuiltinMethod or type(getrandbits) is Method: k = n.bit_length() # don't use (n-1) here because n can be 1 r = getrandbits(k) # 0 <= r < 2**k while r >= n: r = getrandbits(k) return r # There's an overriden random() method but no new getrandbits() method, # so we can only use random() from here. random = self.random if n >= maxsize: _warn("Underlying random() generator does not supply \n" "enough bits to choose from a population range this large.\n" "To remove the range limitation, add a getrandbits() method.") return int(random() * n) rem = maxsize % n limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0 r = random() while r >= limit: r = random() return int(r*maxsize) % n ## -------------------- sequence methods -------------------
Example #27
Source File: inspect.py From jawfish with MIT License | 5 votes |
def ismethod(object): """Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined __func__ function object containing implementation of method __self__ instance to which this method is bound""" return isinstance(object, types.MethodType)
Example #28
Source File: six.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__)
Example #29
Source File: six.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def create_unbound_method(func, cls): return types.MethodType(func, None, cls)
Example #30
Source File: internals.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def overridden(method): """ :return: True if ``method`` overrides some method with the same name in a base class. This is typically used when defining abstract base classes or interfaces, to allow subclasses to define either of two related methods: >>> class EaterI: ... '''Subclass must define eat() or batch_eat().''' ... def eat(self, food): ... if overridden(self.batch_eat): ... return self.batch_eat([food])[0] ... else: ... raise NotImplementedError() ... def batch_eat(self, foods): ... return [self.eat(food) for food in foods] :type method: instance method """ # [xx] breaks on classic classes! if isinstance(method, types.MethodType) and compat.get_im_class(method) is not None: name = method.__name__ funcs = [cls.__dict__[name] for cls in _mro(compat.get_im_class(method)) if name in cls.__dict__] return len(funcs) > 1 else: raise TypeError('Expected an instance method.')