我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用keyword.kwlist()。
def scanvars(reader, frame, locals): """Scan one logical line of Python and look up values of variables used.""" vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__ for ttype, token, start, end, line in tokenize.generate_tokens(reader): if ttype == tokenize.NEWLINE: break if ttype == tokenize.NAME and token not in keyword.kwlist: if lasttoken == '.': if parent is not __UNDEF__: value = getattr(parent, token, __UNDEF__) vars.append((prefix + token, prefix, value)) else: where, value = lookup(token, frame, locals) vars.append((token, where, value)) elif token == '.': prefix += lasttoken + '.' parent = value else: parent, prefix = None, '' lasttoken = token return vars
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] n = len(text) for word in keyword.kwlist: if word[:n] == text: matches.append(word) for nspace in [__builtin__.__dict__, self.namespace]: for word, val in nspace.items(): if word[:n] == text and word != "__builtins__": matches.append(self._callable_postfix(val, word)) return matches
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defines in __main__ that match. """ import keyword matches = [] for list in [keyword.kwlist, builtins.__dict__.keys(), self.ns.keys()]: for word in list: if word.startswith(text) and word != "__builtins__": matches.append(word) return matches
def test_build_db(): reserved_list = keyword.kwlist add_reserveds('Python', reserved_list) # Test some python keywords reserved_row = get_reserved_by_name('from') assert reserved_row.name == 'from' reserved_row = get_reserved_by_name('with') assert reserved_row.name == 'with' reserved_row = get_reserved_by_name('class') assert reserved_row.name == 'class' with pytest.raises(AssertionError): assert reserved_row.name == 'junk'
def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(builtins) if not name.startswith('_') and \ name not in keyword.kwlist] # self.file = open("file") : # 1st 'file' colorized normal, 2nd as builtin, 3rd as string builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) sqstring = r"(\b[rRbB])?'[^'\\\n]*(\\.[^'\\\n]*)*'?" dqstring = r'(\b[rRbB])?"[^"\\\n]*(\\.[^"\\\n]*)*"?' sq3string = r"(\b[rRbB])?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" dq3string = r'(\b[rRbB])?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) return kw + "|" + builtin + "|" + comment + "|" + string +\ "|" + any("SYNC", [r"\n"])
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] n = len(text) for word in keyword.kwlist: if word[:n] == text: matches.append(word) for nspace in [builtins.__dict__, self.namespace]: for word, val in nspace.items(): if word[:n] == text and word != "__builtins__": matches.append(self._callable_postfix(val, word)) return matches
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] seen = {"__builtins__"} n = len(text) for word in keyword.kwlist: if word[:n] == text: seen.add(word) matches.append(word) for nspace in [self.namespace, builtins.__dict__]: for word, val in nspace.items(): if word[:n] == text and word not in seen: seen.add(word) matches.append(self._callable_postfix(val, word)) return matches
def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(__builtin__) if not name.startswith('_')] # We don't know whether "print" is a function or a keyword, # so we always treat is as a keyword (the most common case). builtinlist.remove('print') # self.file = file("file") : # 1st 'file' colorized normal, 2nd as builtin, 3rd as string builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) stringprefix = r"(\br|u|ur|R|U|UR|Ur|uR|b|B|br|Br|bR|BR)?" sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?" dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?' sq3string = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" dq3string = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) return kw + "|" + builtin + "|" + comment + "|" + string +\ "|" + any("SYNC", [r"\n"])
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] seen = {"__builtins__"} n = len(text) for word in keyword.kwlist: if word[:n] == text: seen.add(word) matches.append(word) for nspace in [self.namespace, __builtin__.__dict__]: for word, val in nspace.items(): if word[:n] == text and word not in seen: seen.add(word) matches.append(self._callable_postfix(val, word)) return matches
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ matches = [] seen = {"__builtins__"} n = len(text) if keyword: for word in keyword.kwlist: if word[:n] == text: seen.add(word) matches.append(word) for nspace in [self.namespace, builtin_dir]: for word, val in nspace.items(): if word[:n] == text and word not in seen: seen.add(word) matches.append(self._callable_postfix(val, word)) return matches
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match. """ matches = [] match_append = matches.append n = len(text) for lst in [keyword.kwlist, builtin_mod.__dict__.keys(), self.namespace.keys(), self.global_namespace.keys()]: for word in lst: if word[:n] == text and word != "__builtins__": match_append(word) return [cast_unicode_py2(m) for m in matches]
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defines in __main__ that match. """ import keyword matches = [] n = len(text) for list in [keyword.kwlist, __builtin__.__dict__.keys(), self.ns.keys()]: for word in list: if word[:n] == text and word != "__builtins__": matches.append(word) return matches
def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(builtins) if not name.startswith('_') and \ name not in keyword.kwlist] # self.file = open("file") : # 1st 'file' colorized normal, 2nd as builtin, 3rd as string builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) stringprefix = r"(\br|u|ur|R|U|UR|Ur|uR|b|B|br|Br|bR|BR|rb|rB|Rb|RB)?" sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?" dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?' sq3string = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" dq3string = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) return kw + "|" + builtin + "|" + comment + "|" + string +\ "|" + any("SYNC", [r"\n"])
def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(__builtin__) if not name.startswith('_')] # self.file = file("file") : # 1st 'file' colorized normal, 2nd as builtin, 3rd as string builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) stringprefix = r"(\br|u|ur|R|U|UR|Ur|uR|b|B|br|Br|bR|BR)?" sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?" dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?' sq3string = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" dq3string = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) return kw + "|" + builtin + "|" + comment + "|" + string +\ "|" + any("SYNC", [r"\n"])
def main(): print 'Welcome to the Identifier Checker v2.0' myInput = raw_input('Identifier to test? ').strip() if len(myInput) == 0: print "ERROR: no identifier candidate entered" return if myInput in kwlist: print "ERROR: %r is a keyword" % myInput return alnums = ALPHAS + NUMS for i, c in enumerate(myInput): if i == 0 and c not in ALPHAS: print 'ERROR: first symbol must be alphabetic' break if c not in alnums: print 'ERROR: remaining symbols must be alphanumeric' break else: print "okay as an identifier"
def get_invalid_variable_names(): """ Get a list of invalid variable names for use in sfc_model equations. Includes mathematical operators in module 'math'. Cannot use 'k', as that is the discrete time axis step variable. :return: list """ internal = ['self', 'None', 'k'] kw = keyword.kwlist if is_python_3: built = dir(builtins) else: # pragma: no cover built = dir(__builtin__) out = internal + kw + built + dir(math) return list(out)
def get_invalid_tokens(): """ Get a list of invalid tokens that can be used inside sfc_model equations. :return: list """ internal = ['self', 'None'] kw = keyword.kwlist if is_python_3: built = dir(builtins) else: # pragma: no cover built = dir(__builtin__) out = internal + kw + built # Need to add back in some semi-mathematical operations good_tokens = ('float', 'max', 'min', 'sum', 'pow', 'abs', 'round', 'pow') out = (x for x in out if x not in good_tokens) return list(out)
def reset_dict(self): env.sos_dict = WorkflowDict() env.parameter_vars.clear() env.config.update(self.config) env.sos_dict.set('__null_func__', __null_func__) env.sos_dict.set('__args__', self.args) # initial values env.sos_dict.set('SOS_VERSION', __version__) env.sos_dict.set('__step_output__', []) # load configuration files load_config_files(self.config['config_file']) SoS_exec('import os, sys, glob', None) SoS_exec('from sos.runtime import *', None) self._base_symbols = set(dir(__builtins__)) | set(env.sos_dict['sos_symbols_']) | set(keyword.kwlist) # if users use sos_run, the "scope" of the step goes beyong names in this step # so we cannot save signatures for it. self._base_symbols -= {'dynamic', 'sos_run'} if isinstance(self.args, dict): for key, value in self.args.items(): if not key.startswith('__'): env.sos_dict.set(key, value)
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] seen = {"__builtins__"} n = len(text) for word in keyword.kwlist: if word[:n] == text: seen.add(word) if word in {'finally', 'try'}: word = word + ':' elif word not in {'False', 'None', 'True', 'break', 'continue', 'pass', 'else'}: word = word + ' ' matches.append(word) for nspace in [self.namespace, builtins.__dict__]: for word, val in nspace.items(): if word[:n] == text and word not in seen: seen.add(word) matches.append(self._callable_postfix(val, word)) return matches
def _canonicalize_kwargs(self, kwargs): arguments = {} for k, v in kwargs.items(): if k[0] == '_' and k[1:] in keyword.kwlist: k = k[1:] arguments[k] = v return arguments
def _isidentifier(string): if string in keyword.kwlist: return False return regex.match(string)
def _mangle_name(self, name): if name in keyword.kwlist: return name + '_' return name