本文整理汇总了Python中six.moves.intern函数的典型用法代码示例。如果您正苦于以下问题:Python intern函数的具体用法?Python intern怎么用?Python intern使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了intern函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: map_sum
def map_sum(self, expr):
sum_kind = None
term_kind_matrix = intern("matrix")
term_kind_vector = intern("vector")
term_kind_scalar = intern("scalar")
result = 0
for child in expr.children:
rec_child = self.rec(child)
if is_zero(rec_child):
continue
if isinstance(rec_child, np.ndarray):
if self.is_kind_matrix(rec_child):
term_kind = term_kind_matrix
elif self.is_kind_vector(rec_child):
term_kind = term_kind_vector
else:
raise RuntimeError("unexpected array rank")
else:
term_kind = term_kind_scalar
if sum_kind is None:
sum_kind = term_kind
if term_kind != sum_kind:
raise RuntimeError("encountered %s in sum of kind %s"
% (term_kind, sum_kind))
result = result + rec_child
return result
示例2: __init__
def __init__(self, next_attr_name=None, prev_attr_name=None):
"""Initializes this list.
next_attr_name: The name of the attribute that holds a reference
to the next item in the list.
prev_attr_name: the name of the attribute that holds a reference
to the previous item in the list.
"""
# Keep an interned version of the attribute names. This should
# speed up the process of looking up the attributes.
self.next_name = intern(next_attr_name)
self.prev_name = intern(prev_attr_name)
示例3: __init__
def __init__(self, **kwargs):
kwargs["name"] = intern(kwargs.pop("name"))
target = kwargs.pop("target", None)
dtype = kwargs.pop("dtype", None)
if 'for_atomic' in kwargs:
for_atomic = kwargs['for_atomic']
else:
for_atomic = False
from loopy.types import to_loopy_type
dtype = to_loopy_type(
dtype, allow_auto=True, allow_none=True, for_atomic=for_atomic,
target=target)
import loopy as lp
if dtype is lp.auto:
warn("Argument/temporary data type for '%s' should be None if "
"unspecified, not auto. This usage will be disallowed in 2018."
% kwargs["name"],
DeprecationWarning, stacklevel=2)
dtype = None
kwargs["dtype"] = dtype
ImmutableRecord.__init__(self, **kwargs)
示例4: normalize_chromosome
def normalize_chromosome(c):
try:
return NORMALIZE_CHROMOSOME_CACHE[c]
except KeyError:
pass
if not (is_string(c) or is_integer(c)):
raise TypeError("Chromosome cannot be '%s' : %s" % (c, type(c)))
result = str(c)
if result == "0":
raise ValueError("Chromosome name cannot be 0")
elif result == "":
raise ValueError("Chromosome name cannot be empty")
# only strip off lowercase chr since some of the non-chromosomal
# contigs start with "CHR"
if result.startswith("chr"):
result = result[3:]
# just in case someone is being lazy, capitalize "M", "MT", X", "Y"
result = result.upper()
# standardize mitochondrial genome to be "MT"
if result == "M":
result = "MT"
# interning strings since the chromosome names probably get constructed
# or parsed millions of times, can save memory in tight situations
# (such as parsing GTF files)
result = intern(result)
NORMALIZE_CHROMOSOME_CACHE[c] = result
return result
示例5: memoize_method
def memoize_method(method):
"""Supports cache deletion via ``method_name.clear_cache(self)``.
.. note::
*clear_cache* support requires Python 2.5 or newer.
"""
cache_dict_name = intern("_memoize_dic_"+method.__name__)
def wrapper(self, *args, **kwargs):
if kwargs:
key = (_HasKwargs, frozenset(six.iteritems(kwargs))) + args
else:
key = args
try:
return getattr(self, cache_dict_name)[key]
except AttributeError:
result = method(self, *args, **kwargs)
setattr(self, cache_dict_name, {key: result})
return result
except KeyError:
result = method(self, *args, **kwargs)
getattr(self, cache_dict_name)[key] = result
return result
def clear_cache(self):
delattr(self, cache_dict_name)
if sys.version_info >= (2, 5):
from functools import update_wrapper
new_wrapper = update_wrapper(wrapper, method)
new_wrapper.clear_cache = clear_cache
return new_wrapper
示例6: memoize_method_nested
def memoize_method_nested(inner):
"""Adds a cache to a function nested inside a method. The cache is attached
to *memoize_cache_context* (if it exists) or *self* in the outer (method)
namespace.
Requires Python 2.5 or newer.
"""
from functools import wraps
cache_dict_name = intern("_memoize_inner_dic_%s_%s_%d"
% (inner.__name__, inner.__code__.co_filename,
inner.__code__.co_firstlineno))
from inspect import currentframe
outer_frame = currentframe().f_back
cache_context = outer_frame.f_locals.get("memoize_cache_context")
if cache_context is None:
cache_context = outer_frame.f_locals.get("self")
try:
cache_dict = getattr(cache_context, cache_dict_name)
except AttributeError:
cache_dict = {}
setattr(cache_context, cache_dict_name, cache_dict)
@wraps(inner)
def new_inner(*args):
try:
return cache_dict[args]
except KeyError:
result = inner(*args)
cache_dict[args] = result
return result
return new_inner
示例7: realize_conditional
def realize_conditional(self, node, context_cond=None):
scope = self.scope_stack[-1]
cond_name = intern("loopy_cond%d" % self.condition_id_counter)
self.condition_id_counter += 1
assert cond_name not in scope.type_map
scope.type_map[cond_name] = np.int32
from pymbolic import var
cond_var = var(cond_name)
self.add_expression_instruction(
cond_var, self.parse_expr(node, node.expr))
cond_expr = cond_var
if context_cond is not None:
from pymbolic.primitives import LogicalAnd
cond_expr = LogicalAnd((cond_var, context_cond))
self.conditions_data.append((context_cond, cond_var))
else:
self.conditions_data.append((None, cond_var))
self.conditions.append(cond_expr)
示例8: memoize_method
def memoize_method(method):
"""Supports cache deletion via ``method_name.clear_cache(self)``.
.. note::
*clear_cache* support requires Python 2.5 or newer.
"""
return memoize_on_first_arg(method, intern("_memoize_dic_"+method.__name__))
示例9: make_unique_instruction_id
def make_unique_instruction_id(self, insns=None, based_on="insn",
extra_used_ids=set()):
if insns is None:
insns = self.instructions
used_ids = set(insn.id for insn in insns) | extra_used_ids
for id_str in generate_unique_names(based_on):
if id_str not in used_ids:
return intern(id_str)
示例10: __call__
def __call__(self, based_on="id"):
based_on = self.forced_prefix + based_on
for var_name in generate_unique_names(based_on):
if not self.is_name_conflicting(var_name):
break
var_name = intern(var_name)
self.existing_names.add(var_name)
return var_name
示例11: __init__
def __init__(self, **kwargs):
kwargs["name"] = intern(kwargs.pop("name"))
dtype = kwargs.pop("dtype", None)
if isinstance(dtype, np.dtype):
from loopy.tools import PicklableDtype
kwargs["picklable_dtype"] = PicklableDtype(dtype)
else:
kwargs["picklable_dtype"] = dtype
Record.__init__(self, **kwargs)
示例12: parse_if_necessary
def parse_if_necessary(insn, defines):
if isinstance(insn, InstructionBase):
yield insn.copy(
id=intern(insn.id) if isinstance(insn.id, str) else insn.id,
insn_deps=frozenset(intern(dep) for dep in insn.insn_deps),
groups=frozenset(intern(grp) for grp in insn.groups),
conflicts_with_groups=frozenset(
intern(grp) for grp in insn.conflicts_with_groups),
forced_iname_deps=frozenset(
intern(iname) for iname in insn.forced_iname_deps),
predicates=frozenset(
intern(pred) for pred in insn.predicates),
), []
return
elif not isinstance(insn, str):
raise TypeError("Instructions must be either an Instruction "
"instance or a parseable string. got '%s' instead."
% type(insn))
for insn in insn.split("\n"):
comment_start = insn.find("#")
if comment_start >= 0:
insn = insn[:comment_start]
insn = insn.strip()
if not insn:
continue
for sub_insn in expand_defines(insn, defines, single_valued=False):
yield parse_insn(sub_insn)
示例13: cursor_to_dict
def cursor_to_dict(cursor):
"""Converts a SQL cursor into an list of dicts.
Args:
cursor : The DBAPI cursor which has executed a query.
Returns:
A list of dicts where the key is the column header.
"""
col_headers = list(intern(str(column[0])) for column in cursor.description)
results = list(
dict(zip(col_headers, row)) for row in cursor
)
return results
示例14: __setstate__
def __setstate__(self, val):
super(InstructionBase, self).__setstate__(val)
from loopy.tools import intern_frozenset_of_ids
if self.id is not None: # pylint:disable=access-member-before-definition
self.id = intern(self.id)
self.depends_on = intern_frozenset_of_ids(self.depends_on)
self.groups = intern_frozenset_of_ids(self.groups)
self.conflicts_with_groups = (
intern_frozenset_of_ids(self.conflicts_with_groups))
self.within_inames = (
intern_frozenset_of_ids(self.within_inames))
示例15: intern_string
def intern_string(string):
"""Takes a (potentially) unicode string and interns it if it's ascii
"""
if string is None:
return None
try:
if six.PY2:
string = string.encode("ascii")
return intern(string)
except UnicodeEncodeError:
return string