Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What order should these elements be in a Python module?

Tags:

python

When present, what is the order that these elements should be declared in a Python module?

  • Hash bang (#!/usr/bin/env python)
  • Encoding (# coding: utf-8)
  • Future imports (from __future__ import unicode_literals, ...)
  • Docstring

If declared last, will the docstring work in a call help(module)?

like image 428
augustomen Avatar asked Feb 25 '26 04:02

augustomen


1 Answers

  1. Hash bang. The kernel literally looks at the first two bytes of the file to see if they are equal to #!, so it won't work otherwise.

  2. Encoding. According to the Python Language Reference it must be "on the first or second line".

  3. Docstring. According to PEP 257, a docstring is "a string literal that occurs as the first statement in a module, function, class, or method definition", so it cannot go after any import statements. You can see for yourself that help(module) no longer reports your docstring if you put it in a different place.

  4. Future imports, because they cannot go before any of the above.

like image 111
Thomas Avatar answered Feb 26 '26 19:02

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!