本文整理汇总了Python中six.create_bound_method函数的典型用法代码示例。如果您正苦于以下问题:Python create_bound_method函数的具体用法?Python create_bound_method怎么用?Python create_bound_method使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了create_bound_method函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: addMethods
def addMethods(self):
# Add the auxiliary function specs to this Generator's namespace
for auxfnname in self.funcspec._pyauxfns:
fninfo = self.funcspec._pyauxfns[auxfnname]
if not hasattr(self, fninfo[1]):
# user-defined auxiliary functions
# (built-ins are provided explicitly)
if self._solver:
fnstr = fninfo[0].replace(self._solver.name, "ds._solver")
## self._funcreg[self._solver.name] = self._solver
else:
fnstr = fninfo[0]
try:
exec(fnstr)
except:
print("Error in supplied auxiliary function code")
self._funcreg[fninfo[1]] = ("self", fnstr)
setattr(self, fninfo[1], six.create_bound_method(locals()[fninfo[1]], self))
# user auxiliary function interface wrapper
try:
uafi_code = self.funcspec._user_auxfn_interface[auxfnname]
try:
exec(uafi_code)
except:
print("Error in auxiliary function wrapper")
raise
setattr(self.auxfns, auxfnname, six.create_bound_method(locals()[auxfnname], self.auxfns))
self._funcreg[auxfnname] = ("", uafi_code)
except KeyError:
# not a user-defined aux fn
pass
if self.funcspec.targetlang == "python":
# Add the spec function to this Generator's namespace
fninfo = self.funcspec.spec
if self._solver:
fnstr = fninfo[0].replace(self._solver.name, "ds._solver")
else:
fnstr = fninfo[0]
try:
exec(fnstr)
except:
print("Error in supplied functional specification code")
raise
self._funcreg[fninfo[1]] = ("self", fnstr)
setattr(self, fninfo[1], six.create_bound_method(locals()[fninfo[1]], self))
# Add the auxiliary spec function (if present) to this
# Generator's namespace
if self.funcspec.auxspec != "":
fninfo = self.funcspec.auxspec
if self._solver:
fnstr = fninfo[0].replace(self._solver.name, "ds._solver")
else:
fnstr = fninfo[0]
try:
exec(fnstr)
except:
print("Error in supplied auxiliary variable code")
raise
self._funcreg[fninfo[1]] = ("self", fnstr)
setattr(self, fninfo[1], six.create_bound_method(locals()[fninfo[1]], self))
示例2: __init__
def __init__(self, in_attrs, client):
"""Construct a resource
:param in_attrs: A dictionary of attributes, usually obtained from a
JSON response.
:param client: an instance of gocardless.Client
"""
attrs = in_attrs.copy()
self._raw_attrs = attrs.copy()
self.id = attrs["id"]
self.client = client
if "sub_resource_uris" in attrs:
#For each subresource_uri create a method which grabs data
#from the URI and uses it to instantiate the relevant class
#and return it.
for name, uri in six.iteritems(attrs.pop("sub_resource_uris")):
path = re.sub(".*/api/v1", "", uri)
sub_klass = self._get_klass_from_name(name)
def create_get_resource_func(the_path, the_klass):
# In python functions close over their environment so in
# order to create the correct closure we need a function
# creator, see
# http://stackoverflow.com/questions/233673/
# lexical-closures-in-python/235764#235764
def get_resources(inst, **params):
data = inst.client.api_get(the_path, params=params)
return [the_klass(attrs, self.client) for attrs in data]
return get_resources
res_func = create_get_resource_func(path, sub_klass)
func_name = "{0}".format(name)
res_func.name = func_name
setattr(self, func_name,
six.create_bound_method(res_func, self))
for fieldname in self.date_fields:
val = attrs.pop(fieldname)
if val is not None:
setattr(self, fieldname,
datetime.datetime.strptime(val, "%Y-%m-%dT%H:%M:%SZ"))
else:
setattr(self, fieldname, None)
for fieldname in self.reference_fields:
id = attrs.pop(fieldname)
def create_get_func(the_klass, the_id):
def get_referenced_resource(inst):
return the_klass.find_with_client(the_id, self.client)
return get_referenced_resource
name = fieldname.replace("_id", "")
klass = self._get_klass_from_name(name)
func = create_get_func(klass, id)
setattr(self, name, six.create_bound_method(func, self))
for key, value in six.iteritems(attrs):
setattr(self, key, value)
示例3: addMethods
def addMethods(self):
"""Add Python-specific functions to this object's methods."""
# Add the auxiliary function specs to this Generator's namespace
for auxfnname in self.funcspec._pyauxfns:
fninfo = self.funcspec._pyauxfns[auxfnname]
if not hasattr(self, fninfo[1]):
# user-defined auxiliary functions
# (built-ins are provided explicitly)
try:
exec(fninfo[0])
except:
print('Error in supplied auxiliary function code')
self._funcreg[fninfo[1]] = ('self', fninfo[0])
setattr(self, fninfo[1], six.create_bound_method(locals()[fninfo[1]], self))
# user auxiliary function interface wrapper
try:
uafi_code = self.funcspec._user_auxfn_interface[auxfnname]
try:
exec(uafi_code)
except:
print('Error in auxiliary function wrapper')
raise
setattr(self.auxfns, auxfnname,
six.create_bound_method(locals()[auxfnname], self.auxfns))
self._funcreg[auxfnname] = ('', uafi_code)
except KeyError:
# not a user-defined aux fn
pass
# Add the spec function to this Generator's namespace if
# target language is python (otherwise integrator exposes it anyway)
if self.funcspec.targetlang == 'python':
fninfo = self.funcspec.spec
try:
exec(fninfo[0])
except:
print('Error in supplied functional specification code')
raise
self._funcreg[fninfo[1]] = ('self', fninfo[0])
setattr(self, fninfo[1], six.create_bound_method(locals()[fninfo[1]], self))
# Add the auxiliary spec function (if present) to this
# Generator's namespace
if self.funcspec.auxspec != '':
fninfo = self.funcspec.auxspec
try:
exec(fninfo[0])
except:
print('Error in supplied auxiliary variable code')
raise
self._funcreg[fninfo[1]] = ('self', fninfo[0])
setattr(self, fninfo[1], six.create_bound_method(locals()[fninfo[1]], self))
示例4: load
def load(Class, path):
if not exists(path):
raise IOError
if path.endswith('.zip'):
import geometryIO
from crosscompute_table import pandas as pd
[
proj4,
geometries,
field_packs,
field_definitions,
] = geometryIO.load(path)
# Convert to (longitude, latitude)
normalize_geometry = geometryIO.get_transformGeometry(
proj4 or geometryIO.proj4LL)
geometries = [normalize_geometry(x) for x in geometries]
# Convert to (latitude, longitude)
geometries = transform_geometries(geometries, drop_z)
geometries = transform_geometries(geometries, flip_xy)
# Generate table
table = pd.DataFrame(
field_packs, columns=[x[0] for x in field_definitions])
table['WKT'] = [x.wkt for x in geometries]
else:
table = super(GeotableType, Class).load(path)
# TODO: Consider whether there is a better way to do this
table.interpret = create_bound_method(_interpret, table)
return table
示例5: get_request
def get_request(
self, package=None, perms="", user=None, use_base_url=False, path=None
):
""" Construct a fake request """
request = MagicMock()
request.registry.fallback = self.fallback
request.registry.always_show_upstream = self.always_show_upstream
request.registry.fallback_url = self.fallback_url
request.registry.fallback_base_url = (
self.fallback_base_url if use_base_url else None
)
request.userid = user
request.access.can_update_cache = lambda: "c" in perms
request.access.has_permission.side_effect = lambda n, p: "r" in perms
request.is_logged_in = user is not None
request.request_login = six.create_bound_method(_request_login, request)
pkgs = []
if package is not None:
pkgs.append(package)
if path is not None:
request.path = path
request.db.all.return_value = pkgs
return request
示例6: __getattr__
def __getattr__(self, name):
fun = None
if re.match("__.*__", name):
# This is a python internal name, skip it
raise AttributeError
# try it bare
llib = getattr(self, "lib")
try:
fun = getattr(llib, name)
except AttributeError:
for prefix in self.prefixes:
try:
# wrap it
fun = getattr(llib, prefix + name)
break
except AttributeError:
pass
if fun is None:
# Return a proxy class to generate a good error on call
error_printer = ErrorPrinter(name, self.prefixes)
setattr(self, name, error_printer)
return error_printer
if not callable(fun): # pragma: no cover
setattr(self, name, fun)
return fun
new_fun = self.check_wrap(fun, name)
new_method = six.create_bound_method(new_fun, self)
# Store the wrapper function into the instance
# to prevent a second lookup
setattr(self, name, new_method)
return new_method
示例7: test_365_calendar
def test_365_calendar(self):
f = mock.MagicMock(
lbtim=SplittableInt(4, {"ia": 2, "ib": 1, "ic": 0}),
lbyr=2013,
lbmon=1,
lbdat=1,
lbhr=12,
lbmin=0,
lbsec=0,
spec=PPField3,
)
f.time_unit = six.create_bound_method(PPField3.time_unit, f)
f.calendar = cf_units.CALENDAR_365_DAY
(
factories,
references,
standard_name,
long_name,
units,
attributes,
cell_methods,
dim_coords_and_dims,
aux_coords_and_dims,
) = convert(f)
def is_t_coord(coord_and_dims):
coord, dims = coord_and_dims
return coord.standard_name == "time"
coords_and_dims = list(filter(is_t_coord, aux_coords_and_dims))
self.assertEqual(len(coords_and_dims), 1)
coord, dims = coords_and_dims[0]
self.assertEqual(guess_coord_axis(coord), "T")
self.assertEqual(coord.units.calendar, "365_day")
示例8: __init__
def __init__(self, suite, processes, failfast):
# type: (TestSuite, int, bool) -> None
super(ParallelTestSuite, self).__init__(suite, processes, failfast)
self.subsuites = SubSuiteList(self.subsuites) # type: SubSuiteList
# ParallelTestSuite expects this to be a bound method so it can access
# __func__ when passing it to multiprocessing.
method = partial(run_subsuite, suite.collect_coverage)
self.run_subsuite = six.create_bound_method(cast(types.FunctionType, method), self)
示例9: register_extension_method
def register_extension_method(ext, base, *args, **kwargs):
"""Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a public attribute of that
base.
"""
bound_method = create_bound_method(ext.plugin, base)
setattr(base, ext.name.lstrip('_'), bound_method)
示例10: bind_default_handler
def bind_default_handler(self, obj, name):
"""Bind the default handler method to `obj` as attribute `name`.
This could also be implemented as a mixin class.
"""
assert self.default_handler is not None, '%s has no default handler method, cannot bind' % self.__class__.__name__
setattr(obj, name, six.create_bound_method(self.default_handler, obj))
log.debug("Bound default message handler '%s.%s' to %s", self.__class__.__name__, self.default_handler.__name__,
getattr(obj, name))
示例11: test_create_bound_method
def test_create_bound_method():
class X(object):
pass
def f(self):
return self
x = X()
b = six.create_bound_method(f, x)
assert isinstance(b, types.MethodType)
assert b() is x
示例12: test_autospec_on_bound_builtin_function
def test_autospec_on_bound_builtin_function(self):
meth = six.create_bound_method(time.ctime, time.time())
self.assertIsInstance(meth(), str)
mocked = create_autospec(meth)
# no signature, so no spec to check against
mocked()
mocked.assert_called_once_with()
mocked.reset_mock()
mocked(4, 5, 6)
mocked.assert_called_once_with(4, 5, 6)
示例13: client
def client(app):
client = app.test_client()
def get_session_cookie(self):
return self.cookie_jar._cookies['localhost.local']['/']['session']
client.get_session_cookie = six.create_bound_method(
get_session_cookie, client,
)
return client
示例14: add_context_manager_support
def add_context_manager_support(obj):
""" Add empty __enter__ and __exit__ methods on a given object.
This function is required to be called on any object used by the data()
methods on the stores. They are supposed to be file-like byte streams.
Adding the support for using them as context managers allows us to make
sure we clean the resources when a proper __exit__ method is available.
"""
def __enter__(self):
return self
def __exit__(self, *args):
pass
if not hasattr(obj, '__enter__'):
obj.__enter__ = create_bound_method(__enter__, obj)
if not hasattr(obj, '__exit__'):
obj.__exit__ = create_bound_method(__exit__, obj)
return obj
示例15: _create_action_method
def _create_action_method(self, i, action):
# PP saving style action. No return value, e.g. "pp.lbft = 3".
ns = locals().copy()
exec(compile('def _f(self, field, f, pp, grib, cm): %s' % (action, ),
'<string>',
'exec'),
globals(),
ns)
# Make it a method of ours.
method = six.create_bound_method(ns['_f'], self)
setattr(self, '_exec_action_%d' % (i, ), method)
# Add to our list of actions.
self._exec_actions.append(method)