¿Es posible obtener una lista de palabras clave en Python?

I'd like to get a list of all of Pythons keywords as strings. It would also be rather nifty if I could do a similar thing for built in functions.

Algo como esto :

import syntax
print syntax.keywords
# prints ['print', 'if', 'for', etc...]

preguntado el 09 de marzo de 12 a las 22:03

Anyway: See the Python language documentation: Simple statements, Compund statements y Palabras clave. -

7 Respuestas

Preguntaste sobre declaraciones, while showing las palabras claves in your output example.

Si usted está buscando las palabras claves, they're all listed in the keyword módulo:

>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',
 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',
 'while', 'with', 'yield']

Desde el keyword.kwlist doctor:

Sequence containing all the keywords defined for the interpreter. If any keywords are defined to only be active when particular __future__ statements are in effect, these will be included as well.

respondido 09 mar '12, 23:03

Built-in functions are NO declaraciones. Una ambiental is when you make a declaration such as defining a function and begining with the keyword def and have one or more clauses, etc. He asked about the built-in identifiers NOT about declaraciones as you indicated. From his output only if y for son las palabras claves, print is just a built-in identifier. Also the example is not complete because you're only listing the las palabras claves without listing the built-in identifiers (functions) as he asked. I think you should amend the answer to include those as well. - marius mucenicu

Also you should make the answer even more granular if you'd want it to be complete because print means different things in Python2 y en Python3. En Python3 it won't show up as it does in your example because, as I've indicated in my aforementioned answer, it's not a keyword anymore (but merely a built-in identifier). Also, since he asked about the built-in funciones, estos need to be included. Now, I know this thread has been here for quite some time but this might help future readers. - marius mucenicu

Por qué Un nuevo, init, self, cls, etc. are missing, and how to list them too? - defoe

The built-in functions are in a module called __builtins__, asi que:

dir(__builtins__)

respondido 09 mar '12, 23:03

If this code is in an imported module, I think it would be __builtins__.keys() instead. Or in Python 3, import builtins luego dir(builtins) regardless of module. docs.python.org/3/reference/executionmodel.html "By default, when in the __main__ módulo, __builtins__ is the built-in module builtins; when in any other module, __builtins__ is an alias for the dictionary of the builtins module itself." - S. Kirby

The closest approach I can think of is the following:

from keyword import kwlist
print kwlist

El keyword module is generated automatically. For other things related to Python parsing from Python, check the servicios de idiomas conjunto de módulos.

Regarding listing the builtins I'm not clear if you're asking for items in the __builtin__ module or functions in that package that are implemented directly in the CPython interpreter:

import __builtin__ as B
from inspect import isbuiltin

# You're either asking for this:
print [name for name in dir(B) if isbuiltin(getattr(B, name))]

# Or this:
print dir(B)

respondido 09 mar '12, 23:03

O tu puedes import builtins:

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
>>> 

OR (this does not contain errors and stuff with __ beside them):

>>> help('keywords')

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not                 
class               from                or                  
continue            global              pass                

Respondido 27 ago 18, 06:08

>>> help()

help> keywords

Here is a list of the Python keywords. Enter any keyword to get more help.

False def if raise

None del import return

True elif in try

and else is while

as except lambda with

assert finally nonlocal yield

break for not

class from or

continue global pass

Respondido el 09 de diciembre de 17 a las 18:12

Get a list of all of Pythons keywords

  • 2018-06-07

The standard keyword module is generated automatically (a Quine) Quine (informática)

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>> len(keyword.kwlist)
33

I categorized the keywords for further reference.

keywords_33=[
    ('file_2', ['with', 'as']),
    ('module_2', ['from', 'import']),
    ('constant_3', {'bool': ['False', 'True'], 
                    'none': ['None']}),
    ('operator_5',
            {'logic': ['and', 'not', 'or'],
            'relation': ['is', 'in']}),
    ('class_1', ['class']),
    ('function_7',
            ['lambda','def','pass',
            'global','nonlocal',
            'return','yield']),
    ('loop_4', ['while', 'for', 'continue', 'break']),
    ('condition_3', ['if', 'elif', 'else']),
    ('exception_4', ['try', 'raise','except', 'finally']),
    ('debug_2', ['del','assert']),
]

Respondido el 07 de junio de 18 a las 02:06

You do not need to import syntax, but you still have to import keyword.

>>> import keyword
>>> print(keyword.kwlist)

el resultado es:

['False', 'None', 
'True', 'and', 'as', 'assert', 
'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 
'raise', 'return', 'try', 'while', 'with', 'yield']

contestado el 26 de mayo de 20 a las 10:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.