本文整理汇总了Python中keyword.iskeyword方法的典型用法代码示例。如果您正苦于以下问题:Python keyword.iskeyword方法的具体用法?Python keyword.iskeyword怎么用?Python keyword.iskeyword使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keyword
的用法示例。
在下文中一共展示了keyword.iskeyword方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dekeywordify
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def dekeywordify(name):
'''
Add an underscore to names that are keywords
Parameters
----------
name : string
The string to check against keywords
Returns
-------
string
Name changed to avoid keywords
'''
if keyword.iskeyword(name):
return name + '_'
return name
示例2: test_assign_complex_homogeneous
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def test_assign_complex_homogeneous(variables_dict):
"""test whether visitors properly set the type constraint of the a assign node representing a multi-target-assign
with a homogeneous list as the value.
"""
for variable_name in variables_dict:
assume(not iskeyword(variable_name))
program = ("x = ["
+ ", ".join([repr(value) for value in variables_dict.values()])
+ "]\n"
+ ", ".join(variables_dict.keys())
+ " = x")
module, typeinferrer = cs._parse_text(program)
ass_node = list(module.nodes_of_class(astroid.Assign))[0]
for variable_name in variables_dict:
var_tvar = module.type_environment.lookup_in_env(variable_name)
assert typeinferrer.type_constraints.resolve(var_tvar).getValue() == ass_node.value.elts[0].inf_type.getValue()
示例3: _check_common
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def _check_common(self, name, type_of_name):
# tests that are common to both field names and the type name
if len(name) == 0:
raise ValueError('{0} names cannot be zero '
'length: {1!r}'.format(type_of_name, name))
if _PY2:
if not all(c.isalnum() or c=='_' for c in name):
raise ValueError('{0} names can only contain '
'alphanumeric characters and underscores: '
'{1!r}'.format(type_of_name, name))
if name[0].isdigit():
raise ValueError('{0} names cannot start with a '
'number: {1!r}'.format(type_of_name, name))
else:
if not name.isidentifier():
raise ValueError('{0} names names must be valid '
'identifiers: {1!r}'.format(type_of_name, name))
if _iskeyword(name):
raise ValueError('{0} names cannot be a keyword: '
'{1!r}'.format(type_of_name, name))
示例4: _check_related_name_is_valid
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def _check_related_name_is_valid(self):
import keyword
related_name = self.remote_field.related_name
if related_name is None:
return []
is_valid_id = True
if keyword.iskeyword(related_name):
is_valid_id = False
if not related_name.isidentifier():
is_valid_id = False
if not (is_valid_id or related_name.endswith('+')):
return [
checks.Error(
"The name '%s' is invalid related_name for field %s.%s" %
(self.remote_field.related_name, self.model._meta.object_name,
self.name),
hint="Related name must be a valid Python identifier or end with a '+'",
obj=self,
id='fields.E306',
)
]
return []
示例5: identify
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def identify(str):
"""Turn any string into an identifier:
- replace space by _
- replace other illegal chars by _xx_ (hex code)
- append _ if the result is a python keyword
"""
if not str:
return "empty_ae_name_"
rv = ''
ok = string.ascii_letters + '_'
ok2 = ok + string.digits
for c in str:
if c in ok:
rv = rv + c
elif c == ' ':
rv = rv + '_'
else:
rv = rv + '_%02.2x_'%ord(c)
ok = ok2
if keyword.iskeyword(rv):
rv = rv + '_'
return rv
# Call the main program
示例6: mk_bitstruct
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def mk_bitstruct( cls_name, fields, *, namespace=None, add_init=True,
add_str=True, add_repr=True, add_hash=True ):
# copy namespace since will mutate it
namespace = {} if namespace is None else namespace.copy()
# We assume fields is a dictionary and thus there won't be duplicate
# field names. So we only check if the field names are indeed strings
# and that they are not keywords.
annos = {}
for name, f in fields.items():
if not isinstance( name, str ) or not name.isidentifier():
raise TypeError( f'Field name {name!r} is not a valid identifier!' )
if keyword.iskeyword( name ):
raise TypeError( f'Field name {name!r} is a keyword!' )
annos[ name ] = f
namespace['__annotations__'] = annos
cls = types.new_class( cls_name, (), {}, lambda ns: ns.update( namespace ) )
return bitstruct( cls, add_init=add_init, add_str=add_str,
add_repr=add_repr, add_hash=add_hash )
示例7: buildattributestring
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def buildattributestring(self, attr):
"""
Builds the attribute string for the object creation
attr is a dict containing name value pairs of the attribute and value
"""
if not isinstance(attr, dict):
attr = dict()
parmlist = []
for k, v in attr.items():
if k not in self.EXCLUDEATTR:
# any properly formed xml/json should have keywords already
# escaped however this is just a sanity check. also, it
# misses 'to' which is not a keyword in python, but is
# treated as such in pymeta oh well
if keyword.iskeyword(k):
k += '_'
v = repr(v)
parmlist.append('%s=%s' % (k, v))
attribstr = ', '.join(parmlist)
return attribstr
示例8: register_resource
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def register_resource(self, resource):
name = resource.name
if name is not None:
parts = self.NAME_SPLIT_RE.split(name)
for part in parts:
if not part.isidentifier() or keyword.iskeyword(part):
raise ValueError('Incorrect route name {!r}, '
'the name should be a sequence of '
'python identifiers separated '
'by dash, dot or column'.format(name))
if name in self._named_resources:
raise ValueError('Duplicate {!r}, '
'already handled by {!r}'
.format(name, self._named_resources[name]))
self._named_resources[name] = resource
self._resources.append(resource)
示例9: value
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def value(self, value):
value_parts = value.split('.')
for value_part in value_parts:
if keyword.iskeyword(value_part):
raise ValueError('%s is a reserved keyword.' % value_part)
# If we have too many children, cut the list down to size.
# pylint: disable=attribute-defined-outside-init
self._children = self._children[:len(value_parts)*2-1]
# Update child nodes.
for child, value_part in itertools.izip_longest(
self._children[::2], value_parts):
if child:
# Modify existing children. This helps preserve comments and spaces.
child.value = value_part
else:
# Add children as needed.
self._children.append(snippet.TokenSnippet.Create(token.DOT, '.'))
self._children.append(
snippet.TokenSnippet.Create(token.NAME, value_part))
示例10: alias
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def alias(self, value):
if keyword.iskeyword(value):
raise ValueError('%s is a reserved keyword.' % value)
if value:
# pylint: disable=access-member-before-definition
if len(self.children) < 3:
# If we currently have no alias, add one.
# pylint: disable=access-member-before-definition
self.children.append(
snippet.TokenSnippet.Create(token.NAME, 'as', (0, 1)))
# pylint: disable=access-member-before-definition
self.children.append(
snippet.TokenSnippet.Create(token.NAME, value, (0, 1)))
else:
# We already have an alias. Just update the value.
# pylint: disable=access-member-before-definition
self.children[2].value = value
else:
# Removing the alias. Strip the "as foo".
self.children = [self.children[0]] # pylint: disable=line-too-long, attribute-defined-outside-init
示例11: _is_valid_name
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def _is_valid_name(name):
'''
check if a string is a valid identifier in Python
'''
return name.isidentifier() and not iskeyword(name)
示例12: legal_name
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def legal_name(name, is_param_name=False):
"""
If this name is a legal property name.
is_param_name determines if this name in the name of a property, or a
param_name. See the constructor documentation for more information.
The rules are as follows:
* Cannot start with an underscore.
This is for internal arguments, namely _engine (for the step module).
* Cannot be 'self'
This is to avoid conflict with recipe modules, which use the name self.
* Cannot be a python keyword
"""
if name.startswith('_'):
return False
if name in ('self',):
return False
if keyword.iskeyword(name):
return False
regex = r'^[a-zA-Z][a-zA-Z0-9_]*$' if is_param_name else (
r'^[a-zA-Z][.\w-]*$')
return bool(re.match(regex, name))
示例13: _get_renamed_namedtuple_atributes
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def _get_renamed_namedtuple_atributes(field_names):
names = list(field_names)
seen = set()
for i, name in enumerate(field_names):
if (not all(c.isalnum() or c == '_' for c in name) or keyword.iskeyword(name)
or not name or name[0].isdigit() or name.startswith('_') or name in seen):
names[i] = '_%d' % i
seen.add(name)
return tuple(names)
示例14: _opening_bracket
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def _opening_bracket(self, tokens, i):
self._push_token(tokens[i][1], i)
# Special case: ignore slices
if tokens[i][1] == '[' and tokens[i+1][1] == ':':
return
if (i > 0 and (tokens[i-1][0] == tokenize.NAME and
not (keyword.iskeyword(tokens[i-1][1]))
or tokens[i-1][1] in _CLOSING_BRACKETS)):
self._check_space(tokens, i, (_MUST_NOT, _MUST_NOT))
else:
self._check_space(tokens, i, (_IGNORE, _MUST_NOT))
示例15: whitespace_before_parameters
# 需要导入模块: import keyword [as 别名]
# 或者: from keyword import iskeyword [as 别名]
def whitespace_before_parameters(logical_line, tokens):
r"""Avoid extraneous whitespace.
Avoid extraneous whitespace in the following situations:
- before the open parenthesis that starts the argument list of a
function call.
- before the open parenthesis that starts an indexing or slicing.
Okay: spam(1)
E211: spam (1)
Okay: dict['key'] = list[index]
E211: dict ['key'] = list[index]
E211: dict['key'] = list [index]
"""
prev_type, prev_text, __, prev_end, __ = tokens[0]
for index in range(1, len(tokens)):
token_type, text, start, end, __ = tokens[index]
if (token_type == tokenize.OP and
text in '([' and
start != prev_end and
(prev_type == tokenize.NAME or prev_text in '}])') and
# Syntax "class A (B):" is allowed, but avoid it
(index < 2 or tokens[index - 2][1] != 'class') and
# Allow "return (a.foo for a in range(5))"
not keyword.iskeyword(prev_text)):
yield prev_end, "E211 whitespace before '%s'" % text
prev_type = token_type
prev_text = text
prev_end = end