2

I was asked this question in a recent interview. And I know super is the way to get the super class, pass has no effect but to close a function or class declaration, yield is used in generator. But I have no idea how they are implemented in Python.

I searched and only get the answer for super: How is super() in Python 3 implemented?, anybody can answer for others?

Community
  • 1
  • 1
Kane Blueriver
  • 4,170
  • 4
  • 29
  • 48
  • 4
    Do you know how compilers work? What a "lexer" and a "parser" do? `pass` and `yield` are implemented there. – Ferdinand Beyer Mar 22 '15 at 08:25
  • 1
    They just compiled (or not in case of `pass`) into specific PVM instructions (in CPython). Also that answer you mention - is CPython code. – myaut Mar 22 '15 at 08:26
  • @FerdinandBeyer No, I don't. :( Can you explain it more detailed? – Kane Blueriver Mar 22 '15 at 08:30
  • @myaut I'm reading that article but seem is not what I pretended. I'm pool with C and lexer, so have learn them first to get this question understand? – Kane Blueriver Mar 22 '15 at 08:35
  • 1
    How these are implemented will depend on the um, implementation. So you need to look at the source code, which could change at any release. Sounds like a daft question unless you are writing your own Python implementation. How they are used is a different question. – cdarke Mar 22 '15 at 09:36
  • 1
    @kxxoling In CPython, the interpreter reads your `.py` files and compiles the code into its own "bytecode" representation that is then executable. The "lexer" is the first component, it will read the Python code and produce a stream of "tokens". If it reads "pass", it will report something like "TK_PASS". These tokens are then consumed by the "parser", who does not care anymore how keywords are spelled, but knows where they are allowed to occur (e.g., that `def return yield` is invalid syntax). Read the Wikipedia articles on "Lexical analysis" and "Parsing" to learn more. – Ferdinand Beyer Mar 22 '15 at 10:27
  • Umm... Seems I have a lot to learn to get the answer of this question. – Kane Blueriver Mar 23 '15 at 15:18

1 Answers1

2

super is not a keyword in python, it's a variable like int or range. Keywords like pass, yield, def, if, ... are consumed by the parser to build an AST (Abstract-Syntax-Tree). You can play with the AST by yourself with the ast-module of python. The AST is then turned in some lower level machine or virtual machine code by the code generator, ready for execution.

Daniel
  • 42,087
  • 4
  • 55
  • 81