Python rules
tx0 checks .py and .pyi files with 230 rules, 69 of them in the default tier. Files that say a tool generated them are skipped. Each rule's page explains what it finds and what it leaves alone.
Default: 69 rules
Bugs and security problems with measured precision. They run without a tx0.toml.
-
tx0/python:assert-always-truedefaultAn assertion tests a non-empty string or display, which is always true
-
tx0/python:assert-tupledefaultAn assertion tests a tuple, which is always true
-
tx0/python:call-arguments-mismatchdefaultA call does not fit the parameters of a function defined in the same file
-
tx0/python:callback-arity-mismatchdefaultA lambda takes a different number of arguments than the builtin calls it with
-
tx0/python:command-string-without-shelldefaultsubprocessgets a command line as one string withoutshell=True -
tx0/python:comprehension-key-never-variesdefaultA dict comprehension uses the same literal key for every element
-
tx0/python:coroutine-not-awaiteddefaultA coroutine is created by a call and dropped without being awaited
-
tx0/python:dataclass-mutable-defaultdefaultA dataclass field defaults to a list, dict or set, and defining the class raises
ValueError -
tx0/python:datetime-out-of-rangedefaultA date or time is built from a literal field outside its range
-
tx0/python:decimal-file-modedefaultFile permissions are written in decimal where octal was meant
-
tx0/python:decorator-orderdefaultA method's decorators are stacked in an order that fails or no longer works
-
tx0/python:defaultdict-factory-keyworddefaultdefaultdictgets its factory asdefault_factory=, which becomes a dict entry -
tx0/python:discarded-resultdefaultThe result of a call that has no other effect is dropped
-
tx0/python:duplicate-base-classdefaultA class lists the same base twice
-
tx0/python:duplicate-conditiondefaultA condition of an if-elif chain repeats an earlier one
-
tx0/python:duplicate-dict-keydefaultA dict display gives the same key twice
-
tx0/python:duplicate-set-itemdefaultA set display lists the same member twice
-
tx0/python:empty-membershipdefaultA value is looked up with
inin an empty display -
tx0/python:enum-with-generated-methodsdefaultGenerated
__init__,__eq__and__repr__replace those of anEnumsubclass -
tx0/python:environ-copy-still-livedefaultcopy.copy(os.environ)makes an object that still changes the real environment -
tx0/python:except-joined-typesdefaultA handler's types are joined with
ororand, so one class is matched -
tx0/python:except-shadoweddefaultAn exception type is already caught by an earlier
exceptclause -
tx0/python:finally-control-flowdefaultA
finallyblock jumps away withreturn,breakorcontinueand drops any pending exception -
tx0/python:format-call-mismatchdefaultA literal
str.formattemplate and its arguments do not fit together -
tx0/python:fromkeys-shared-valuedefaultEvery key of
dict.fromkeysor every context of aContextVargets the same mutable object -
tx0/python:identical-operandsdefaultBoth operands of an operator are the same
-
tx0/python:incompatible-literal-operandsdefaultAn operator combines two literals of types that do not support it
-
tx0/python:invalid-escapedefaultA backslash in a string starts no escape sequence
-
tx0/python:invalid-regexdefaultA literal regular expression or replacement is one that
rerefuses -
tx0/python:is-literaldefaultisoris notcompares with a literal -
tx0/python:isinstance-bad-classdefaultisinstanceorissubclassis given something other than classes to check against -
tx0/python:iter-method-returns-collectiondefault__iter__returns a collection or literal, which is not an iterator -
tx0/python:join-non-stringsdefaultstr.joinis given literals that are not strings -
tx0/python:length-sign-testdefaultThe result of
lenis tested for being negative, which it never is -
tx0/python:literal-misusedefaultA literal is called, searched with
inor indexed, which its type does not support -
tx0/python:logging-format-mismatchdefaultA logging call's
%format and its arguments do not fit together -
tx0/python:mock-check-without-assertdefaultA mock check such as
called_once_withis written withoutassert_, so it checks nothing -
tx0/python:modified-while-iteratingdefaultA loop adds to or removes from the collection it is walking
-
tx0/python:nan-equalitydefaultA value is compared with NaN using
==or!= -
tx0/python:nested-event-loopdefaultasyncio.runis called inside a coroutine, where a loop is already running -
tx0/python:non-string-environ-valuedefaultA value other than a string is assigned to
os.environ -
tx0/python:not-an-exceptiondefaultA value that is not an exception is raised, caught or given as a cause
-
tx0/python:not-implemented-truthdefaultThe truth value of
NotImplementedis taken -
tx0/python:open-modedefaultA file is opened with a mode or arguments that
openrefuses -
tx0/python:percent-formatdefaultA
%format and its values do not match -
tx0/python:print-redirectdefaultprint >> fileis written as in Python 2 -
tx0/python:property-accessor-aritydefaultA property accessor takes the wrong arguments, or its getter returns nothing
-
tx0/python:pytz-tzinfo-argumentdefaultA
pytztime zone is passed astzinfo, which gives a wrong offset -
tx0/python:raise-not-implementeddefaultNotImplementedis raised instead ofNotImplementedError -
tx0/python:raises-context-unuseddefaultpytest.raisesis called as a statement, so it checks nothing -
tx0/python:redefined-functiondefaultA function or class is defined again before the first definition is used
-
tx0/python:regex-case-range-gapdefaultA character class of a regular expression has the range
A-z, which also takes in six punctuation characters -
tx0/python:regex-flag-as-countdefaultAn
reflag is passed wherere.suborre.splittake a count -
tx0/python:removed-numpy-aliasdefaultA NumPy alias of a builtin type that NumPy 1.24 removed is used
-
tx0/python:removed-unittest-aliasdefaultA test calls an old alias of a
unittestassertion, such asassertEquals, which Python 3.12 removed -
tx0/python:return-in-initdefault__init__hands back a value, and creating the object raisesTypeError -
tx0/python:self-assignmentdefaultAn assignment stores a name's value back into the same name
-
tx0/python:slots-conflictdefaultA name in
__slots__is also a class attribute, and defining the class raisesValueError -
tx0/python:special-method-aritydefaultA special method takes a different number of arguments than Python passes it
-
tx0/python:star-handler-group-typedefaultA star handler is written for a whole exception group type
-
tx0/python:stop-iteration-in-generatordefaultA generator raises
StopIteration, which Python turns intoRuntimeError -
tx0/python:swapped-augmented-operatordefault=+,=-or=~is written where an augmented assignment was likely meant -
tx0/python:tempfile-mktempdefaulttempfile.mktempreturns a name another process can take first -
tx0/python:type-variable-name-mismatchdefaultA
TypeVar,ParamSpec,TypeVarTupleorNewTypeis given a name that differs from the variable it is assigned to -
tx0/python:typevar-two-variancesdefaultA type variable is declared with both variance flags set
-
tx0/python:unhashable-literaldefaultA list, dict or set is written as a dict key or set member
-
tx0/python:unparsable-number-literaldefaultintorfloatis given a string literal it cannot read as a number -
tx0/python:unraised-exceptiondefaultAn exception object is built as a statement of its own and thrown away
-
tx0/python:unreachable-codedefaultCode that can never run
Recommended: 72 rules
Likely bugs, resource and performance problems.
-
tx0/python:bare-exceptrecommendedexcept:without a type also catchesKeyboardInterruptandSystemExit -
tx0/python:bare-raise-in-finallyrecommendedA bare
raisestands in afinallyblock, which also runs without an exception -
tx0/python:blocking-call-in-asyncrecommendedAn
asyncfunction makes a call that blocks the event loop -
tx0/python:cached-methodrecommendedA method is cached with
functools.lru_cacheorcache, which keeps every instance alive -
tx0/python:class-attribute-redefinedrecommendedA class body assigns the same attribute twice
-
tx0/python:class-skips-exception-baserecommendedA class derives from
BaseExceptiondirectly, soexcept Exceptionmisses it -
tx0/python:constant-ivrecommendedData is encrypted with an initialization vector or nonce written in the source
-
tx0/python:constant-saltrecommendedA password is hashed with a salt written in the source
-
tx0/python:cors-any-originrecommendedCross-origin requests are allowed from every origin
-
tx0/python:csrf-check-offrecommendedProtection against cross-site request forgery is turned off for a view or an application
-
tx0/python:cyclomatic-complexityrecommendedA function has more independent paths than the limit
-
tx0/python:debugger-callrecommendedA call stops the program in a debugger
-
tx0/python:deprecated-logger-warnrecommendedwarnis called on a logger, an old alias ofwarningthat is deprecated -
tx0/python:django-debug-settingrecommendedA Django settings module turns
DEBUGon, or allows every host name -
tx0/python:django-form-all-fieldsrecommendedA Django model form or serializer exposes every model field with
__all__orexclude -
tx0/python:dunder-all-entryrecommendedAn entry of
__all__is not a string, or names nothing the module defines -
tx0/python:duplicate-importrecommendedThe same module or name is imported twice in one scope
-
tx0/python:duplicate-parametrize-caserecommendedpytest.mark.parametrizelists the same case twice -
tx0/python:eval-execrecommendedevalorexecruns code that is not a literal -
tx0/python:exact-type-testrecommendedThe type of a value is compared with
==or!= -
tx0/python:file-not-closedrecommendedA file is opened and used in one expression, so nothing closes it
-
tx0/python:fixed-truth-conditionrecommendedAn
ifor ternary tests a literal, so the same branch runs every time -
tx0/python:flask-debugrecommendedA Flask application is run in debug mode
-
tx0/python:hardcoded-passwordrecommendedA password or secret key is written in the source
-
tx0/python:identical-branchesrecommendedEvery branch of an if-else or conditional expression is the same
-
tx0/python:implicit-concatenationrecommendedTwo string literals on one line are joined into one item of a list or call
-
tx0/python:insecure-randomrecommendedA token, password or key is made with the predictable
randommodule -
tx0/python:isclose-without-abs-tolrecommendedmath.isclosecompares with zero withoutabs_tol, so only exact zero passes -
tx0/python:loop-else-without-breakrecommendedA loop has an
elseblock but nobreak, so the block runs like code after the loop -
tx0/python:loop-runs-oncerecommendedA loop's body always leaves the loop, so it runs at most once
-
tx0/python:loop-variable-closurerecommendedA lambda stored in a loop reads the loop variable when called, not when made
-
tx0/python:lxml-entity-expansionrecommendedXML is parsed with
lxmlin a way that expands entities from the document -
tx0/python:mark-safe-formattedrecommendedmark_safeis given a string built by formatting, so the values put into it are not escaped -
tx0/python:method-without-selfrecommendedA method has no parameter to receive the instance or class
-
tx0/python:mutable-default-argumentrecommendedA parameter's default is a list, dict or set shared by all calls
-
tx0/python:naive-utc-datetimerecommendeddatetime.utcnoworutcfromtimestampmakes a UTC time without a time zone -
tx0/python:nested-loop-reuses-variablerecommendedAn inner
forloop assigns the variable of an outer one -
tx0/python:nesting-depthrecommendedControl statements are nested deeper than the limit
-
tx0/python:operator-raises-not-implementedrecommendedAn operator method raises
NotImplementedErrorwhere returningNotImplementedlets the other operand try -
tx0/python:os-systemrecommendedos.systemoros.popenruns a command built at run time -
tx0/python:pytest-yield-fixturerecommendedA fixture is declared with
pytest.yield_fixture, an alias that pytest deprecated and removed -
tx0/python:regex-duplicate-class-memberrecommendedA bracket set in a pattern names the same character twice
-
tx0/python:regex-empty-alternativerecommended||or a|at either end of a pattern adds a choice that matches nothing at all -
tx0/python:regex-empty-grouprecommendedA pattern has parentheses with nothing between them
-
tx0/python:removed-stdlib-apirecommendedA module or function that the standard library removed in Python 3.11 to 3.13 is used
-
tx0/python:request-without-timeoutrecommendedAn HTTP request with
requestshas no timeout -
tx0/python:silent-exception-handlerrecommendedAn
exceptclause forExceptionorBaseExceptiondoes nothing butpass -
tx0/python:sql-formattingrecommendedAn SQL query is built by formatting values into its text
-
tx0/python:ssh-unknown-host-acceptedrecommendedA
paramikoSSH client accepts servers whose host key it does not know -
tx0/python:subprocess-shellrecommendedA command built at run time is run through the shell
-
tx0/python:tangled-functionrecommendedA function's branches and loops, weighted by how deep they nest, exceed the configured limit
-
tx0/python:tar-extract-without-filterrecommendedA tar archive is extracted without a
filter, so its members can write outside the target directory -
tx0/python:task-reference-droppedrecommendedThe task
asyncio.create_taskreturns is not kept anywhere -
tx0/python:template-autoescape-offrecommendedA Jinja environment does not escape the values put into templates
-
tx0/python:tls-verify-disabledrecommendedThe certificate or host name of a TLS server is not checked
-
tx0/python:token-signature-ignoredrecommendedjwt.decodeis told to skip the signature check -
tx0/python:torch-load-unrestrictedrecommendedtorch.loadmay unpickle code from the file -
tx0/python:uncalled-private-methodrecommendedNothing calls a method whose name is mangled private
-
tx0/python:undefined-namerecommendedA name is used that the file never binds and that is not a builtin
-
tx0/python:unlisted-star-importrecommendedfrom module import *binds names that the file does not list -
tx0/python:unsafe-deserializationrecommendedData is read with
pickleor a format that can run code -
tx0/python:unused-importrecommendedAn imported name is never used
-
tx0/python:unused-variablerecommendedA local variable is assigned but never read
-
tx0/python:useless-reraiserecommendedEvery
exceptclause of atryraises the caught exception again unchanged -
tx0/python:weak-cipherrecommendedA broken cipher or the ECB mode encrypts data
-
tx0/python:weak-hashrecommendedMD5 or SHA-1 is used without
usedforsecurity=False -
tx0/python:weak-key-sizerecommendedAn RSA or DSA key is made shorter than 2048 bits
-
tx0/python:weak-tls-versionrecommendedAn SSL or early TLS version with known attacks is used
-
tx0/python:world-writable-moderecommendedA file's permissions let every user write it
-
tx0/python:write-only-private-fieldrecommendedA class assigns a private attribute
self.__namethat nothing reads -
tx0/python:yaml-unsafe-loadrecommendedYAML is read with a loader that can build any object
-
tx0/python:yield-without-finallyrecommendedA generator context manager's cleanup after
yieldis skipped when the block raises
Strict: 89 rules
Code that can be written more plainly.
-
tx0/python:ambiguous-namestrictA variable, parameter, function or class is named
l,OorI -
tx0/python:any-annotationstrictA parameter or return value is annotated with
Any, which turns type checking off for it -
tx0/python:async-without-awaitstrictAn
asyncfunction never awaits anything -
tx0/python:bool-literal-comparisonstrictA value is compared with
TrueorFalseusing==or!= -
tx0/python:boolean-complexitystrictAn expression joins more conditions with
andandorthan the limit -
tx0/python:case-only-name-clashstrictTwo members of a class have names that are equal apart from upper and lower case
-
tx0/python:catch-all-error-thrownstrictraisethrows the root classExceptionorBaseExceptionitself -
tx0/python:class-attribute-name-stylestrictA name assigned in a class body follows neither the configured style nor
UPPER_CASE -
tx0/python:class-name-stylestrictThe name of a class does not follow the configured case style
-
tx0/python:collapsible-ifstrictAn
ifholds only anotherif, and the two conditions can be joined -
tx0/python:complex-classstrictThe methods of a class together have more paths than the configured limit
-
tx0/python:conditional-inside-conditionalstrictA ternary
x if c else yholds another ternary -
tx0/python:consecutive-appendsstrictSeveral
appendcalls on the same list follow each other, where oneextendor a display does the same -
tx0/python:cookie-without-flagsstrictA cookie is set without
secureor withouthttponly -
tx0/python:copying-comprehensionstrictA list or set comprehension only copies the items of an iterable
-
tx0/python:default-fixture-scopestrictA pytest fixture is given
scope="function", which is already the default -
tx0/python:disabled-code-commentstrictA comment holds code that was switched off
-
tx0/python:django-locals-contextstrictlocals()is passed as the context of a Django template -
tx0/python:django-model-without-strstrictA Django model defines no
__str__, so the admin and shell show it asModel object (1) -
tx0/python:django-nullable-text-fieldstrictA Django text field allows
NULL, so an empty value can be stored in two ways -
tx0/python:double-negationstrictnotor~is applied twice in a row -
tx0/python:duplicate-function-bodystrictTwo functions of a file have the same body
-
tx0/python:duplicate-string-literalstrictThe same string literal is written several times in one file
-
tx0/python:eager-log-formattingstrictA log message is formatted before the call, even when the level is turned off
-
tx0/python:empty-collection-callstrictdict(),list()ortuple()is called without arguments where a display is shorter -
tx0/python:eq-without-hashstrictA class defines
__eq__but not__hash__, so its instances cannot be put in sets or used as dict keys -
tx0/python:error-log-without-tracebackstrictAn
exceptblock logs witherror, which drops the traceback thatexceptionwould record -
tx0/python:exception-name-suffixstrictAn exception class's name does not end in
Error,ExceptionorWarning -
tx0/python:explicit-super-argumentsstrictsuperis given the class and instance that Python 3 fills in on its own -
tx0/python:file-lengthstrictA module has more lines of code than the limit
-
tx0/python:fstring-in-fstringstrictAn f-string is written inside a replacement field of another f-string
-
tx0/python:fstring-without-placeholdersstrictAn f-string has no replacement fields
-
tx0/python:function-lengthstrictA function exceeds the configured count of code lines
-
tx0/python:function-name-stylestrictThe name of a function does not follow the configured case style
-
tx0/python:global-statementstrictA function rebinds a module variable through
global -
tx0/python:hardcoded-ip-addressstrictAn IP address is written in the source
-
tx0/python:if-return-boolstrictAn
ifreturnsTruein one branch andFalsein the other, instead of returning the condition -
tx0/python:incomplete-orderingstrictA class defines some of
__lt__,__le__,__gt__and__ge__but not all, and is not markedtotal_ordering -
tx0/python:inconsistent-returnstrictA function returns a value on some paths and nothing on others
-
tx0/python:jump-at-block-endstrictA bare
returnends a function, orcontinueends a loop body, where control goes anyway -
tx0/python:lambda-assignmentstrictA lambda is assigned to a name where a
defwould give it that name -
tx0/python:late-module-importstrictA module-level import comes after other code
-
tx0/python:legacy-typing-genericstrictAn annotation uses
typing.List,Dictor another alias where the builtin type takes parameters -
tx0/python:legacy-union-syntaxstrictAn annotation uses
Optional[X]orUnion[X, Y]whereX | NoneandX | Ysay the same -
tx0/python:length-test-against-zerostrictThe length of a value is compared with zero where its truth value says the same
-
tx0/python:listen-on-any-addressstrictA socket or server is given the address
0.0.0.0or:: -
tx0/python:long-linestrictA line is wider than the configured number of characters
-
tx0/python:loop-yield-delegationstrictA
forloop only yields each item of an iterable, whichyield fromdoes directly -
tx0/python:many-instance-attributesstrictThe methods of a class assign more attributes of
selfthan the configured limit -
tx0/python:member-named-after-classstrictA method or attribute of a class has the class's own name
-
tx0/python:method-could-be-staticstrictA method never uses
self, so it does not need an instance -
tx0/python:method-name-stylestrictThe name of a method does not follow the configured case style
-
tx0/python:missing-final-newlinestrictA file does not end with a line break
-
tx0/python:missing-parameter-annotationstrictA parameter of a public function has no annotation
-
tx0/python:missing-return-annotationstrictA public function has no return annotation
-
tx0/python:module-name-stylestrictA file's name is not a lowercase module name
-
tx0/python:multiple-imports-per-linestrictOne
importstatement imports several modules -
tx0/python:multiple-statements-per-linestrictSeveral statements share one line, joined by
;or after the colon of a compound statement -
tx0/python:naive-datetime-nowstrictdatetime.now()ordatetime.today()makes a local time without a time zone -
tx0/python:needless-passstrictpassstands in a block that has other statements -
tx0/python:negated-comparisonstrictnotis applied to a comparison that has an operator for the opposite test -
tx0/python:none-comparisonstrictA value is compared with
Noneusing==or!= -
tx0/python:object-base-classstrictA class names
objectas its base, which every class already has -
tx0/python:open-without-encodingstrictA file is opened in text mode without an encoding, so it is read with the platform's default
-
tx0/python:parameter-name-stylestrictA parameter's name does not follow the configured case style
-
tx0/python:parenthesized-conditionstrictThe condition of
if,eliforwhile, or the value ofreturn, is wrapped in parentheses that do nothing -
tx0/python:regex-char-alternationstrictA group of a regular expression chooses between single characters with
| -
tx0/python:regex-plain-substitutionstrictre.subreplaces a pattern without special characters, whichstr.replacedoes without a regular expression -
tx0/python:regex-repeated-spacesstrictA pattern holds a run of spaces that is hard to count
-
tx0/python:regex-single-char-classstrictBrackets in a pattern wrap one letter or digit, which matches the same without them
-
tx0/python:regex-verbose-quantifierstrictA quantifier of a regular expression is written in a longer form than needed, or does nothing
-
tx0/python:repeated-prefix-teststrictstartswithorendswithis called several times on one value, joined withor -
tx0/python:shadowed-builtinstrictA variable hides a builtin of the same name
-
tx0/python:skip-without-reasonstrictA test is skipped or marked as an expected failure without a reason
-
tx0/python:subprocess-run-uncheckedstrictsubprocess.runis called withoutcheck, so a failing command goes unnoticed -
tx0/python:tab-indentationstrictA line is indented with tabs
-
tx0/python:todo-commentstrictA comment marks unfinished work with
TODO,FIXMEorXXX -
tx0/python:too-many-localsstrictA function binds more local variables than the configured limit
-
tx0/python:too-many-parametersstrictA function takes more parameters than the limit
-
tx0/python:too-many-returnsstrictA function has more
returnstatements than the limit -
tx0/python:undocumented-classstrictA public class has no docstring
-
tx0/python:undocumented-functionstrictA public function or method has no docstring
-
tx0/python:undocumented-modulestrictA module has no docstring
-
tx0/python:unencrypted-connectionstrictA connection is opened with FTP or Telnet, which encrypt nothing
-
tx0/python:vague-test-assertionstrictassertTrueorassertFalsetests a comparison that a specific assertion would report better -
tx0/python:variable-name-stylestrictA local variable's name does not follow the configured case style
-
tx0/python:wasteful-idiomstrictA builtin is used in a way that does more work than the result needs
-
tx0/python:whitespace-at-line-endstrictA line ends in spaces or tabs
-
tx0/python:zip-without-strictstrictzipis called on several iterables withoutstrict, so a length mismatch is silently cut off