Meta tags:
description= ;
author= ;
Headings (most frequently used words):
names, and, comments, naming, function, the, for, code, to, conventions, recommendations, or, line, module, variable, method, pep, style, guide, python, introduction, foolish, consistency, is, hobgoblin, of, little, minds, lay, out, string, quotes, whitespace, in, expressions, statements, when, use, trailing, commas, programming, indentation, tabs, spaces, maximum, length, should, break, before, after, binary, operator, blank, lines, source, file, encoding, imports, level, dunder, pet, peeves, other, block, inline, documentation, strings, overriding, principle, descriptive, styles, prescriptive, public, internal, interfaces, annotations, avoid, ascii, compatibility, package, class, type, exception, global, arguments, instance, variables, constants, designing, inheritance, footnotes, copyright,
Text of the page (most frequently used words):
the (296), and (116), are (83), for (82), that (77), with (76), use (69), should (66), python (59), this (51), code (47), when (44), line (38), not (37), names (37), from (36), name (33), used (29), #public (28), pep (28), class (27), style (26), yes (26), module (26), #import (25), using (22), foo (22), return (22), exception (22), function (21), lines (20), such (20), have (20), always (20), def (20), other (20), ham (20), all (19), can (19), comments (19), some (19), only (19), you (19), library (18), than (18), type (17), non (17), imports (17), except (16), string (16), attribute (16), statement (15), more (15), single (15), avoid (15), annotations (14), example (14), trailing (14), note (14), none (14), naming (14), which (14), one (14), spaces (14), may (13), make (13), methods (13), same (13), statements (13), also (13), characters (13), your (13), attributes (13), indentation (12), don (12), however (12), files (12), any (12), comment (12), exceptions (12), two (12), conventions (12), inside (12), underscores (12), first (11), guide (11), but (11), instead (11), after (11), try (11), argument (11), internal (11), these (11), convention (11), where (10), whitespace (10), form (10), see (10), them (10), will (10), error (10), they (10), operator (10), leading (10), space (10), before (10), syntax (9), indented (9), recommended (9), standard (9), there (9), true (9), explicit (9), case (9), long (9), continuation (9), rather (9), never (9), operators (9), generally (9), anystr (9), ascii (9), docstrings (9), binary (9), has (8), parenthesis (8), 484 (8), their (8), bar (8), api (8), value (8), functions (8), better (8), interfaces (8), level (8), lowercase (8), readability (8), following (8), lower (8), munge (8), var_one (8), character (7), those (7), add (7), strings (7), consistent (7), key (7), raise (7), arguments (7), here (7), classes (7), operations (7), both (7), written (7), does (7), modules (7), must (7), underscore (7), method (7), usually (7), upper (7), blank (7), break (7), want (6), over (6), like (6), optional (6), separate (6), tools (6), default (6), based (6), file (6), new (6), rules (6), object (6), rule (6), compatibility (6), either (6), parentheses (6), preferred (6), implementation (6), package (6), still (6), __all__ (6), mangling (6), side (6), about (6), variables (6), words (6), letter (6), consistency (6), docstring (6), open (6), offset (6), wrapping (6), tabs (6), long_function_name (6), var_two (6), var_three (6), var_four (6), being (5), closing (5), hanging (5), needs (5), backwards (5), third (5), packages (5), read (5), behavior (5), different (5), put (5), was (5), whether (5), editors (5), older (5), expression (5), present (5), indicate (5), important (5), limit (5), absolute (5), comma (5), way (5), control (5), containing (5), although (5), what (5), assignment (5), best (5), variable (5), even (5), considered (5), unless (5), documented (5), part (5), path (5), interface (5), list (5), clashes (5), double (5), keyword (5), guidelines (5), below (5), capwords (5), short (5), starts (5), related (5), itself (5), inline (5), block (5), each (5), english (5), print (5), blah (5), input (5), around (5), many (5), yourclass (5), myclass (5), sibling (5), length (5), compatible (4), section (4), checkers (4), ignore (4), party (4), within (4), easy (4), styles (4), longer (4), recommendations (4), write (4), seq (4), unicode (4), keep (4), comparisons (4), math (4), sqrt (4), else (4), explicitly (4), conn (4), local (4), particular (4), acceptable (4), keyerror (4), clause (4), amount (4), necessary (4), catching (4), system (4), work (4), user (4), good (4), bare (4), cases (4), include (4), need (4), apply (4), builtin (4), lambda (4), while (4), readable (4), set (4), implementations (4), across (4), access (4), distinguish (4), between (4), simple (4), data (4), just (4), spelling (4), another (4), instance (4), constants (4), separated (4), globals (4), because (4), most (4), identifiers (4), uppercase (4), its (4), multiline (4), 257 (4), omitted (4), setup (4), cfg (4), do_blah_thing (4), okay (4), multiple (4), complex (4), real (4), imag (4), immediately (4), spam (4), sys (4), definitions (4), extra (4), indent (4), further (4), conditional (4), document (3), suggested (3), typeshed (3), knuth (3), context (3), opening (3), barry (3), added (3), users (3), who (3), top (3), encouraged (3), annotation (3), previous (3), greeting (3), values (3), false (3), literals (3), rely (3), str (3), basestring (3), isinstance (3), obj (3), mind (3), might (3), startswith (3), less (3), much (3), required (3), end (3), latter (3), provide (3), something (3), ensure (3), finally (3), handle_value (3), catch (3), errors (3), prefer (3), out (3), least (3), making (3), baseexception (3), specific (3), message (3), text (3), original (3), appropriately (3), without (3), suffix (3), reserved (3), thus (3), uses (3), provides (3), expressions (3), writing (3), cpython (3), time (3), imported (3), prefixed (3), documentation (3), guarantees (3), well (3), subclass (3), get (3), intended (3), subclasses (3), helps (3), properties (3), functional (3), abbreviation (3), often (3), designed (3), unnecessary (3), changes (3), examples (3), conflicts (3), improve (3), typevar (3), policy (3), magic (3), whose (3), items (3), follow (3), please (3), sometimes (3), sparingly (3), sentence (3), period (3), priority (3), commas (3), etc (3), confusing (3), surround (3), do_one (3), do_two (3), do_three (3), lst (3), multi (3), projects (3), slice (3), brackets (3), braces (3), quoted (3), backslashes (3), implicit (3), would (3), mypkg (3), maximum (3), this_is_one_thing (3), that_is_another_thing (3), do_something (3), guideline (3), project (3), been (2), placed (2), straddling (2), https (2), www (2), repo (2), com (2), http (2), camelcase (2), donald (2), pages (2), setting (2), paragraph (2), term (2), last (2), subsequent (2), relevant (2), free (2), expected (2), run (2), stub (2), checker (2), preference (2), author (2), through (2), issue (2), messages (2), checking (2), alter (2), fine (2), ways (2), conservative (2), allowed (2), application (2), how (2), order (2), formatting (2), worse (2), boolean (2), visually (2), indistinguishable (2), len (2), sequences (2), tuples (2), fact (2), empty (2), too (2), base (2), types (2), directly (2), endswith (2), slicing (2), suffixes (2), backward (2), returns (2), state (2), doesn (2), do_stuff_in_transaction (2), whenever (2), collection (2), raised (2), key_not_found (2), clauses (2), avoids (2), hierarchy (2), introduced (2), introspection (2), problems (2), exc (2), binding (2), cleanup (2), then (2), traceback (2), occurred (2), program (2), platform_specific_module (2), mention (2), possible (2), means (2), valueerror (2), forms (2), special (2), question (2), wrong (2), problem (2), inheritance (2), useful (2), offer (2), identifier (2), indicates (2), assumed (2), interpreter (2), swap (2), implement (2), six (2), contexts (2), tool (2), comparison (2), really (2), testing (2), could (2), done (2), place (2), concatenation (2), works (2), isn (2), parts (2), __init__ (2), namespace (2), support (2), declare (2), able (2), clearly (2), algorithm (2), mangled (2), collisions (2), subclassed (2), consider (2), invokes (2), makes (2), future (2), recommendation (2), above (2), append (2), cls (2), known (2), especially (2), designing (2), take (2), private (2), since (2), removed (2), decide (2), doubt (2), letters (2), total (2), cannot (2), __a (2), class_ (2), mixedcase (2), already (2), global (2), vt_co (2), covariant (2), kt_contra (2), contravariant (2), normally (2), together (2), primarily (2), improves (2), discouraged (2), 3131 (2), eye (2), objects (2), addition (2), group (2), tuple (2), call (2), abbreviations (2), httpservererror (2), capitalizedwords (2), recognize (2), mess (2), standards (2), says (2), frobnicate (2), describes (2), ends (2), appear (2), paragraphs (2), follows (2), sure (2), language (2), complete (2), sentences (2), tox (2), ini (2), initialize (2), redundant (2), extended (2), adding (2), close (2), bracket (2), brace (2), delimiter (2), 1000 (2), sep (2), sign (2), colons (2), parameter (2), submitted (2), hypot2 (2), lowest (2), own (2), judgment (2), backslash (2), marker (2), long_variable (2), align (2), dct (2), index (2), step_fn (2), colon (2), eggs (2), quote (2), contains (2), __future__ (2), __version__ (2), __author__ (2), wildcard (2), spell (2), relative (2), layouts (2), tend (2), source (2), aren (2), test (2), authors (2), latin (2), utf (2), encoding (2), distribution (2), feed (2), sections (2), web (2), glyph (2), operands (2), income (2), gross_wages (2), taxable_interest (2), dividends (2), qualified_dividends (2), ira_deduction (2), student_loan_interest (2), formulas (2), away (2), columns (2), discussion (2), file_1 (2), file_2 (2), limiting (2), exclusively (2), provided (2), wrapped (2), visual (2), window (2), width (2), versions (2), limited (2), warnings (2), options (2), remain (2), my_list (2), result (2), some_function_that_takes_arguments (2), under (2), plus (2), suite (2), nested (2), indents (2), introduction (2), reasons (2), someone (2), guido (2), coding (2), domain, copyright, org, dev, peps, 0484, github, wikipedia, wiki, 195, 196, texbook, describe, parenthesized, until, gnu, mailman, warsaw, software, styleguide, txt, van, rossum, footnotes, purpose, recommends, pyi, corresponding, distributed, separately, permission, linters, interpreters, due, near, tells, grained, disabling, complaints, found, wants, adopting, big, refactorings, outside, stdlib, experiments, now, marking, large, reviewing, observing, presence, increases, understandability, experimentation, previously, forward, preferably, acceptance, changing, compare, significant, recently, reindent, trim, lists, exist, bytes, kind, sequence, integers, common, int, comparing, cleaner, prone, check, prefixes, faster, share, override, pythons, returned, reachable, information, doing, connection, transaction, __exit__, __enter__, begin_transaction, managers, invoked, acquire, release, resources, resource, cleaned, promptly, reliably, broad, additionally, minimum, again, masking, bugs, operating, errno, supported, ambiguity, associated, process_data, dataprocessingfailederror, caught, lets, propagate, upwards, handle, handler, printing, logging, aware, thumb, systemexit, keyboardinterrupt, harder, interrupt, disguise, signal, equivalent, importerror, paren, thanks, legal, raising, deliberately, replacing, inner, details, transferred, preserving, converting, attributeerror, embedding, chaining, replacement, losing, flow, signaling, design, hierarchies, distinctions, likely, locations, aim, answer, went, programmatically, stating, lesson, learned, 3151, derive, direct, almost, thing, resulting, specifically, generic, tracebacks, representations, general, eliminates, sole, benefit, embedded, larger, binds, reflexivity, guaranteed, confusion, arise, max, min, sort, 207, minimize, effort, involved, decorator, generate, missing, functools, total_ordering, implementing, ordering, rich, relying, exercise, __ge__, __gt__, __le__, __lt__, __ne__, __eq__, functionally, identical, former, beware, mean, defaults, container, singletons, equality, efficient, optimization, fragile, refcounting, performance, sensitive, occurs, linear, various, join, disadvantage, pypy, jython, ironpython, cython, psyco, programming, detail, indirect, exposes, functionality, submodules, declares, provisional, exempt, usual, undocumented, accordingly, everyone, likes, balance, accidental, potential, advanced, callers, certain, debugging, convenient, perform, manually, __getattr__, chooses, into, inadvertently, contain, computationally, expensive, notation, caller, believe, relatively, cheap, effect, effects, caching, expose, complicated, accessor, mutator, enhancement, find, grow, hide, behind, collides, preferable, corrupted, notwithstanding, pythonic, category, called, protected, languages, inherited, extend, modify, aspects, care, decisions, truly, expect, unrelated, clients, commitment, incompatible, parties, won, change, collectively, choose, easier, later, defined, capital, separating, max_overflow, controversy, __names, mangles, named, accessed, insistent, gain, calling, _foo__a, invoke, corruption, perhaps, synonym, clss, self, prevailing, threading, retain, via, mechanism, prevent, exporting, prefixing, let, hope, meant, applies, actually, typing, preferring, correspondingly, _contra, _co, num, callable, extension, accompanying, higher, oriented, _socket, described, fonts, numerals, zero, tempted, prescriptive, live, controlled, namespaces, invent, __file__, __import__, __double_leading_and_trailing_underscore__, foobar, becomes, _foobar__boo, __boo, __double_leading_underscore, tkinter, toplevel, master, classname, single_trailing_underscore_, weak, indicator, _single_leading_underscore, recognized, combined, x11, deemed, unique, prefix, mentioned, completeness, traditionally, emphasize, correspondence, fields, posix, struct, programmers, familiar, st_mtime, st_size, st_mode, stat, capitalize, ugly, capitalized_words_with_underscores, differs, initial, studlycaps, upper_case_with_underscores, lower_case_with_underscores, commonly, distinguished, lot, independently, descriptive, visible, reflect, usage, overriding, principle, bit, completely, nevertheless, currently, including, frameworks, existing, liner, foobang, plotz, bizbaz, importantly, immortalized, compensate, border, increment, distracting, obvious, start, coders, speaking, countries, 120, people, speak, strunk, white, ending, consist, built, phrase, word, capitalized, begins, contradict, keeping, date, helpful, version, pattern, next, sense, singleton, mandatory, element, semantics, clarity, technically, do_non_blah_thing, three, definitely, delay, small, body, folding, compound, combining, posint, normal, arrow, priorities, ies, sides, augmented, booleans, anywhere, invisible, followed, newline, count, preserve, pre, commit, hooks, reject, indexing, step, upper_fn, acts, equal, amounts, treating, spacing, applied, semicolon, extraneous, situations, pet, peeves, triple, pick, stick, quotes, stuff, barry_as_flufl, cardinal, biggles, dunders, mandates, dunder, republishing, regarding, avoided, unclear, readers, automated, defensible, republish, overwriting, pure, accelerator, exactly, overwritten, advance, causes, importing, alternative, dealing, unnecessarily, verbose, behaved, give, incorrectly, configured, directory, grouped, subprocess, popen, pipe, say, though, audience, adopt, similar, beyond, prescribed, wherever, feasible, technical, terms, features, alphabet, transliteration, encodings, purposes, otherwise, escapes, declaration, core, accepts, treat, page, separators, viewers, show, logical, groups, bunch, liners, dummy, surrounded, permissible, locally, match, tradition, mathematics, results, relations, displayed, solve, mathematicians, publishers, opposite, explains, traditional, his, series, computers, typesetting, sit, far, decades, hurt, scattered, screen, moved, operand, onto, tell, subtracted, continued, assert, thoughts, appropriate, times, implied, broken, requires, teams, strongly, maintained, team, reach, agreement, increase, nominal, 100, effectively, increasing, disrupts, structure, difficult, understand, limits, chosen, places, final, column, dynamic, editor, several, review, adjacent, flowing, blocks, fewer, structural, restrictions, invoking, command, option, issues, illegally, mixes, become, highly, mixture, converted, disallows, mixing, solely, lined, construct, constructs, distinction, supporting, highlighting, conditions, enough, require, worth, noting, combination, creates, natural, produce, conflict, naturally, takes, position, situation, forbidden, vertical, alignment, distinguishable, aligned, included, rest, elements, vertically, joining, per, lay, feature, predates, reason, modifying, surrounding, breaks, maybe, historic, opportunity, clean, applying, reading, comply, know, inconsistent, applicable, look, looks, hesitate, ask, insights, wide, spectrum, counts, foolish, hobgoblin, little, minds, event, guides, precedence, evolves, additional, identified, past, rendered, obsolete, were, adapted, essay, additions, gives, comprising, main, companion, informational, describing, stylized, presentation, established, created, humans, kenneth, reitz,
Text of the page (random words):
ary to improve readability mixedcase is allowed only in contexts where that s already the prevailing style e g threading py to retain backwards compatibility function and method arguments always use self for the first argument to instance methods always use cls for the first argument to class methods 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 class_ is better than clss perhaps better is to avoid such clashes by using a synonym method names and instance variables use 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 __a it cannot be accessed by foo __a an insistent user could still gain access by calling foo _foo__a generally double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed note there is some controversy about the use of __names see below constants constants are usually defined on a module level and written in all capital letters with underscores separating words examples include max_overflow and total designing for inheritance always 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 backward 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 attributes should have no leading underscores if your public attribute name collides with a reserved keyword append a single trailing underscore to your attribute name this is preferable to an abbreviation or corrupted spelling however notwithstanding this rule cls is the preferred spelling for any variable or argument which is known to be a class especially the first argument to a class method note 1 see the argument name recommendation above for class methods for simple public data attributes it is best to expose just the attribute name without complicated accessor mutator methods keep in mind that python provides an easy path to future enhancement should you find that a simple data attribute needs to grow functional behavior in that case use properties to hide functional implementation behind simple data attribute access syntax note 1 properties only work on new style classes note 2 try to keep the functional behavior side effect free although side effects such as caching are generally fine note 3 avoid using properties for computationally expensive operations the attribute notation makes the caller believe that access is relatively cheap if your class is intended to be subclassed and you have attributes that you do not want subclasses to use consider naming them with double leading underscores and no trailing underscores this invokes python s name mangling algorithm where the name of the class is mangled into the attribute name this helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name note 1 note that only the simple class name is used in the mangled name so if a subclass chooses both the same class name and attribute name you can still get name collisions note 2 name mangling can make certain uses such as debugging and __getattr__ less convenient however the name mangling algorithm is well documented and easy to perform manually note 3 not everyone likes name mangling try to balance the need to avoid accidental name clashes with potential use by advanced callers public and internal interfaces any 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 __all__ attribute setting __all__ to an empty list indicates that the module has no public api even with __all__ set appropriately internal interfaces packages modules classes functions attributes or other names should still be prefixed with a single leading underscore 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 os path or a package s __init__ module that exposes functionality from submodules programming recommendations code should be written in a way that does not disadvantage other implementations of python pypy jython ironpython cython psyco and such for example do not rely on cpython s efficient implementation of in place string concatenation for statements in the form a b or a a b this optimization is fragile even in cpython it only works for some types and isn t present at all in implementations that don t use refcounting in performance sensitive parts of the library the join form should be used instead this will ensure that concatenation occurs in linear time across various implementations comparisons to singletons like none should always be done with is or is not never the equality operators also beware of writing if x when you really mean if x is not none e g when testing whether a variable or argument that defaults to none was set to some other value the other value might have a type such as a container that could be false in a boolean context use is not operator rather than not is while both expressions are functionally identical the former is more readable and preferred yes if foo is not none no if not foo is none when implementing ordering operations with rich comparisons it is best to implement all six operations __eq__ __ne__ __lt__ __le__ __gt__ __ge__ rather than relying on other code to only exercise a particular comparison to minimize the effort involved the functools total_ordering decorator provides a tool to generate missing comparison methods pep 207 indicates that reflexivity rules are assumed by python thus the interpreter may swap y x with x y y x with x y and may swap the arguments of x y and x y the sort and min operations are guaranteed to use the operator and the max function uses the operator however it is best to implement all six operations so that confusion doesn t arise in other contexts always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier yes def f x return 2 x no f lambda x 2 x the first form means that the name of the resulting function object is specifically f instead of the generic lambda this is more useful for tracebacks and string representations in general the use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement i e that it can be embedded inside a larger expression derive exceptions from exception rather than baseexception direct inheritance from baseexception is reserved for exceptions where catching them is almost always the wrong thing to do design exception hierarchies based on the distinctions that code catching the exceptions is likely to need rather than the locations where the exceptions are raised aim to answer the question what went wrong programmatically rather than only stating that a problem occurred see pep 3151 for an example of this lesson being learned for the builtin exception hierarchy class naming conventions apply here although you should add the suffix error to your exception classes if the exception is an error non error exceptions that are used for non local flow control or other forms of signaling need no special suffix use exception chaining appropriately in python 3 raise x from y should be used to indicate explicit replacement without losing the original traceback when deliberately replacing an inner exception using raise x in python 2 or raise x from none in python 3 3 ensure that relevant details are transferred to the new exception such as preserving the attribute name when converting keyerror to attributeerror or embedding the text of the original exception in the new exception message when raising an exception in python 2 use raise valueerror message instead of the older form raise valueerror message the latter form is not legal python 3 syntax the paren using form also means that when the exception arguments are long or include string formatting you don t need to use line continuation characters thanks to the containing parentheses when catching exceptions mention specific exceptions whenever possible instead of using a bare except clause for example use try import platform_specific_module except importerror platform_specific_module none a bare except clause will catch systemexit and keyboardinterrupt exceptions making it harder to interrupt a program with control c and can disguise other problems if you want to catch all exceptions that signal program errors use except exception bare except is equivalent to except baseexception a good rule of thumb is to limit use of bare except clauses to two cases if the exception handler will be printing out or logging the traceback at least the user will be aware that an error has occurred if the code needs to do some cleanup work but then lets the exception propagate upwards with raise try finally can be a better way to handle this case when binding caught exceptions to a name prefer the explicit name binding syntax added in python 2 6 try process_data except exception as exc raise dataprocessingfailederror str exc this is the only syntax supported in python 3 and avoids the ambiguity problems associated with the older comma based syntax when catching operating system errors prefer the explicit exception hierarchy introduced in python 3 3 over introspection of errno values additionally for all try except clauses limit the try clause to the absolute minimum amount of code necessary again this avoids masking bugs yes try value collection key except keyerror return key_not_found key else return handle_value value no try too broad return handle_value collection key except keyerror will also catch keyerror raised by handle_value return key_not_found key when a resource is local to a particular section of code use a with statement to ensure it is cleaned up promptly and reliably after use a try finally statement is also acceptable context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources for example yes with conn begin_transaction do_stuff_in_transaction conn no with conn do_stuff_in_transaction conn the latter example doesn t provide any information to indicate that the __enter__ and __exit__ methods are doing something other than closing the connection after a transaction being explicit is important in this case be consistent in return statements either all return statements in a function should return an expression or none of them should if any return statement returns an expression any return statements where no value is returned should explicitly state this as return none and an explicit return statement should be present at the end of the function if reachable yes def foo x if x 0 return math sqrt x else return none def bar x if x 0 return none return math sqrt x no def foo x if x 0 return math sqrt x def bar x if x 0 return return math sqrt x use string methods instead of the string module string methods are always much faster and share the same api with unicode strings override this rule if backward compatibility with pythons older than 2 0 is required use startswith and endswith instead of string slicing to check for prefixes or suffixes startswith and endswith are cleaner and less error prone for example yes if foo startswith bar no if foo 3 bar object type comparisons should always use isinstance instead of comparing types directly yes if isinstance obj int no if type obj is type 1 when checking if an object is a string keep in mind that it might be a unicode string too in python 2 str and unicode have a common base class basestring so you can do if isinstance obj basestring note that in python 3 unicode and basestring no longer exist there is only str and a bytes object is no longer a kind of string it is a sequence of integers instead for sequences strings lists tuples use the fact that empty sequences are false yes if not seq if seq no if len seq if not len seq don t write string literals that rely on significant trailing whitespace such trailing whitespace is visually indistinguishable and some editors or more recently reindent py will trim them don t compare boolean values to true or false using yes if greeting no if greeting true worse if greeting is true function annotations with the acceptance of pep 484 the style rules for function annotations are changing in order to be forward compatible function annotations in python 3 code should preferably use pep 484 syntax there are some formatting recommendations for annotations in the previous section the experimentation with annotation styles that was recommended previously in this pep is no longer encouraged however outside the stdlib experiments within the rules of pep 484 are now encouraged for example marking up a large third party library or application with pep 484 style type annotations reviewing how easy it was to add those annotations and observing whether their presence increases code understandability the python standard library should be conservative in adopting such annotations but th...
|