Jump to content

Manual:Coding conventions/Python/ja: Difference between revisions

ショートカット: CC/PY  CC/Python
From mediawiki.org
Content deleted Content added
Created page with "厳格な遵守のために、厳格な遵守よりも読みやすさと自明性を目指してください。"
FuzzyBot (talk | contribs)
Updating to match new version of source page
 
(39 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<languages/>
<languages/>
{{Shortcut|CC/PY}}
{{Shortcut|CC/PY|CC/Python}}
{{Development guideline}}
{{Development guideline}}
このページでは、MediaWiki プロジェクトまたはサポート プロジェクトの一部である '''Python''' プロジェクト群の'''コーディング規約'''について説明します。
このページでは、MediaWiki プロジェクトまたはサポート プロジェクトの一部である '''Python''' プロジェクト群の'''コーディング規約'''について説明します。


{{TOCRight}}
{{TOCRight}}
<span id="Preamble"></span>
== 前文 ==
== 前文 ==


Line 10: Line 11:


* 厳格な遵守のために、厳格な遵守よりも読みやすさと自明性を目指してください。
* 厳格な遵守のために、厳格な遵守よりも読みやすさと自明性を目指してください。
* コードは、書かれるよりもはるかに頻繁に読まれます。
* <span lang="en" dir="ltr" class="mw-content-ltr">Code is read much more often than it is written.</span>
* 既存のコードと一貫性を保ちつつ、最善の判断を下してください。 既存のコードを修正するのがそれほど難しくない場合は、[[:ja:WP:BOLD|ページの編集は大胆に]]。
* <span lang="en" dir="ltr" class="mw-content-ltr">Be consistent with existing code, but use your best judgement.</span> <span lang="en" dir="ltr" class="mw-content-ltr">If it isn't too hard to fix up the existing code, WP:BOLD.</span>


<span lang="en" dir="ltr" class="mw-content-ltr">For anything not covered in this document, please refer to [http://www.python.org/dev/peps/pep-0008/ Python Enhancement Proposal 0008] for the general practice.</span>
この文書で網羅されていないものについては、一般的な方法について [http://www.python.org/dev/peps/pep-0008/ Python Enhancement Proposal 0008] を参照してください。
以下の節は、ほとんどの場合、PEP8 の最も一般的に参照される部分の要約です。
<span lang="en" dir="ltr" class="mw-content-ltr">The following sections are for the most part a summary of the most commonly referred to parts of PEP8.</span>

<span id="Python_version"></span>
== Python のバージョン ==


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
The minimum supported version is 2.7, but in special cases it is okay to support older versions.
== Python version ==
</div>
</div>
The minimum supported version is 2.7, but in special cases it is ok to support older versions.


{{note|1=Python 2.7 is no longer maintained [https://pythonclock.org as of 2020].}}
{{note|1=<span lang="en" dir="ltr" class="mw-content-ltr">Python 2.7 is no longer maintained [https://pythonclock.org as of 2020].</span>}}


<div lang="en" dir="ltr" class="mw-content-ltr">
If you have not already, you should change to Python 3 for local development.
If you have not already, you should change to Python 3 for local development.
</div>

<span id="Whitespace"></span>
== 空白類 ==


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
== Whitespace ==
</div>
Lines should be indented with 4 spaces.
Lines should be indented with 4 spaces.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Lines at the end of files should end with a newline, just like every other line in the file.
Lines at the end of files should end with a newline, just like every other line in the file.
</div>

<span lang="en" dir="ltr" class="mw-content-ltr">Try to keep lines under 80 characters long, but aim for readability and obviousness over strict adherence for the sake of strict adherence.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">Shorter lines are just a general side effect of good idiomatic Python - short but properly scoped descriptive names, avoiding [http://stackoverflow.com/questions/4975457/python-preventing-if-staircases staircase code], etc.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">When splitting up lines, pick the most obviously unambiguous method possible for the situation.</span>


<span id="Module_structure"></span>
Try to keep lines under 80 characters long, but aim for readability and obviousness over strict adherence for the sake of strict adherence.
== モジュールの構造 ==
Shorter lines are just a general side effect of good idiomatic python - short but properly scoped descriptive names, avoiding [http://stackoverflow.com/questions/4975457/python-preventing-if-staircases staircase code], etc.
<span lang="en" dir="ltr" class="mw-content-ltr">The standard way to distribute Python modules is to create a <code>setup.py</code> file and leverage a library called "distribute".</span>
When splitting up lines, pick the most obviously unambiguous method possible for the situation.
<span lang="en" dir="ltr" class="mw-content-ltr">There are modules that will generate the structure of a base project for you, a deprecated one is <code>paster create</code> which is no longer maintained.</span>
<span lang="en" dir="ltr" class="mw-content-ltr">A replacement is [https://pypi.python.org/pypi/pythong pythong].</span>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
== Module structure ==
In general module structure should look like this:
</div>
</div>
The standard way to distribute python modules is to create a <code>setup.py</code> file and leverage a library called "distribute".
There are modules that will generate the structure of a base project for you, a deprecated one is <code>paster create</code> which is no longer maintained.
A replacement is [https://pypi.python.org/pypi/pythong pythong].


In general module structure should look like this:
<pre>
<pre>
newproject
newproject
Line 57: Line 68:
</pre>
</pre>


<span id="Imports"></span>
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Imports ===
=== インポート ===
<span lang="en" dir="ltr" class="mw-content-ltr">Within a file it's generally a good idea to organize your imports in some fashion.</span>
</div>
<span lang="en" dir="ltr" class="mw-content-ltr">Typically alphabetical order is favored, but this can become unwieldy when importing a large number of libraries.</span>
Within a file it's generally a good idea to organize your imports in some fashion.
<span lang="en" dir="ltr" class="mw-content-ltr">To help avoid this, it's good to separate out imports in this fashion, with each block separated from the others by an empty line:</span>
Typically alphabetical order is favored, but this can become unwieldy when importing a large number of libraries.
To help avoid this, it's good to separate out imports in this fashion, with each block separated from the others by an empty line:


* Standard library imports
* <span lang="en" dir="ltr" class="mw-content-ltr">Standard library imports</span>
* Third party imports
* <span lang="en" dir="ltr" class="mw-content-ltr">Third party imports</span>
* Your library imports
* <span lang="en" dir="ltr" class="mw-content-ltr">Your library imports</span>


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
Line 79: Line 89:
</syntaxhighlight>
</syntaxhighlight>


Here are some patterns to avoid:
<span lang="en" dir="ltr" class="mw-content-ltr">Here are some patterns to avoid:</span>


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
import sys, os # importing different modules on the same line
import sys, os # 同じ行で異なるモジュールをインポート
from sqlalchemy import * # don't import *
from sqlalchemy import * # * をインポートしないでください
from .models import util # use fully qualified names instead of relative imports
from .models import util # 相対的なインポートではなく完全修飾名を使用してください
</syntaxhighlight>
</syntaxhighlight>


Line 90: Line 100:
====== Imports expanded example ======
====== Imports expanded example ======
</div>
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
Here is a more detailed abstracted version (the comments are just for explanation purposes):
Here is a more detailed abstracted version (the comments are just for explanation purposes):
</div>


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# stdlib モジュールの完全インポート、アルファベット順
# Full import of stdlib modules, in alphabetic order
import a_stdlib_module
import a_stdlib_module
import b_stdlib_module
import b_stdlib_module


# stdlib モジュールの下位モジュールのインポート、上下と左右の両方でアルファベット順
# Submodules imports of stdlib modules, in alphabetic order both vertically and horizontally
from another_stdlib_module import a_stdlib_submodule, b_stdlib_submodule
from another_stdlib_module import a_stdlib_submodule, b_stdlib_submodule
from c_stdlib_module import another_stdlib_submodule, last_stdlib_submodule
from c_stdlib_module import another_stdlib_submodule, last_stdlib_submodule


# サード パーティ モジュールの完全インポート、アルファベット順
# Full import of 3rd party modules, in alphabetic order
import a_third_party_module
import a_third_party_module
import b_third_party_module
import b_third_party_module


# サード パーティ モジュールの下位モジュールのインポート、上下と左右の両方でアルファベット順
# Submodules imports of 3rd party modules, in alphabetic order both vertically and horizontally
from another_third_party_module import a_third_submodule, b_third_submodule
from another_third_party_module import a_third_submodule, b_third_submodule
from c_third_party_module import another_third_submodule, last_third_submodule
from c_third_party_module import another_third_submodule, last_third_submodule


# 現在のアプリケーション モジュールの完全インポート、絶対インポートでアルファベット順
# Full import of current application modules, in alphabetic order and with absolute imports
import myapp.a_module
import myapp.a_module
import myapp.b_module
import myapp.b_module


# 現在のアプリケーション モジュールの下位モジュールのインポート、上下と左右の両方でアルファベット順
# Submodules imports of current application modules, in alphabetic order both vertically and horizontally
from my_app.another_module import a_submodule, b_submodule
from my_app.another_module import a_submodule, b_submodule
from my_app.c_module import another_submodule, last_submodule
from my_app.c_module import another_submodule, last_submodule
Line 121: Line 134:
== Docstrings and function annotation ==
== Docstrings and function annotation ==
</div>
</div>
Generally all but the simplest functions should have docstrings.
<span lang="en" dir="ltr" class="mw-content-ltr">Generally all but the simplest functions should have docstrings.</span>
These are standardized in [http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings PEP 257]
<span lang="en" dir="ltr" class="mw-content-ltr">These are standardized in [http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings PEP 257]</span>


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
def fractionize(first, second=1):
def fractionize(first, second=1):
"""
"""
2 つの数値の分数の文字列表現を作成する。
Make a string representation of a fraction of two numbers.


キーワード引数:
Keyword arguments:
first -- the top of the fraction
first -- 分数の分子
second -- the bottom of the fraction (anything but 0)
second -- 分数の分母 (0 以外のあらゆる値)
"""
"""
return "{0} / {1}" % (first, second)
return "{0} / {1}" % (first, second)
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
This makes it possible to automatically generate docs, as well as use Python's built-in <code>help</code> function.
This makes it possible to automatically generate docs, as well as use Python's built-in <code>help</code> function.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
In Python 3.3 and above [http://www.python.org/dev/peps/pep-3107/ PEP 3107] specifies syntax for function annotations.
In Python 3.3 and above [http://www.python.org/dev/peps/pep-3107/ PEP 3107] specifies syntax for function annotations.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Function annotations do not have a completely set use case, but a common emerging case is for improved help docs and for type annotation.
Function annotations do not have a completely set use case, but a common emerging case is for improved help docs and for type annotation.
</div>


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
def parse(source: "the original document",
def parse(source: "the original document",
lang: "what markup syntax is being used? [md|rst|textile]",
lang: "使用するマークアップ構文 [md|rst|textile]",
force: "Ignore syntax errors?"):
force: "構文エラーを無視するかどうか"):
</syntaxhighlight>
</syntaxhighlight>


<span id="Naming_conflicts"></span>
<div lang="en" dir="ltr" class="mw-content-ltr">
== Naming conflicts ==
== 命名の競合 ==
<span lang="en" dir="ltr" class="mw-content-ltr">Conflicting with builtins is a somewhat common problem.</span>
</div>
<span lang="en" dir="ltr" class="mw-content-ltr">There are some builtin names (like <code>hash</code> and <code>id</code>) that you may want to use in your code.</span>
Conflicting with builtins is a somewhat common problem.
<span lang="en" dir="ltr" class="mw-content-ltr">The PEP8 way to deal with these conflicts is by appending an underscore to the name, such as <code>hash_</code> or <code>class_</code> (although if you're naming a variable <code>class_</code> that may be a code smell).</span>
There are some builtin names (like <code>hash</code> and <code>id</code>) that you may want to use in your code.
The PEP8 way to deal with these conflicts is by appending an underscore to the name, such as <code>hash_</code> or <code>class_</code> (although if you're naming a variable <code>class_</code> that may be a code smell).


If you find yourself in conflict with the name of some part of another module, <code>import as</code> is your friend.
<span lang="en" dir="ltr" class="mw-content-ltr">If you find yourself in conflict with the name of some part of another module, <code>import as</code> is your friend.</span>


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
Line 161: Line 179:
from mymodule import exceptions as my_exceptions
from mymodule import exceptions as my_exceptions
</syntaxhighlight>
</syntaxhighlight>

<span id="See_also"></span>
== 関連項目 ==


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
* [[Manual:Pywikibot/Development/Guidelines|Pywikibot Development Guidelines]]
== See also ==
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
* [https://www.python.org/ Official website]
</div>
</div>
* [[Manual:Pywikibot/Development/Guidelines]]
* [https://www.python.org/ Official WebSite]

{{Conventions navigation}}
{{Conventions navigation}}

Latest revision as of 06:59, 15 August 2026

このページでは、MediaWiki プロジェクトまたはサポート プロジェクトの一部である Python プロジェクト群のコーディング規約について説明します。

前文

まず、コード標準は単なるガイドラインであり、正当な理由がある場合は違反する可能性があることを忘れないでください。

  • 厳格な遵守のために、厳格な遵守よりも読みやすさと自明性を目指してください。
  • コードは、書かれるよりもはるかに頻繁に読まれます。
  • 既存のコードと一貫性を保ちつつ、最善の判断を下してください。 既存のコードを修正するのがそれほど難しくない場合は、ページの編集は大胆に

この文書で網羅されていないものについては、一般的な方法について Python Enhancement Proposal 0008 を参照してください。 以下の節は、ほとんどの場合、PEP8 の最も一般的に参照される部分の要約です。

Python のバージョン

The minimum supported version is 2.7, but in special cases it is okay to support older versions.

Python 2.7 is no longer maintained as of 2020.

If you have not already, you should change to Python 3 for local development.

空白類

Lines should be indented with 4 spaces.

Lines at the end of files should end with a newline, just like every other line in the file.

Try to keep lines under 80 characters long, but aim for readability and obviousness over strict adherence for the sake of strict adherence. Shorter lines are just a general side effect of good idiomatic Python - short but properly scoped descriptive names, avoiding staircase code, etc. When splitting up lines, pick the most obviously unambiguous method possible for the situation.

モジュールの構造

The standard way to distribute Python modules is to create a setup.py file and leverage a library called "distribute". There are modules that will generate the structure of a base project for you, a deprecated one is paster create which is no longer maintained. A replacement is pythong.

In general module structure should look like this:

newproject
├── bin
├── distribute_setup.py
├── docs
├── newproject
│     └── __init__.py
├── setup.py
└── tests
       ├── __init__.py
       └── newproject_tests.py

インポート

Within a file it's generally a good idea to organize your imports in some fashion. Typically alphabetical order is favored, but this can become unwieldy when importing a large number of libraries. To help avoid this, it's good to separate out imports in this fashion, with each block separated from the others by an empty line:

  • Standard library imports
  • Third party imports
  • Your library imports
import os
import re
import sys

import pymongo
from sqlalchemy import create_engine, exceptions

from mymodule import MyCustomException, models, views

Here are some patterns to avoid:

import sys, os # 同じ行で異なるモジュールをインポート
from sqlalchemy import * # * をインポートしないでください
from .models import util # 相対的なインポートではなく完全修飾名を使用してください
Imports expanded example

Here is a more detailed abstracted version (the comments are just for explanation purposes):

# stdlib モジュールの完全インポート、アルファベット順
import a_stdlib_module
import b_stdlib_module

# stdlib モジュールの下位モジュールのインポート、上下と左右の両方でアルファベット順
from another_stdlib_module import a_stdlib_submodule, b_stdlib_submodule
from c_stdlib_module import another_stdlib_submodule, last_stdlib_submodule

# サード パーティ モジュールの完全インポート、アルファベット順
import a_third_party_module
import b_third_party_module

# サード パーティ モジュールの下位モジュールのインポート、上下と左右の両方でアルファベット順
from another_third_party_module import a_third_submodule, b_third_submodule
from c_third_party_module import another_third_submodule, last_third_submodule

# 現在のアプリケーション モジュールの完全インポート、絶対インポートでアルファベット順
import myapp.a_module
import myapp.b_module

# 現在のアプリケーション モジュールの下位モジュールのインポート、上下と左右の両方でアルファベット順
from my_app.another_module import a_submodule, b_submodule
from my_app.c_module import another_submodule, last_submodule

Docstrings and function annotation

Generally all but the simplest functions should have docstrings. These are standardized in PEP 257

def fractionize(first, second=1):
    """
    2 つの数値の分数の文字列表現を作成する。

    キーワード引数:
    first -- 分数の分子
    second -- 分数の分母 (0 以外のあらゆる値)
    """
    return "{0} / {1}" % (first, second)

This makes it possible to automatically generate docs, as well as use Python's built-in help function.

In Python 3.3 and above PEP 3107 specifies syntax for function annotations.

Function annotations do not have a completely set use case, but a common emerging case is for improved help docs and for type annotation.

def parse(source: "the original document",
          lang: "使用するマークアップ構文 [md|rst|textile]",
          force: "構文エラーを無視するかどうか"):

命名の競合

Conflicting with builtins is a somewhat common problem. There are some builtin names (like hash and id) that you may want to use in your code. The PEP8 way to deal with these conflicts is by appending an underscore to the name, such as hash_ or class_ (although if you're naming a variable class_ that may be a code smell).

If you find yourself in conflict with the name of some part of another module, import as is your friend.

from sqlalchemy import exceptions as sa_exceptions
from mymodule import exceptions as my_exceptions

関連項目