Hướng dẫn dùng denoted definition python
python Return trong Python Function trong Python Hàm trong Python Nội dung chính Bài Viết Liên QuanHướng dẫn dùng numpy ln pythonHướng dẫn dùng matplotlib styles pythonHướng dẫn dùng python __all__ pythonHướng dẫn dùng python subarray pythonHướng dẫn dùng d.e.l pythonHướng dẫn dùng matlab scatterplot pythonHướng dẫn dùng .._.._...._ trong PHPHướng dẫn dùng python iterables pythonHướng dẫn thuật toán pythonHướng dẫn dùng true check pythonHướng dẫn python round upHướng dẫn dùng strx meaning pythonHướng dẫn dùng value def pythonHướng dẫn dùng regex string pythonHướng dẫn dùng pyspark.sql.types pythonHướng dẫn front-end pythonHướng dẫn dùng corr python pythonHướng dẫn dùng python -m pythonHướng dẫn dùng df mean pythonHướng dẫn dùng numpy pop pythonToplist mới#1 Top 10 bài tập nâng cao về cảm ứng từ 20226 ngày trước #2 Top 10 vở bài tập tiếng việt lớp 3 tập 2 trang 50 20226 ngày trước #3 Top 9 cửa hàng bán đồ an vặt trung quốc tphcm 20222 ngày trước #4 Top 9 công thức chỉnh màu lightroom tone xám 20225 giờ trước #5 Top 9 bài 6 trang 37 sbt toán 7 tập 2 20223 ngày trước #6 Top 10 muôn đội sâu các thế hệ người việt nam sẽ còn nhắc đến chiến thắng vĩ đại điện biên phủ như 20224 ngày trước #7 Top 9 bình đun nước fatz quick 6 20222 ngày trước #8 Top 10 kính công giáo đọc hằng ngày mp3 202218 giờ trước #9 Top 9 học phí cấp 3 trường công lập tphcm 20223 ngày trước Bài mới nhấtCô giáo mần non lộ cliplight bulbing là gì - Nghĩa của từ light bulbingWhen the auditor decides to select less than 100% of the population for testing the auditor is said to be using?Mối quan hệ giữa đức và tài là gìPhương pháp giải bài tập H+ NO3Top 20 cửa hàng đt cũ Huyện Tu Mơ Rông Kon Tum 2022What are the four common triggers of conflict spoken about in Chapter 6 choose the 4 that apply?meedy là gì - Nghĩa của từ meedyWhich one of the following statements provides the most credible explanation for the fact that human beings seem to surpass all other animal species?Câu nói hay trong phim Nhất Sinh Nhất thếChủ ĐềToplist Hỏi Đáp Là gì Địa Điểm Hay Mẹo Hay Nghĩa của từ Học Tốt Cách Công Nghệ Học Review Khỏe Đẹp Máy Cryto Sản phẩm tốt Giá Bao nhiêu Ngôn ngữ Ở đâu Xây Đựng Top List Dịch Tại sao Nhà Hướng dẫn Là ai Tiếng anh Vì sao Bao lâu So Sánh Máy tính Bài tập Top Đại học Khoa Học So sánh Thế nào Sách Phương trình Món Ngon Thuốc Nghĩa là gì Hà Nội Giới Tính Thanh Hóa Phim Đánh giá Game Hồ Chí Minh Xây
IntroductionThis document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python. This document and PEP 257 (Docstring Conventions) were adapted from Guido’s original Python Style Guide essay, with some additions from Barry’s style guide [2]. This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself. Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project. A Foolish Consistency is the Hobgoblin of Little MindsOne of Guido’s key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, “Readability counts”. A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important. However, know when to be inconsistent – sometimes style guide recommendations just aren’t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask! In particular: do not break backwards compatibility just to comply with this PEP! Some other good reasons to ignore a particular guideline:
Code Lay-outIndentationUse 4 spaces per indentation level. Continuation lines should align wrapped elements either vertically using Python’s implicit line joining inside parentheses, brackets and braces, or using a hanging indent [1]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line: # Correct: # Aligned with opening delimiter. foo = long_function_name(var_one, var_two, var_three, var_four) # Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest. def long_function_name( var_one, var_two, var_three, var_four): print(var_one) # Hanging indents should add a level. foo = long_function_name( var_one, var_two, var_three, var_four) # Wrong: # Arguments on first line forbidden when not using vertical alignment. foo = long_function_name(var_one, var_two, var_three, var_four) # Further indentation required as indentation is not distinguishable. def long_function_name( var_one, var_two, var_three, var_four): print(var_one) The 4-space rule is optional for continuation lines. Optional: # Hanging indents *may* be indented to other than 4 spaces. foo = long_function_name( var_one, var_two, var_three, var_four) When the conditional part of an # No extra indentation. if (this_is_one_thing and that_is_another_thing): do_something() # Add a comment, which will provide some distinction in editors # supporting syntax highlighting. if (this_is_one_thing and that_is_another_thing): # Since both conditions are true, we can frobnicate. do_something() # Add some extra indentation on the conditional continuation line. if (this_is_one_thing and that_is_another_thing): do_something() (Also see the discussion of whether to break before or after binary operators below.) The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list, as in: my_list = [ 1, 2, 3, 4, 5, 6, ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', ) or it may be lined up under the first character of the line that starts the multiline construct, as in: my_list = [ 1, 2, 3, 4, 5, 6, ] result = some_function_that_takes_arguments( 'a', 'b', 'c', 'd', 'e', 'f', ) Tabs or Spaces?Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs. Python disallows mixing tabs and spaces for indentation. Maximum Line LengthLimit all lines to a maximum of 79 characters. For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters. Limiting the required editor window width makes it possible to have several files open side by side, and works well when using code review tools that present the two versions in adjacent columns. The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all. Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters. The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72). The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Backslashes may still be appropriate at times. For example, long, multiple with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read()) (See the previous discussion on multiline if-statements for further thoughts on the indentation of such multiline Another such case is with Make sure to indent the continued line appropriately. Should a Line Break Before or After a Binary Operator?For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted: # Wrong: # operators sit far away from their operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: “Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations” [3]. Following the tradition from mathematics usually results in more readable code: # Correct: # easy to match operators with operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth’s style is suggested. Blank LinesSurround top-level function and class definitions with two blank lines. Method definitions inside a class are surrounded by a single blank line. Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations). Use blank lines in functions, sparingly, to indicate logical sections. Python accepts the control-L (i.e. ^L) form feed character as whitespace; many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file. Note, some editors and web-based code viewers may not recognize control-L as a form feed and will show another glyph in its place. Source File EncodingCode in the core Python distribution should always use UTF-8, and should not have an encoding declaration. In the standard library, non-UTF-8 encodings should be used only for test purposes. Use non-ASCII characters sparingly, preferably only to denote places and human names. If using non-ASCII characters as data, avoid noisy Unicode characters like z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘ and byte order marks. All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible (in many cases, abbreviations and technical terms are used which aren’t English). Open source projects with a global audience are encouraged to adopt a similar policy. Imports
Module Level Dunder NamesModule level “dunders” (i.e. names with two leading and two trailing underscores) such as """This is the example module. This module does stuff. """ from __future__ import barry_as_FLUFL __all__ = ['a', 'b', 'c'] __version__ = '0.1' __author__ = 'Cardinal Biggles' import os import sys String QuotesIn Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability. For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257. Whitespace in Expressions and StatementsPet PeevesAvoid extraneous whitespace in the following situations:
Other Recommendations
When to Use Trailing CommasTrailing commas are usually optional, except they are mandatory when making a tuple of one element. For clarity, it is recommended to surround the latter in (technically redundant) parentheses: # Correct: FILES = ('setup.cfg',) # Wrong: FILES = 'setup.cfg', When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line. However it does not make sense to have a trailing comma on the same line as the closing delimiter (except in the above case of singleton tuples): # Correct: FILES = [ 'setup.cfg', 'tox.ini', ] initialize(FILES, error=True, ) # Wrong: FILES = ['setup.cfg', 'tox.ini',] initialize(FILES, error=True,) Naming ConventionsThe naming conventions of Python’s library are a bit of a mess, so we’ll never get this completely consistent – nevertheless, here are the currently recommended naming standards. New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred. Overriding PrincipleNames that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation. Descriptive: Naming StylesThere are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for. The following naming styles are commonly distinguished:
There’s
also the style of using a short unique prefix to group related names together. This is not used much in Python, but it is mentioned for completeness. For example, the The X11 library uses a leading X for all its public functions. In Python, this style is generally deemed unnecessary because attribute and method names are prefixed with an object, and function names are prefixed with a module name. In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):
Prescriptive: Naming ConventionsNames to AvoidNever use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use ‘l’, use ‘L’ instead. ASCII CompatibilityIdentifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131. Package and Module NamesModules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged. When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. Class NamesClass names should normally use the CapWords convention. The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable. Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants. Type Variable NamesNames of type variables introduced in PEP 484 should
normally use CapWords preferring short names: from typing import TypeVar VT_co = TypeVar('VT_co', covariant=True) KT_contra = TypeVar('KT_contra', contravariant=True) Exception NamesBecause exceptions should be classes, the class naming convention applies here. However, you should use the suffix “Error” on your exception names (if the exception actually is an error). Global Variable Names(Let’s hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions. Modules that are designed for use via Function and Variable NamesFunction names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names. mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility. Function and Method ArgumentsAlways use Always use If a function argument’s name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus Method Names and Instance VariablesUse the function naming rules: lowercase with words separated by underscores as necessary to improve readability. Use one leading underscore only for non-public methods and instance variables. To avoid name clashes with subclasses, use two leading underscores to invoke Python’s name mangling rules. Python mangles these names with the class name: if class Foo has an attribute named Note: there is some controversy about the use of __names (see below). ConstantsConstants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include Designing for InheritanceAlways decide whether a class’s methods and instance variables (collectively: “attributes”) should be public or non-public. If in doubt, choose non-public; it’s easier to make it public later than to make a public attribute non-public. Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backwards incompatible changes. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won’t change or even be removed. We don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work). Another category of attributes are those that are part of the “subclass API” (often called “protected” in other languages). Some classes are designed to be inherited from, either to extend or modify aspects of the class’s behavior. When designing such a class, take care to make explicit decisions about which attributes are public, which are part of the subclass API, and which are truly only to be used by your base class. With this in mind, here are the Pythonic guidelines:
Public and Internal InterfacesAny backwards compatibility guarantees apply only to public interfaces. Accordingly, it is important that users be able to clearly distinguish between public and internal interfaces. Documented interfaces are considered public, unless the documentation explicitly declares them to be provisional or internal interfaces exempt from the usual backwards compatibility guarantees. All undocumented interfaces should be assumed to be internal. To better support introspection, modules should explicitly declare the names in their public API using the Even with An interface is also considered internal if any containing namespace (package, module or class) is considered internal. Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module’s API, such
as Programming Recommendations
Function AnnotationsWith the acceptance of PEP 484, the style rules for function annotations have changed.
Variable AnnotationsPEP 526 introduced variable annotations. The style recommendations for them are similar to those on function annotations described above:
Footnotes ReferencesCopyrightThis document has been placed in the public domain. |