Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 7 – Style Guide for C Code

Author:
Guido van Rossum <guido at python.org>, Barry Warsaw <barry at python.org>
Status:
Active
Type:
Process
Created:
05-Jul-2001
Post-History:


Table of Contents

Introduction

This document gives coding conventions for the C code comprising the Cimplementation of Python. Please see the companion informational PEPdescribingstyle guidelines for Python code.

Note, rules are there to be broken. Two good reasons to break aparticular rule:

  1. When applying the rule would make the code less readable, even forsomeone who is used to reading code that follows the rules.
  2. To be consistent with surrounding code that also breaks it (maybefor historic reasons) – although this is also an opportunity toclean up someone else’s mess (in true XP style).

C standards

Follow the following standards.For features that aren’t in the relevant standard, use CPython-specificwrappers (for example:_Py_atomic_store_int32,Py_ALWAYS_INLINE,Py_ARITHMETIC_RIGHT_SHIFT;_Py_ALIGNED_DEF in public headers).When adding such wrappers, try to make them easy to adjust for unsupportedcompilers.

  • Python 3.11 and newer versions use C11 withoutoptional features.The public C API should be compatible with C99 and C++.

    (As a reminder to any users reading this: this PEP is astyle guide; theserules are there to be broken.)

  • Python 3.6 to 3.10 use C89 with several select C99 features:
    • Standard integer types in<stdint.h> and<inttypes.h>. Werequire the fixed width integer types.
    • staticinline functions
    • designated initializers (especially nice for type declarations)
    • intermingled declarations
    • booleans
    • C++-style line comments
  • Python versions before 3.6 used ANSI/ISO standard C (the 1989 versionof the standard). This meant, amongst many other things, that alldeclarations were at the top of a block.

Common C code conventions

  • Don’t use compiler-specific extensions, such as those of GCC or MSVC.For example, don’t write multi-line strings without trailing backslashes.
  • All function declarations and definitions must use full prototypes.That is, specify the types of all arguments and use(void) to declarefunctions with no arguments.
  • No compiler warnings with major compilers (gcc, VC++, a few others).
  • staticinline functions should be preferred over macros in newcode.

Code lay-out

  • Use 4-space indents and no tabs at all.
  • No line should be longer than 79 characters. If this and theprevious rule together don’t give you enough room to code, your codeis too complicated – consider using subroutines.
  • No line should end in whitespace. If you think you need significanttrailing whitespace, think again – somebody’s editor might deleteit as a matter of routine.
  • Function definition style: function name in column 1, outermostcurly braces in column 1, blank line after local variabledeclarations.
    staticintextra_ivars(PyTypeObject*type,PyTypeObject*base){intt_size=PyType_BASICSIZE(type);intb_size=PyType_BASICSIZE(base);assert(t_size>=b_size);/* type smaller than base! */...return1;}
  • Code structure: one space between keywords likeif,for andthe following left paren; no spaces inside the paren; braces arerequired everywhere, even where C permits them to be omitted, but donot add them to code you are not otherwise modifying. All new Ccode requires braces. Braces should be formatted as shown:
    if(mro!=NULL){...}else{...}
  • The return statement shouldnot get redundant parentheses:
    return(albatross);/* incorrect */

    Instead:

    returnalbatross;/* correct */
  • Function and macro call style:foo(a,b,c) – no space beforethe open paren, no spaces inside the parens, no spaces beforecommas, one space after each comma.
  • Always put spaces around assignment, Boolean and comparisonoperators. In expressions using a lot of operators, add spacesaround the outermost (lowest-priority) operators.
  • Breaking long lines: if you can, break after commas in the outermostargument list. Always indent continuation lines appropriately,e.g.:
    PyErr_Format(PyExc_TypeError,"cannot create '%.100s' instances",type->tp_name);
  • When you break a long expression at a binary operator, bracesshould be formatted as shown:
    if(type->tp_dictoffset!=0&&base->tp_dictoffset==0&&type->tp_dictoffset==b_size&&(size_t)t_size==b_size+sizeof(PyObject*)){return0;/* "Forgive" adding a __dict__ only */}

    It’s OK to put operators at ends of lines, especially to beconsistent with surrounding code.(SeePEP 8 for a longer discussion.)

  • Vertically align line continuation characters in multi-line macros.
  • Macros intended to be used as a statement should use thedo{...}while(0) macro idiom,without a final semicolon.Example:
    #define ADD_INT_MACRO(MOD, INT)                                   \    do {                                                          \        if (PyModule_AddIntConstant((MOD), (#INT), (INT)) < 0) {  \            goto error;                                           \        }                                                         \    } while (0)// To be used like a statement with a semicolon:ADD_INT_MACRO(m,SOME_CONSTANT);
  • #undef file local macros after use.
  • Put blank lines around functions, structure definitions, and majorsections inside functions.
  • Comments go before the code they describe.
  • All functions and global variables should be declared static unlessthey are to be part of a published interface.
  • For external functions and variables, we always have a declarationin an appropriate header file in the “Include” directory, which usesthePyAPI_FUNC() macro andPyAPI_DATA() macro, like this:
    PyAPI_FUNC(PyObject*)PyObject_Repr(PyObject*);PyAPI_DATA(PyTypeObject)PySuper_Type;

Naming conventions

  • Use aPy prefix for public functions; never for staticfunctions. ThePy_ prefix is reserved for global serviceroutines likePy_FatalError; specific groups of routines(e.g. specific object type APIs) use a longer prefix,e.g.PyString_ for string functions.
  • Public functions and variables use MixedCase with underscores, likethis:PyObject_GetAttr,Py_BuildValue,PyExc_TypeError.
  • Occasionally an “internal” function has to be visible to the loader;we use the_Py prefix for this, e.g.:_PyObject_Dump.
  • Macros should have a MixedCase prefix and then use upper case, forexample:PyString_AS_STRING,Py_PRINT_RAW.
  • Macro parameters should useALL_CAPS style,so they are easily distinguishable from C variables and struct members.

Documentation Strings

  • Use thePyDoc_STR() orPyDoc_STRVAR() macro for docstringsto support building Python without docstrings (./configure--without-doc-strings).
  • The first line of each function docstring should be a “signatureline” that gives a brief synopsis of the arguments and return value.For example:
    PyDoc_STRVAR(myfunction__doc__,"myfunction(name, value) -> bool\n\n\Determine whether name and value make a valid pair.");

    Always include a blank line between the signature line and the textof the description.

    If the return value for the function is alwaysNone (because thereis no meaningful return value), do not include the indication of thereturn type.

  • When writing multi-line docstrings, be sure to always use backslashcontinuations, as in the example above, or string literalconcatenation:
    PyDoc_STRVAR(myfunction__doc__,"myfunction(name, value) -> bool\n\n""Determine whether name and value make a valid pair.");

    Though some C compilers accept string literals without either:

    /* BAD -- don't do this! */PyDoc_STRVAR(myfunction__doc__,"myfunction(name, value) -> bool\n\nDeterminewhethernameandvaluemakeavalidpair.");

    not all do; the MSVC compiler is known to complain about this.

Copyright

This document has been placed in the public domain.


Source:https://github.com/python/peps/blob/main/peps/pep-0007.rst

Last modified:2025-08-27 10:48:57 GMT


[8]ページ先頭

©2009-2025 Movatter.jp