Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is "class ClassName : pass" in Python?

In this tutorial, an entire class is defined as class DontAppend: pass. According to this Q&A on Stack Overflow, pass defines the class.

The consensus from Google, however, is that pass is a statement. I’ve never seen statements define a class other than within definitions of class methods.

As a statement, pass also doesn’t define a named class attribute/property.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Since pass doesn’t serve to define a method or an attribute, how does it actually define the class? Is this just a special convention, solely for defining an empty class?

>Solution :

Here is the specification for the syntax of the python class definition statement:

classdef    ::=  [decorators] "class" classname [inheritance] ":" suite
inheritance ::=  "(" [argument_list] ")"
classname   ::=  identifier

So, as you can see, everything after the colon : is part of a "suite" (generally, this suite is called "the class body", or the "body of the class definition statement").

Here is the specification for a suite:

suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

So basically, a "suite" is any series of statements. Here is a valid class definition:

>>> class Foo:
...     print("inside the class body")
...
inside the class body
>>>

(Note, the body is executed, a class definition is executable code). So any valid Python statement can go in a class body. So what is pass then? Here is the spec:

pass_stmt ::= "pass"

pass is a null operation — when it is executed, nothing happens. It is
useful as a placeholder when a statement is required syntactically,
but no code needs to be executed, for example:

def f(arg): pass # a function that does nothing (yet)

class C: pass # a class with no methods (yet)

So some statement is required in the class body, you cannot just leave it blank if you want the class to be empty. So in that case, you can simply use pass.

Note, if you want more nitty-gritty details about how a class definition statement is executed and how that namespace becomes the namespace of the class object, this link to the data model will be useful

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading