本文整理匯總了Python中types.MethodType方法的典型用法代碼示例。如果您正苦於以下問題:Python types.MethodType方法的具體用法?Python types.MethodType怎麽用?Python types.MethodType使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類types
的用法示例。
在下文中一共展示了types.MethodType方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: create_file_logger
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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
示例2: forEachLine
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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
示例3: validate_error_func
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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
示例4: get_pfunctions
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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
示例5: subscribe
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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)
示例6: bind_method
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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)
示例7: __init__
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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)
示例8: validate_error_func
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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
示例9: get_pfunctions
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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
示例10: api_view_serializer_class_getter
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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
示例11: test_websocket_sending_invalid_payload
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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"
示例12: _getargs
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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]
示例13: _forEachRecord
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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
示例14: _form_master_re
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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')
# -----------------------------------------------------------------------------
示例15: make_method_with_retries
# 需要導入模塊: import types [as 別名]
# 或者: from types import MethodType [as 別名]
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