[{"data":1,"prerenderedAt":3845},["ShallowReactive",2],{"son9Skqhar":3,"xCEoFPywez":50,"9KBZe8Dq6c":784,"iXczXQEsee":941},{"id":4,"name":5,"shortcode":6,"logo":7,"type":8,"version":9,"exampleConfig":10,"numIssues":11,"issueDistribution":12,"order":47,"url":48,"documentationUrl":49},"QW5hbHl6ZXI6bGtiZXZ6","Python","python","https://static.deepsource.com/analyzer_logos/python.svg?v=1784619987","CORE","v2.14.2","version = 1\n\n[[analyzers]]\nname = \"python\"\ndependency_file_paths = [\n  \"requirements/requirements_project.txt\"\n]\n\n  [analyzers.meta]\n  max_line_length = 100\n",577,[13,17,21,25,29,32,35,39,43],{"title":14,"category":15,"count":16},"Anti-pattern","ANTI_PATTERN",106,{"title":18,"category":19,"count":20},"Bug risk","BUG_RISK",217,{"title":22,"category":23,"count":24},"Coverage","COVERAGE",0,{"title":26,"category":27,"count":28},"Documentation","DOCUMENTATION",17,{"title":30,"category":31,"count":28},"Performance","PERFORMANCE",{"title":33,"category":34,"count":24},"Secrets","SECRETS",{"title":36,"category":37,"count":38},"Security","SECURITY",77,{"title":40,"category":41,"count":42},"Style","STYLE",87,{"title":44,"category":45,"count":46},"Type check","TYPECHECK",71,1,"/directory/python","https://docs.deepsource.com/docs/analyzers-python",[51,72,91,112,136,160,178,196,218,241,259,277,302,320,338,363,385,407,428,446,464,482,503,521,532,556,580,601,619,641,661,682,703,725,747,766],{"id":52,"name":53,"shortcode":54,"logo":55,"type":8,"version":56,"exampleConfig":57,"numIssues":28,"issueDistribution":58,"url":70,"documentationUrl":71},"QW5hbHl6ZXI6bnpucnd6","Ansible","ansible","https://static.deepsource.com/analyzer_logos/ansible.svg?v=1718563766","v0.4.7","version = 1\n\n[[analyzers]]\nname = \"ansible\"\n",[59,61,63,64,65,66,67,68,69],{"title":14,"category":15,"count":60},5,{"title":18,"category":19,"count":62},10,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":47},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":47},{"title":44,"category":45,"count":24},"/directory/ansible","https://docs.deepsource.com/docs/analyzers-ansible",{"id":73,"name":74,"shortcode":75,"logo":76,"type":8,"version":77,"exampleConfig":78,"numIssues":24,"issueDistribution":79,"url":89,"documentationUrl":90},"QW5hbHl6ZXI6YnJhcXB6","Apex","apex","https://static.deepsource.com/analyzer_logos/apex.svg?v=1790856406","v1.0.0","version = 1\n\n[[analyzers]]\nname = \"apex\"\n",[80,81,82,83,84,85,86,87,88],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/apex","https://docs.deepsource.com/docs/analyzers-apex",{"id":92,"name":93,"shortcode":94,"logo":95,"type":96,"version":97,"exampleConfig":98,"numIssues":99,"issueDistribution":100,"url":110,"documentationUrl":111},"QW5hbHl6ZXI6eGJheG16","AWS CloudFormation Linter","cfn-lint","/img/icon/language/aws-cfn.svg","COMMUNITY","0.83.0","version = 1\n\n[[analyzers]]\nname = \"cfn-lint\"\ntype = \"community\"\n",157,[101,102,103,104,105,106,107,108,109],{"title":14,"category":15,"count":99},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/cfn-lint","https://docs.deepsource.com/docs/analyzers-cfn-lint",{"id":113,"name":114,"shortcode":115,"logo":116,"type":8,"version":117,"exampleConfig":118,"numIssues":119,"issueDistribution":120,"url":134,"documentationUrl":135},"QW5hbHl6ZXI6bHpxbG5i","C & C++","cxx","https://static.deepsource.com/analyzer_logos/cxx.svg?v=1772450322","v0.18.2","version = 1\n\n[[analyzers]]\nname = \"cxx\"\n",151,[121,123,125,126,127,129,130,131,133],{"title":14,"category":15,"count":122},36,{"title":18,"category":19,"count":124},86,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":128},11,{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":62},{"title":40,"category":41,"count":132},8,{"title":44,"category":45,"count":24},"/directory/cxx","https://docs.deepsource.com/docs/analyzers-cxx",{"id":137,"name":138,"shortcode":139,"logo":140,"type":8,"version":141,"exampleConfig":142,"numIssues":143,"issueDistribution":144,"order":60,"url":158,"documentationUrl":159},"QW5hbHl6ZXI6cmJqeWF6","C#","csharp","https://static.deepsource.com/analyzer_logos/csharp.svg?v=1775822514","v0.51.2","version = 1\n\n[[analyzers]]\nname = \"csharp\"\n",304,[145,147,149,150,151,153,154,156,157],{"title":14,"category":15,"count":146},146,{"title":18,"category":19,"count":148},102,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":47},{"title":30,"category":31,"count":152},27,{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":155},28,{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/csharp","https://docs.deepsource.com/docs/analyzers-csharp",{"id":161,"name":162,"shortcode":163,"logo":164,"type":8,"version":77,"exampleConfig":165,"numIssues":24,"issueDistribution":166,"url":176,"documentationUrl":177},"QW5hbHl6ZXI6emFwbXZi","CSS","css","https://static.deepsource.com/analyzer_logos/css.svg?v=1790856402","version = 1\n\n[[analyzers]]\nname = \"css\"\n",[167,168,169,170,171,172,173,174,175],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/css","https://docs.deepsource.com/docs/analyzers-css",{"id":179,"name":180,"shortcode":181,"logo":182,"type":8,"version":77,"exampleConfig":183,"numIssues":24,"issueDistribution":184,"url":194,"documentationUrl":195},"QW5hbHl6ZXI6amJrZXdi","Dart","dart","https://static.deepsource.com/analyzer_logos/dart.svg?v=1790856403","version = 1\n\n[[analyzers]]\nname = \"dart\"\n",[185,186,187,188,189,190,191,192,193],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/dart","https://docs.deepsource.com/docs/analyzers-dart",{"id":197,"name":198,"shortcode":199,"logo":200,"type":96,"version":201,"exampleConfig":202,"numIssues":203,"issueDistribution":204,"url":216,"documentationUrl":217},"QW5hbHl6ZXI6bmJuYXd6","Dart Analyze","dart-analyze","https://static.deepsource.com/analyzer_logos/dart-analyze.svg?v=1772099075","3.2.0","version = 1\n\n[[analyzers]]\nname = \"dart-analyze\"\ntype = \"community\"\n",717,[205,207,209,210,211,212,213,214,215],{"title":14,"category":15,"count":206},174,{"title":18,"category":19,"count":208},543,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/dart-analyze","https://docs.deepsource.com/docs/analyzers-dart-analyze",{"id":219,"name":220,"shortcode":221,"logo":222,"type":8,"version":223,"exampleConfig":224,"numIssues":225,"issueDistribution":226,"url":239,"documentationUrl":240},"QW5hbHl6ZXI6eGR6bWF6","Docker","docker","https://static.deepsource.com/analyzer_logos/docker.svg?v=1773642773","v0.4.0","version = 1\n\n[[analyzers]]\nname = \"docker\"\n\n  [analyzers.meta]\n  dockerfile_paths = [\n    \"dev.dockerfile\",\n    \"prod.dockerfile\"\n  ]\n\n  trusted_registries = [\n    \"my-registry.com\",\n    \"docker.io\"\n  ]\n",85,[227,228,230,231,232,234,235,237,238],{"title":14,"category":15,"count":28},{"title":18,"category":19,"count":229},56,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":233},9,{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":236},2,{"title":40,"category":41,"count":47},{"title":44,"category":45,"count":24},"/directory/docker","https://docs.deepsource.com/docs/analyzers-docker",{"id":242,"name":243,"shortcode":244,"logo":245,"type":8,"version":77,"exampleConfig":246,"numIssues":24,"issueDistribution":247,"url":257,"documentationUrl":258},"QW5hbHl6ZXI6YmRweWVi","Elixir","elixir","https://static.deepsource.com/analyzer_logos/elixir.svg?v=1790856400","version = 1\n\n[[analyzers]]\nname = \"elixir\"\n",[248,249,250,251,252,253,254,255,256],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/elixir","https://docs.deepsource.com/docs/analyzers-elixir",{"id":260,"name":261,"shortcode":262,"logo":263,"type":8,"version":77,"exampleConfig":264,"numIssues":24,"issueDistribution":265,"url":275,"documentationUrl":276},"QW5hbHl6ZXI6YmdwbGt6","Erlang","erlang","https://static.deepsource.com/analyzer_logos/erlang.svg?v=1790856401","version = 1\n\n[[analyzers]]\nname = \"erlang\"\n",[266,267,268,269,270,271,272,273,274],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/erlang","https://docs.deepsource.com/docs/analyzers-erlang",{"id":278,"name":279,"shortcode":280,"logo":281,"type":8,"version":282,"exampleConfig":283,"numIssues":284,"issueDistribution":285,"order":292,"url":300,"documentationUrl":301},"QW5hbHl6ZXI6cmx6b2xi","Go","go","https://static.deepsource.com/analyzer_logos/go.svg?v=1787715483","v1.30.9","[[analyzers]]\n\nname = \"go\"\n\n  [analyzers.meta]\n  import_root = \"github.com/deepsourcelabs/webapp\"\n",394,[286,288,290,291,293,294,295,297,299],{"title":14,"category":15,"count":287},96,{"title":18,"category":19,"count":289},182,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":292},4,{"title":30,"category":31,"count":28},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":296},80,{"title":40,"category":41,"count":298},20,{"title":44,"category":45,"count":24},"/directory/go","https://docs.deepsource.com/docs/analyzers-go",{"id":303,"name":304,"shortcode":305,"logo":306,"type":8,"version":77,"exampleConfig":307,"numIssues":24,"issueDistribution":308,"url":318,"documentationUrl":319},"QW5hbHl6ZXI6YnZvZWd6","Groovy","groovy","https://static.deepsource.com/analyzer_logos/groovy.svg?v=1790856405","version = 1\n\n[[analyzers]]\nname = \"groovy\"\n",[309,310,311,312,313,314,315,316,317],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/groovy","https://docs.deepsource.com/docs/analyzers-groovy",{"id":321,"name":322,"shortcode":323,"logo":324,"type":8,"version":77,"exampleConfig":325,"numIssues":24,"issueDistribution":326,"url":336,"documentationUrl":337},"QW5hbHl6ZXI6emxyb2V6","Helm","helm","https://static.deepsource.com/analyzer_logos/helm.svg?v=1790856404","version = 1\n\n[[analyzers]]\nname = \"helm\"\n",[327,328,329,330,331,332,333,334,335],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/helm","https://docs.deepsource.com/docs/analyzers-helm",{"id":339,"name":340,"shortcode":341,"logo":342,"type":8,"version":343,"exampleConfig":344,"numIssues":345,"issueDistribution":346,"order":360,"url":361,"documentationUrl":362},"QW5hbHl6ZXI6bGJyZ3Z6","Java","java","https://static.deepsource.com/analyzer_logos/java.svg?v=1777531604","v0.81.0","version = 1\n\n[[analyzers]]\nname = \"java\"\n\n  [analyzers.meta]\n  runtime_version = 11\n  skip_doc_coverage = [ \"nonpublic\" ]\n",413,[347,349,351,352,353,355,356,358,359],{"title":14,"category":15,"count":348},119,{"title":18,"category":19,"count":350},183,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":132},{"title":30,"category":31,"count":354},33,{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":357},66,{"title":40,"category":41,"count":292},{"title":44,"category":45,"count":24},3,"/directory/java","https://docs.deepsource.com/docs/analyzers-java",{"id":364,"name":365,"shortcode":366,"logo":367,"type":8,"version":368,"exampleConfig":369,"numIssues":370,"issueDistribution":371,"order":236,"url":383,"documentationUrl":384},"QW5hbHl6ZXI6ZXJ6amFi","JavaScript","javascript","https://static.deepsource.com/analyzer_logos/javascript.svg?v=1781619307","v3.1.2","version = 1\n\n[[analyzers]]\nname = \"javascript\"\n\n  [analyzers.meta]\n  module_system = \"commonjs\"\n  environment = [\n    \"nodejs\",\n    \"browser\",\n    \"jest\",\n  ]\n\n  plugins = [\"react\"]\n  style_guide = \"airbnb\"\n  dialect = \"flow\"\n",659,[372,374,376,377,378,379,380,381,382],{"title":14,"category":15,"count":373},283,{"title":18,"category":19,"count":375},266,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":236},{"title":30,"category":31,"count":354},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":229},{"title":40,"category":41,"count":233},{"title":44,"category":45,"count":62},"/directory/javascript","https://docs.deepsource.com/docs/analyzers-javascript",{"id":386,"name":387,"shortcode":388,"logo":389,"type":8,"version":390,"exampleConfig":391,"numIssues":392,"issueDistribution":393,"url":405,"documentationUrl":406},"QW5hbHl6ZXI6cWJsdnhi","Kotlin","kotlin","https://static.deepsource.com/analyzer_logos/kotlin.svg?v=1745909268","v0.12.0","version = 1\n\n[[analyzers]]\nname = \"kotlin\"\n\n  [analyzers.meta]\n  language_version = \"1.8\"\n  runtime_version = \"17\"\n",81,[394,396,398,399,400,401,402,403,404],{"title":14,"category":15,"count":395},48,{"title":18,"category":19,"count":397},24,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":47},{"title":30,"category":31,"count":60},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":360},{"title":44,"category":45,"count":24},"/directory/kotlin","https://docs.deepsource.com/docs/analyzers-kotlin",{"id":408,"name":409,"shortcode":410,"logo":411,"type":96,"version":412,"exampleConfig":413,"numIssues":414,"issueDistribution":415,"url":426,"documentationUrl":427},"QW5hbHl6ZXI6cnpqdmF6","KubeLinter","kube-linter","/img/icon/language/kubernetes.svg","0.7.6","version = 1\n\n[[analyzers]]\nname = \"kube-linter\"\ntype = \"community\"\n",60,[416,418,419,420,421,422,423,424,425],{"title":14,"category":15,"count":417},59,{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":47},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/kube-linter","https://docs.deepsource.com/docs/analyzers-kube-linter",{"id":429,"name":430,"shortcode":431,"logo":432,"type":8,"version":77,"exampleConfig":433,"numIssues":24,"issueDistribution":434,"url":444,"documentationUrl":445},"QW5hbHl6ZXI6YnhxeGV6","Lua","lua","https://static.deepsource.com/analyzer_logos/lua.svg?v=1790856399","version = 1\n\n[[analyzers]]\nname = \"lua\"\n",[435,436,437,438,439,440,441,442,443],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/lua","https://docs.deepsource.com/docs/analyzers-lua",{"id":447,"name":448,"shortcode":449,"logo":450,"type":8,"version":77,"exampleConfig":451,"numIssues":24,"issueDistribution":452,"url":462,"documentationUrl":463},"QW5hbHl6ZXI6YnFxeW9i","Objective-C","objc","https://static.deepsource.com/analyzer_logos/objc.svg?v=1790856407","version = 1\n\n[[analyzers]]\nname = \"objc\"\n",[453,454,455,456,457,458,459,460,461],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/objc","https://docs.deepsource.com/docs/analyzers-objc",{"id":465,"name":466,"shortcode":467,"logo":468,"type":8,"version":77,"exampleConfig":469,"numIssues":24,"issueDistribution":470,"url":480,"documentationUrl":481},"QW5hbHl6ZXI6Ym93cnZi","Perl","perl","https://static.deepsource.com/analyzer_logos/perl.svg?v=1790856403","version = 1\n\n[[analyzers]]\nname = \"perl\"\n",[471,472,473,474,475,476,477,478,479],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/perl","https://docs.deepsource.com/docs/analyzers-perl",{"id":483,"name":484,"shortcode":485,"logo":486,"type":8,"version":487,"exampleConfig":488,"numIssues":489,"issueDistribution":490,"url":501,"documentationUrl":502},"QW5hbHl6ZXI6eXp5bHZi","PHP","php","https://static.deepsource.com/analyzer_logos/php.svg?v=1775798682","v0.32.0","version = 1\n\ntest_patterns = [\n  \"tests/**\",\n  \"test_e2e/**\"\n]\nexclude_patterns = [\n  \"vendor/**\"\n]\n\n[[analyzers]]\nname = \"php\"\n\n  [analyzers.meta]\n  bootstrap_files = [\"config/bootstrap.php\"]\n",114,[491,493,494,495,496,497,498,499,500],{"title":14,"category":15,"count":492},14,{"title":18,"category":19,"count":38},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":360},{"title":30,"category":31,"count":236},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":492},{"title":40,"category":41,"count":236},{"title":44,"category":45,"count":236},"/directory/php","https://docs.deepsource.com/docs/analyzers-php",{"id":504,"name":505,"shortcode":506,"logo":507,"type":8,"version":77,"exampleConfig":508,"numIssues":24,"issueDistribution":509,"url":519,"documentationUrl":520},"QW5hbHl6ZXI6enlkb3Ji","PowerShell","powershell","https://static.deepsource.com/analyzer_logos/powershell.svg?v=1790856407","version = 1\n\n[[analyzers]]\nname = \"powershell\"\n",[510,511,512,513,514,515,516,517,518],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/powershell","https://docs.deepsource.com/docs/analyzers-powershell",{"id":4,"name":5,"shortcode":6,"logo":7,"type":8,"version":9,"exampleConfig":10,"numIssues":11,"issueDistribution":522,"order":47,"url":48,"documentationUrl":49},[523,524,525,526,527,528,529,530,531],{"title":14,"category":15,"count":16},{"title":18,"category":19,"count":20},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":28},{"title":30,"category":31,"count":28},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":38},{"title":40,"category":41,"count":42},{"title":44,"category":45,"count":46},{"id":533,"name":534,"shortcode":535,"logo":536,"type":8,"version":537,"exampleConfig":538,"numIssues":143,"issueDistribution":539,"url":554,"documentationUrl":555},"QW5hbHl6ZXI6a2R6Z296","Ruby","ruby","https://static.deepsource.com/analyzer_logos/ruby.svg?v=1772452763","v0.16.8","version = 1\n\n[[analyzers]]\n\nname = \"ruby\"\n",[540,542,544,545,546,548,549,551,553],{"title":14,"category":15,"count":541},142,{"title":18,"category":19,"count":543},93,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":236},{"title":30,"category":31,"count":547},31,{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":550},23,{"title":40,"category":41,"count":552},13,{"title":44,"category":45,"count":24},"/directory/ruby","https://docs.deepsource.com/docs/analyzers-ruby",{"id":557,"name":558,"shortcode":559,"logo":560,"type":8,"version":561,"exampleConfig":562,"numIssues":563,"issueDistribution":564,"url":578,"documentationUrl":579},"QW5hbHl6ZXI6bnpuand6","Rust","rust","/img/icon/language/rust-black.svg","v0.13.7","version = 1\n\n[[analyzers]]\nname = \"rust\"\n\n  [analyzers.meta]\n  msrv = \"stable\"\n",247,[565,567,569,570,571,573,574,576,577],{"title":14,"category":15,"count":566},136,{"title":18,"category":19,"count":568},68,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":236},{"title":30,"category":31,"count":572},15,{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":575},26,{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/rust","https://docs.deepsource.com/docs/analyzers-rust",{"id":581,"name":582,"shortcode":583,"logo":584,"type":8,"version":585,"exampleConfig":586,"numIssues":587,"issueDistribution":588,"url":599,"documentationUrl":600},"QW5hbHl6ZXI6bGJxZG56","Scala","scala","https://static.deepsource.com/analyzer_logos/scala.svg?v=1719031873","v0.23.4","version = 1\n\ntest_patterns = [\n  \"src/test/scala/**\"\n]\n\nexclude_patterns = [\n  \"**/examples/**\"\n]\n\n[[analyzers]]\nname = \"scala\"\n",188,[589,591,592,593,594,595,596,597,598],{"title":14,"category":15,"count":590},82,{"title":18,"category":19,"count":296},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":47},{"title":30,"category":31,"count":128},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":236},{"title":40,"category":41,"count":132},{"title":44,"category":45,"count":292},"/directory/scala","https://docs.deepsource.com/docs/analyzers-scala",{"id":602,"name":33,"shortcode":603,"logo":604,"type":8,"version":605,"exampleConfig":606,"numIssues":357,"issueDistribution":607,"url":617,"documentationUrl":618},"QW5hbHl6ZXI6ZGJneG96","secrets","/img/icon/language/secrets.svg","v0.9.5","version = 1\ntest_patterns = [\n  \"test/**\",\n  \"test_e2e/**\"\n]\nexclude_patterns = [\n  \"**/examples/**\"\n]\n[[analyzers]]\nname = \"secrets\"\n",[608,609,610,611,612,613,614,615,616],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":357},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/secrets","https://docs.deepsource.com/docs/analyzers-secrets",{"id":620,"name":621,"shortcode":622,"logo":623,"type":8,"version":624,"exampleConfig":625,"numIssues":626,"issueDistribution":627,"url":639,"documentationUrl":640},"QW5hbHl6ZXI6a3pldnZi","Shell","shell","https://static.deepsource.com/analyzer_logos/shell.svg?v=1774603539","v0.7.0","version = 1\n\n[[analyzers]]\n\nname = \"shell\"\n",230,[628,630,632,633,634,635,636,637,638],{"title":14,"category":15,"count":629},35,{"title":18,"category":19,"count":631},186,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":60},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":47},{"title":40,"category":41,"count":360},{"title":44,"category":45,"count":24},"/directory/shell","https://docs.deepsource.com/docs/analyzers-shell",{"id":642,"name":643,"shortcode":644,"logo":645,"type":96,"version":646,"exampleConfig":647,"numIssues":543,"issueDistribution":648,"url":659,"documentationUrl":660},"QW5hbHl6ZXI6b3p3ZW56","Slither","slither","/img/icon/language/slither.png","0.10.1","version = 1\n\n[[analyzers]]\nname = \"slither\"\ntype = \"community\"\n",[649,651,652,653,654,655,656,657,658],{"title":14,"category":15,"count":650},88,{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":60},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/slither","https://docs.deepsource.com/docs/analyzers-slither",{"id":662,"name":663,"shortcode":664,"logo":665,"type":96,"version":666,"exampleConfig":667,"numIssues":668,"issueDistribution":669,"url":680,"documentationUrl":681},"QW5hbHl6ZXI6bHpwZWFi","Solhint","solhint","https://static.deepsource.com/analyzer_logos/solhint.svg?v=1772099076","4.1.1","version = 1\n\n[[analyzers]]\nname = \"solhint\"\ntype = \"community\"\n",52,[670,671,672,673,674,675,676,677,679],{"title":14,"category":15,"count":28},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":28},{"title":40,"category":41,"count":678},18,{"title":44,"category":45,"count":24},"/directory/solhint","https://docs.deepsource.com/docs/analyzers-solhint",{"id":683,"name":684,"shortcode":685,"logo":686,"type":8,"version":687,"exampleConfig":688,"numIssues":689,"issueDistribution":690,"url":701,"documentationUrl":702},"QW5hbHl6ZXI6Z296d25i","SQL","sql","https://static.deepsource.com/analyzer_logos/sql.svg?v=1718498446","v0.5.2","version = 1\n\n[[analyzers]]\nname = \"sql\"\n",55,[691,692,693,694,695,696,697,698,700],{"title":14,"category":15,"count":132},{"title":18,"category":19,"count":360},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":699},44,{"title":44,"category":45,"count":24},"/directory/sql","https://docs.deepsource.com/docs/analyzers-sql",{"id":704,"name":705,"shortcode":706,"logo":707,"type":8,"version":708,"exampleConfig":709,"numIssues":710,"issueDistribution":711,"url":723,"documentationUrl":724},"QW5hbHl6ZXI6eHpkbWFi","Swift","swift","https://static.deepsource.com/analyzer_logos/swift.svg?v=1721810582","v0.6.1","version = 1\n\n[[analyzers]]\nname = \"swift\"\n\n  [analyzers.meta]\n  swift_version = \"5.8\"\n  skip_doc_coverage = [\n    \"struct\",\n    \"enum\"\n  ]\n",83,[712,714,715,716,717,718,719,721,722],{"title":14,"category":15,"count":713},30,{"title":18,"category":19,"count":152},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":236},{"title":30,"category":31,"count":552},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":720},7,{"title":40,"category":41,"count":292},{"title":44,"category":45,"count":24},"/directory/swift","https://docs.deepsource.com/docs/analyzers-swift",{"id":726,"name":727,"shortcode":728,"logo":729,"type":8,"version":730,"exampleConfig":731,"numIssues":732,"issueDistribution":733,"url":745,"documentationUrl":746},"QW5hbHl6ZXI6b2x6cW5i","Terraform","terraform","https://static.deepsource.com/analyzer_logos/terraform.svg?v=1721154948","v0.4.1","version = 1\n\n[[analyzers]]\nname = \"terraform\"\n",160,[734,735,737,738,739,740,741,743,744],{"title":14,"category":15,"count":720},{"title":18,"category":19,"count":736},21,{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":360},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":742},158,{"title":40,"category":41,"count":47},{"title":44,"category":45,"count":24},"/directory/terraform","https://docs.deepsource.com/docs/analyzers-terraform",{"id":748,"name":749,"shortcode":750,"logo":751,"type":8,"version":752,"exampleConfig":753,"numIssues":360,"issueDistribution":754,"url":764,"documentationUrl":765},"QW5hbHl6ZXI6am16dmp6","Test coverage","test-coverage","https://static.deepsource.com/analyzer_logos/test-coverage.svg?v=1788147104","v0.30.17","version = 1\n\n[[analyzers]]\nname = \"test-coverage\"\n",[755,756,757,758,759,760,761,762,763],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":360},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/test-coverage","https://docs.deepsource.com/docs/analyzers-test-coverage",{"id":767,"name":768,"shortcode":769,"logo":770,"type":8,"version":77,"exampleConfig":771,"numIssues":24,"issueDistribution":772,"url":782,"documentationUrl":783},"QW5hbHl6ZXI6Ym13dndi","VB.NET","vbnet","https://static.deepsource.com/analyzer_logos/vbnet.svg?v=1790856405","version = 1\n\n[[analyzers]]\nname = \"vbnet\"\n",[773,774,775,776,777,778,779,780,781],{"title":14,"category":15,"count":24},{"title":18,"category":19,"count":24},{"title":22,"category":23,"count":24},{"title":26,"category":27,"count":24},{"title":30,"category":31,"count":24},{"title":33,"category":34,"count":24},{"title":36,"category":37,"count":24},{"title":40,"category":41,"count":24},{"title":44,"category":45,"count":24},"/directory/vbnet","https://docs.deepsource.com/docs/analyzers-vbnet",{"data":785,"body":787,"excerpt":-1,"toc":939},{"title":786,"description":786},"",{"type":788,"children":789},"root",[790,933],{"type":791,"tag":792,"props":793,"children":797},"element","pre",{"className":794,"code":795,"language":796,"meta":786,"style":786},"language-toml shiki shiki-themes github-light","version = 1\n\n[[analyzers]]\nname = \"python\"\ndependency_file_paths = [\n  \"requirements/requirements_project.txt\"\n]\n\n  [analyzers.meta]\n  max_line_length = 100\n\n","toml",[798],{"type":791,"tag":799,"props":800,"children":801},"code",{"__ignoreMap":786},[802,820,829,848,862,870,879,887,894,920],{"type":791,"tag":803,"props":804,"children":806},"span",{"class":805,"line":47},"line",[807,814],{"type":791,"tag":803,"props":808,"children":810},{"style":809},"--shiki-default:#24292E",[811],{"type":812,"value":813},"text","version = ",{"type":791,"tag":803,"props":815,"children":817},{"style":816},"--shiki-default:#005CC5",[818],{"type":812,"value":819},"1\n",{"type":791,"tag":803,"props":821,"children":822},{"class":805,"line":236},[823],{"type":791,"tag":803,"props":824,"children":826},{"emptyLinePlaceholder":825},true,[827],{"type":812,"value":828},"\n",{"type":791,"tag":803,"props":830,"children":831},{"class":805,"line":360},[832,837,843],{"type":791,"tag":803,"props":833,"children":834},{"style":809},[835],{"type":812,"value":836},"[[",{"type":791,"tag":803,"props":838,"children":840},{"style":839},"--shiki-default:#6F42C1",[841],{"type":812,"value":842},"analyzers",{"type":791,"tag":803,"props":844,"children":845},{"style":809},[846],{"type":812,"value":847},"]]\n",{"type":791,"tag":803,"props":849,"children":850},{"class":805,"line":292},[851,856],{"type":791,"tag":803,"props":852,"children":853},{"style":809},[854],{"type":812,"value":855},"name = ",{"type":791,"tag":803,"props":857,"children":859},{"style":858},"--shiki-default:#032F62",[860],{"type":812,"value":861},"\"python\"\n",{"type":791,"tag":803,"props":863,"children":864},{"class":805,"line":60},[865],{"type":791,"tag":803,"props":866,"children":867},{"style":809},[868],{"type":812,"value":869},"dependency_file_paths = [\n",{"type":791,"tag":803,"props":871,"children":873},{"class":805,"line":872},6,[874],{"type":791,"tag":803,"props":875,"children":876},{"style":858},[877],{"type":812,"value":878},"  \"requirements/requirements_project.txt\"\n",{"type":791,"tag":803,"props":880,"children":881},{"class":805,"line":720},[882],{"type":791,"tag":803,"props":883,"children":884},{"style":809},[885],{"type":812,"value":886},"]\n",{"type":791,"tag":803,"props":888,"children":889},{"class":805,"line":132},[890],{"type":791,"tag":803,"props":891,"children":892},{"emptyLinePlaceholder":825},[893],{"type":812,"value":828},{"type":791,"tag":803,"props":895,"children":896},{"class":805,"line":233},[897,902,906,911,916],{"type":791,"tag":803,"props":898,"children":899},{"style":809},[900],{"type":812,"value":901},"  [",{"type":791,"tag":803,"props":903,"children":904},{"style":839},[905],{"type":812,"value":842},{"type":791,"tag":803,"props":907,"children":908},{"style":809},[909],{"type":812,"value":910},".",{"type":791,"tag":803,"props":912,"children":913},{"style":839},[914],{"type":812,"value":915},"meta",{"type":791,"tag":803,"props":917,"children":918},{"style":809},[919],{"type":812,"value":886},{"type":791,"tag":803,"props":921,"children":922},{"class":805,"line":62},[923,928],{"type":791,"tag":803,"props":924,"children":925},{"style":809},[926],{"type":812,"value":927},"  max_line_length = ",{"type":791,"tag":803,"props":929,"children":930},{"style":816},[931],{"type":812,"value":932},"100\n",{"type":791,"tag":934,"props":935,"children":936},"style",{},[937],{"type":812,"value":938},"html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}",{"title":786,"searchDepth":236,"depth":236,"links":940},[],[942,948,953,958,963,968,973,978,983,988,993,998,1003,1008,1013,1018,1023,1028,1033,1038,1043,1048,1053,1058,1063,1068,1073,1078,1083,1088,1093,1098,1103,1108,1113,1118,1123,1128,1133,1138,1143,1148,1153,1158,1163,1168,1173,1178,1183,1188,1193,1198,1205,1210,1215,1220,1225,1230,1235,1240,1245,1250,1255,1260,1265,1270,1275,1280,1285,1290,1296,1301,1306,1311,1316,1321,1326,1331,1336,1341,1346,1351,1356,1363,1368,1373,1378,1383,1388,1393,1398,1403,1408,1413,1418,1423,1428,1432,1436,1440,1444,1448,1453,1458,1463,1468,1473,1478,1483,1488,1493,1498,1504,1509,1514,1519,1523,1528,1533,1538,1543,1548,1553,1558,1563,1568,1573,1578,1583,1588,1593,1598,1603,1607,1612,1617,1622,1628,1633,1638,1643,1649,1653,1658,1663,1668,1673,1678,1683,1688,1693,1698,1705,1711,1717,1723,1730,1735,1741,1747,1752,1757,1762,1767,1772,1777,1782,1787,1792,1797,1802,1807,1812,1817,1822,1827,1832,1837,1842,1847,1852,1857,1862,1867,1872,1877,1882,1887,1892,1897,1902,1907,1912,1917,1922,1927,1932,1937,1942,1947,1952,1957,1962,1967,1972,1977,1982,1987,1992,1997,2002,2007,2012,2017,2022,2027,2032,2037,2042,2047,2052,2057,2062,2067,2072,2077,2082,2087,2092,2097,2102,2107,2112,2117,2122,2127,2132,2137,2142,2147,2152,2157,2162,2167,2172,2177,2182,2187,2192,2197,2202,2207,2212,2217,2222,2227,2232,2238,2243,2248,2253,2258,2263,2268,2273,2278,2283,2288,2293,2298,2303,2308,2313,2318,2324,2329,2334,2339,2344,2349,2354,2359,2364,2369,2375,2380,2385,2390,2395,2400,2405,2410,2415,2420,2425,2430,2435,2440,2445,2450,2455,2460,2465,2470,2475,2480,2485,2490,2495,2499,2504,2509,2514,2519,2524,2529,2534,2540,2545,2550,2555,2560,2564,2569,2574,2579,2584,2589,2593,2598,2603,2608,2613,2618,2622,2626,2631,2636,2641,2646,2651,2656,2660,2665,2670,2675,2680,2684,2689,2694,2699,2704,2709,2714,2719,2724,2729,2735,2740,2745,2750,2755,2760,2765,2770,2775,2780,2784,2789,2793,2798,2805,2810,2817,2822,2826,2831,2836,2841,2846,2852,2857,2862,2867,2872,2877,2882,2887,2892,2897,2902,2907,2912,2917,2922,2927,2932,2937,2942,2947,2952,2957,2962,2967,2972,2977,2982,2987,2992,2997,3002,3007,3012,3017,3022,3027,3032,3037,3042,3048,3053,3058,3063,3068,3073,3078,3083,3088,3093,3098,3103,3108,3113,3118,3123,3128,3134,3139,3144,3149,3154,3159,3164,3169,3174,3179,3184,3189,3194,3199,3204,3210,3215,3220,3225,3230,3235,3242,3247,3252,3257,3262,3267,3272,3277,3281,3286,3290,3295,3300,3305,3310,3315,3320,3325,3330,3335,3340,3345,3350,3355,3359,3364,3368,3373,3378,3383,3388,3393,3398,3403,3408,3413,3418,3423,3428,3433,3438,3443,3448,3453,3458,3463,3468,3473,3478,3483,3488,3493,3498,3503,3508,3513,3518,3523,3528,3533,3538,3543,3547,3552,3557,3562,3567,3572,3577,3582,3587,3591,3596,3601,3606,3611,3615,3620,3625,3630,3635,3640,3645,3650,3655,3660,3665,3670,3675,3680,3685,3690,3695,3700,3705,3710,3715,3720,3725,3730,3735,3740,3745,3750,3755,3760,3765,3770,3775,3780,3789,3795,3800,3805,3812,3820,3825,3830,3835,3840],{"shortcode":943,"title":944,"description":945,"category":19,"severity":946,"tags":947,"isRecommended":825},"PYL-E0241","Class has duplicate bases","A class must not specify inheritance from another class more than once. Duplicate base classes will raise a `TypeError`.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass SomeClass(SomeBase, Unique, SomeBase):\n    ...\n```\n\n### Recommended\n```python\nclass SomeClass(SomeBase, Unique):\n    ...\n```","CRITICAL",[],{"shortcode":949,"title":950,"description":951,"category":19,"severity":946,"tags":952,"isRecommended":825},"PYL-E0111","Bad reversed sequence","The first argument to the `reversed()` builtin should be a sequence and the object type of the sequence should implement `__reversed__`, `__len__` and `__getitem__`.\nIn the issue raised, the argument is violating one or more of the condition mentioned above.\nPython will throw a `TypeError` during execution.\n\nExample:\n```python\nseq = reversed(None)  # Error here.\nbad_reversed = reversed({2, 4, 6, 8})  # Sets are not reversible too. Error here.\n```",[],{"shortcode":954,"title":955,"description":956,"category":19,"severity":946,"tags":957,"isRecommended":825},"PYL-E1129","Object which is not a context manager used with the `with` statement","The object used in the `with` statement doesn't implement the context manager protocol (enter/exit). This is an error.",[],{"shortcode":959,"title":960,"description":961,"category":19,"severity":946,"tags":962,"isRecommended":825},"PYL-E0712","Exception caught which does not inherit from `Exception`","For an exception to be caught, it must inherit from the `Exception` class.\n\n\u003C!--more-->\n### Bad practice\n```python\ntry:\n    if foo \u003C 5:\n        print('foo is small')\nexcept NotImplemented:  # This is not an error class!\n    print('Some error occured')\n```\n### Recommended\n### Bad practice\n```python\ntry:\n    if foo \u003C 5:\n        print('foo is small')\nexcept NotImplementedError:  # This is a valid error class\n    print('Some error occured')\n```",[],{"shortcode":964,"title":965,"description":966,"category":19,"severity":946,"tags":967,"isRecommended":825},"PYL-E1123","Unexpected keyword argument in function call","The function call has passed a keyword argument that doesn't correspond to one of the function's parameter names. This is an error.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef update_count(item, available=True)\n    if available:\n        count[item] += 1\n\nupdate_count(\"coffee\", is_available=True) # Wrong keyword arguemnt used\n```\n\n## Recommended:\n```python\ndef update_count(item, available=True)\n    if available:\n        count[item] += 1\n\nupdate_count(\"coffee\", available=False)\n```",[],{"shortcode":969,"title":970,"description":971,"category":19,"severity":946,"tags":972,"isRecommended":825},"PYL-E1124","Argument passed both by position and keyword in function call","The function call would result in assigning multiple values to a function parameter, one value from a positional argument and one from a keyword argument.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef square(a):\n    return a*a\n\nres = square(2, a=3)\n```\n\n## Recommended:\n```\ndef square(a):\n    return a*a\n\nres = square(a=3)",[],{"shortcode":974,"title":975,"description":976,"category":19,"severity":946,"tags":977,"isRecommended":825},"PYL-E1125","Missing mandatory keyword argument in function call","The function call does not pass a mandatory keyword-only argument. This is an error.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef func(foo, *args, test):\n    print(foo, test)\n\nfunc(10, 20, 30)  # Missing required keyword argument 'test'\n```\n### Recommended\n```python\ndef func(foo, *args, test):\n    print(foo, test)\n\nfunc(10, 20, 30, test=False)\n```",[],{"shortcode":979,"title":980,"description":981,"category":19,"severity":946,"tags":982,"isRecommended":825},"PYL-E1133","Non-iterable value used in an iterating context","A non-iterable value is being used in an iterating context, For example, a non-iterable value being passed into a `for` loop. This will raise a `TypeError`.\n\u003C!--more-->\n### Bad practice\nUsing a non-iterable as object in a loop.\n```python\ndef fx(val=None):\n    return val\n\n\nseq = fx()\nfor val in seq:\n    print(val)\n```\nBecause `seq` would be `None` which is not an iterable, this code snippet will raise an error.\n\n### Recommended\nMake sure only an iterable is passed to the iterator.\nIn our example, tweaking `fx` to always return an iterable will fix the problem:\n```python\ndef fx(val=None):\n    val = val or []\n    return val\n\n\nseq = fx()\nfor val in seq:\n    print(val)\n```",[],{"shortcode":984,"title":985,"description":986,"category":19,"severity":946,"tags":987,"isRecommended":825},"PYL-E0239","Inheritance is not from a class","Python classes can only inherit from a class. Inheriting from any other object is an error.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass MyClass:\n    pass\n\nmy_obj = MyClass()\n\nclass SubClass(my_obj):  # Not a class, will raise an error\n    pass\n```\n### Recommended\n```python\nclass MyClass:\n    pass\n\nmy_obj = MyClass()\n\nclass SubClass(MyClass):  # Extending a class\n    pass\n```\n\n## Exceptions\nIf a class used as the base is dynamically generated and returned by a function, the checker may not correctly understand its type at the moment.\nTherefore, it is recommended to prevent DeepSource from raising this issue again using a `# skipcq` pragma.\n\n## Reference\n- Python Docs for [inheritance](https://docs.python.org/3/tutorial/classes.html#inheritance).",[],{"shortcode":989,"title":990,"description":991,"category":19,"severity":946,"tags":992,"isRecommended":825},"PYL-E1205","Logging format string contains too many arguments","Too many arguments passed to the logging format string.\n\n\u003C!--more-->\n### Bad practice\n```python\nlogger.error(\"Failed to retrieve URL \", url)\n```\n\n### Recommended\n```python\nlogger.error(\"Failed to retrieve URL %s\", url)\n```",[],{"shortcode":994,"title":995,"description":996,"category":19,"severity":946,"tags":997,"isRecommended":825},"PYL-E1206","Logging format string contains too few arguments","Too few arguments are passed to the logging format string. Ensure that the number of arguments being passed to the logging call is the same as the number of arguments the format string can accept.\n\n\u003C!--more-->\n### Bad practice\n```python\nimport logging\nlogging.info('LOG: %s (%s)', \"E100\")  # Expected 2 arguments, got 1\n```\n### Recommended\n```python\nimport logging\nlogging.info('LOG: %s (%s)', \"Missing data\", \"E100\")\n```",[],{"shortcode":999,"title":1000,"description":1001,"category":19,"severity":946,"tags":1002,"isRecommended":825},"PYL-E1300","Invalid format character","An unsupported format character is used in the format string. It is recommended to check the format string once again and see if there is a need to escape some special character.\n\n\u003C!--more-->\n### Bad practice\n```python\nmarks = 84\nmy_string = 'Marks: %d%!' % (marks,)\n                    # ^ un-escaped `%` sign\n```\n### Recommended\n\nUse two `%` signs to print an actual `%` character in a format string\n\n```python\nmarks = 84\nmy_string = 'Marks: %d%%!' % (marks,)\nprint(my_string)  # Marks: 84%!\n```",[],{"shortcode":1004,"title":1005,"description":1006,"category":19,"severity":946,"tags":1007,"isRecommended":825},"PYL-E1306","Not enough arguments in format string","Format string do not contain enough arguments to unpack. This can cause an error.\n\n\u003C!--more-->\n### Bad practice\n```python\nprint('Hey {}, {} messaged you'.format('Bob'))\n```\n\n### Recommended\n```python\nprint('Hey {}, {} messaged you'.format('Bob', 'Alex'))\n```",[],{"shortcode":1009,"title":1010,"description":1011,"category":19,"severity":946,"tags":1012,"isRecommended":825},"PYL-W0631","Loop variable used outside the loop","Using a loop variable (i.e. defined by a for loop or a list comprehension or a generator expression) outside the loop can create subtle bugs, like the variable not being defined if the list was empty. Generally, you should avoid using loop variables outside the loop, or define them early.\n\n\u003C!--more-->\n### Bad practice\n```python\nfor i in items:\n    if item_name(i) == \"coffee\":\n        price = calculate_cost(i)\n\nprint(price) # raises `NameError` if `items` is empty\n```\n\n## Preferred:\n```python\nprice = None  # Define variable outside loop\nfor i in items:\n    if item_name(i) == \"coffee\":\n        price = calculate_cost(i)\n\nprint(price)\n```",[],{"shortcode":1014,"title":1015,"description":1016,"category":19,"severity":946,"tags":1017,"isRecommended":825},"PYL-E0118","Name used prior global declaration","A global variable is being accessed in a local scope before it has been defined with a `global` statement.\nDoing so will raise a `SyntaxError`.\n\n\u003C!--more-->\n### Bad practice\n```python\nvar = \"Some Value\"\n\n\ndef foo():\n    var = \"New value\"\n    global var\n    ...\n```\n\n### Preferred\n```python\nvar = \"Some Value\"\n\n\ndef foo():\n    global var\n    var = \"New value\"\n    ...\n```",[],{"shortcode":1019,"title":1020,"description":1021,"category":19,"severity":946,"tags":1022,"isRecommended":825},"PYL-E0119","Misplaced format function","The `format()` function is called on an object that is not a string. This is an error.\n\nIncorrect code:\n```python\nprint('value: {}').format(123)\n```\n\nCorrect code:\n```python\nprint('value: {}'.format(123))\n```",[],{"shortcode":1024,"title":1025,"description":1026,"category":19,"severity":946,"tags":1027,"isRecommended":825},"PYL-E0202","Method hidden by an attribute","When a method has the same name as an attribute (defined in the ancestor class or the same class), the attribute takes precedence and hides the method.\nPython will throw an error when the method is called.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass Example:\n    def __init__(self, pie=\"Apple\"):\n        self.pie = pie\n\n    def pie(self):\n        ...\n```\nHere, if the class is instantiated with a value for `pie`, the method `pie` would be hidden.\nSo, a function call like this: `Example(\"apple\").pie()` will raise a run time error &mdash; `TypeError: 'str' object is not callable`.\n\nIt is recommended to have different names for attributes and methods.\n### Recommended\n```python\nclass Example:\n    def __init__(self, pie=\"Apple\"):\n        self.pie = pie\n\n    def make_pie(self):  # No longer shadowed by self.pie\n        ...\n```",[],{"shortcode":1029,"title":1030,"description":1031,"category":19,"severity":946,"tags":1032,"isRecommended":825},"PYL-E0211","Method has no argument","A method which should have the bound instance as first argument has no argument defined.\nPython will throw an error when you'll try to call this method.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass Cls:\n    def some_method():\n        ...\n\n    @classmethod\n    def something():\n        ...\n```\n\n### Recommended\n```python\nclass Cls:\n    def some_method(self):\n        ...\n\n    @classmethod\n    def something(cls):\n        ...\n```",[],{"shortcode":1034,"title":1035,"description":1036,"category":19,"severity":946,"tags":1037,"isRecommended":825},"PYL-E0236","Invalid `slots` object","`__slots__` must contain only non-empty strings or an iterable/sequence of strings with variable names used by instances, otherwise it will raise a `TypeError` during runtime.\nIt is recommended to review the `__slots__` objects and make sure they are all strings.\n\u003C!--more-->\n### Problematic code:\n```python\nclass ExampleClass:\n    __slots__ = (\"a\", \"b\", \"\", 34)\n```\n\n### Recommended\n```python\nclass ExampleClass:\n    __slots__ = (\"a\", \"b\")\n```\n\n## References\n- Python documentation for [slots](https://docs.python.org/3/reference/datamodel.html#slots).\n\n**Note: During autofix, DeepSource will remove the invalid objects present in `__slots__`.**",[],{"shortcode":1039,"title":1040,"description":1041,"category":19,"severity":946,"tags":1042,"isRecommended":825},"FLK-F701","`break` statement used outside of a `while` or `for` loop","The `break` statement cannot not be used outside a loop. This will raise a\n`SyntaxError`",[],{"shortcode":1044,"title":1045,"description":1046,"category":19,"severity":946,"tags":1047,"isRecommended":825},"FLK-F407","an undefined __future__ feature name was imported","The imported name does not exist in the `__future__` package.",[],{"shortcode":1049,"title":1050,"description":1051,"category":19,"severity":946,"tags":1052,"isRecommended":825},"PYL-E0301","`iter` returns a non-iterator","The `__iter__` method of a class must return an iterator with a `__next__` method.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass MyIterator:\n    def __iter__(self):\n        return self\n```\n### Recommended\n```python\nclass MyIterator:\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        return 42\n```",[],{"shortcode":1054,"title":1055,"description":1056,"category":19,"severity":946,"tags":1057,"isRecommended":825},"PYL-E0303","Invalid return for `__len__`","The `__len__` method of a class must return a non-negative integer.\n\n### Bad practice\n```python\nclass BadLenOne:\n    \"\"\" __len__ returns a negative integer \"\"\"\n\n    def __len__(self):\n        return -1\n\n\nclass SecondBadLen(object):\n    \"\"\" __len__ returns non-int \"\"\"\n\n    def __len__(self):\n        return 3.0\n```\n\n### Recommended\nThis is valid:\n```python\nclass BadLenOne:\n    \"\"\" __len__ returns a non-negative integer \"\"\"\n\n    def __len__(self):\n        return 1\n```",[],{"shortcode":1059,"title":1060,"description":1061,"category":19,"severity":946,"tags":1062,"isRecommended":825},"PYL-E0604","Invalid object found in `__all__`","The `__all__` list must contain only strings. Having other kinds of objects is an error.\n\n\u003C!--more-->\n### Bad practice\nTrying to do this will give an error:\n```python\n__all__ = ['calculate', 'patch', diff]  # `diff` is not a string!\n```\n\n### Recommended\n```python\n__all__ = ['calculate', 'patch', 'diff']\n```\n\nNote: During Autofix, DeepSource will convert the invalid objects into a string.",[],{"shortcode":1064,"title":1065,"description":1066,"category":19,"severity":946,"tags":1067,"isRecommended":825},"PYL-E0633","Attempting to unpack a non-sequence object","Unpacking is supported only for sequence objects, like lists, sets, tuples, iterators or generators, etc.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef get_system_info():\n    return ['linux', '64-bit']\n\nsystem, architecture = get_system_info  # is a function, cannot be unpacked\nprint(system)\n```\n### Recommended\n```python\ndef get_system_info():\n    return ['linux', '64-bit']\n\nsystem, architecture = get_system_info()  # returns a list, can be unpacked\nprint(system)\n```",[],{"shortcode":1069,"title":1070,"description":1071,"category":19,"severity":946,"tags":1072,"isRecommended":825},"FLK-F704","`yield` or `yield from` statement used outside of a function","`yield` should not be used outside of a function. This will raise a\n`SyntaxError`",[],{"shortcode":1074,"title":1075,"description":1076,"category":19,"severity":946,"tags":1077,"isRecommended":825},"PYL-E1131","Unsupported binary operation","Binary operation being done between operands that do not support it. This can cause an error on execution.",[],{"shortcode":1079,"title":1080,"description":1081,"category":19,"severity":946,"tags":1082,"isRecommended":825},"FLK-F705","`return` statement used with arguments inside a generator","A return statement with arguments should not be used inside a generator.",[],{"shortcode":1084,"title":1085,"description":1086,"category":19,"severity":946,"tags":1087,"isRecommended":825},"FLK-F831","Duplicate argument in function definition","Two or more parameters in a function definition have the same name. All names in the function definition should be distinct.",[],{"shortcode":1089,"title":1090,"description":1091,"category":19,"severity":946,"tags":1092,"isRecommended":825},"PYL-E0238","Invalid slots object","An invalid slots value is found in class. Only a string, an iterable or a sequence is permitted. This is an error.\n\n#### Guilty Code:\n```python\nclass Bad:\n    __slots__ = list\n```\n\nAssigning an invalid object to `__slots__` would raise a `TypeError`.\nDuring autofix, DeepSource will replace the invalid object with `[]`.",[],{"shortcode":1094,"title":1095,"description":1096,"category":19,"severity":946,"tags":1097,"isRecommended":825},"PYL-E0240","Inconsistent method resolution order","The order in which other classes are specified for inheritance in a class matters. Python classes use the C3 linearization method to determine a method resolution ordering for each class, which ensures that for a class C, if a class C1 precedes a class C2 in the MRO of C then C1 should also precede C2 in the MRO of all subclasses of C.",[],{"shortcode":1099,"title":1100,"description":1101,"category":19,"severity":946,"tags":1102,"isRecommended":825},"PYL-E0703","Exception context set to something which is not an exception, nor None","The syntax `raise ... from ...` can be used only when the exception context is an exception, or `None`. Trying to do so with other object types is an error.",[],{"shortcode":1104,"title":1105,"description":1106,"category":19,"severity":946,"tags":1107,"isRecommended":825},"PYL-E1140","Dictionary key is unhashable","It is recommended to use immutable objects as keys in a dictionary. If you want to use complex objects, ensure that they are hashable.",[],{"shortcode":1109,"title":1110,"description":1111,"category":19,"severity":946,"tags":1112,"isRecommended":825},"FLK-E999","Invalid syntax","A Python syntax error is detected.",[],{"shortcode":1114,"title":1115,"description":1116,"category":19,"severity":946,"tags":1117,"isRecommended":825},"PYL-E0701","Bad `except` order found","Except clauses are not in the correct order (from the more specific to the more generic). Some exceptions will never reach the more specific error handlers because of this setup.\n\n\u003C!--more-->\n### Bad practice\n```python\nwhile True:\n  try:\n      int(input('Enter a number:'))\n      break\n  except BaseException:\n      print('Invalid input')\n  except KeyboardInterrupt:  # will never run, `BaseException` also catches `KeyboardInterrupt`\n      pass\n```\n### Recommended\nOrder your exceptions from most specific to least specific. In this case, `KeyboardInterrupt` should appear before `BaseException`:\n\n```python\nwhile True:\n  try:\n      int(input('Enter a number:'))\n      break\n  except KeyboardInterrupt:\n      pass\n  except BaseException:\n      print('Invalid input')\n```",[],{"shortcode":1119,"title":1120,"description":1121,"category":19,"severity":946,"tags":1122,"isRecommended":825},"PYL-E0702","Object of unsupported type raised","Raising objects other than a class, an instance or a string can cause a `TypeError`.\n\nThere can be cases where the value being raised is dynamically set. One common example is initially setting the value to `None` and assigning other objects based on a condition. Doing so can affect readability and is generally not recommended. In such cases, either re-write the block or ignore the issue for this file.\n\n\u003C!--more-->\n### Bad practice\n```python\nerror = None\nif not isinstance(foo, int):\n    error = TypeError('Expected foo to be of type int')\nelse:\n    error = ValueError('Unknown value')\n\nraise error\n```\n### Recommended\n```python\nif not isinstance(foo, int):\n    raise TypeError('Expected foo to be of type int')\nelse:\n    raise ValueError('Unknown value')\n```",[],{"shortcode":1124,"title":1125,"description":1126,"category":19,"severity":946,"tags":1127,"isRecommended":825},"PYL-E0704","The raise statement is not inside an except clause","A bare raise is used inside something which is not an `except` clause. This generates an error, since there are no active exceptions to be re-raised.\n\n\u003C!--more-->\n### Bad practice\n```python\nfor num in numbers:\n    if num == 0:\n        raise  # No error has been caught to re-raise, so this doesn't work.\n\n    inverse = 1 / num\n```\n### Recommended\nThe solution is to either only use a bare `raise` inside an `except` block, or to raise a new exception value:\n```python\nfor num in numbers:\n    if num == 0:\n        raise ValueError('Expected non-zero value')  # Works just fine\n\n    inverse = 1 / num\n```\n\nAn exception to this rule is represented by a bare raise inside a `finally` clause, which might work, as long as an exception is raised inside the `try` block, but that means it won't always work, which is a code smell that must not be relied upon.",[],{"shortcode":1129,"title":1130,"description":1131,"category":19,"severity":946,"tags":1132,"isRecommended":825},"PYL-E1130","Unary operand used on an unsupported object","A unary operand is used on an object which does not support this type of operation. This is an error.",[],{"shortcode":1134,"title":1135,"description":1136,"category":19,"severity":946,"tags":1137,"isRecommended":825},"FLK-F622","Two or more starred expressions in an assignment (a, *b, *c = d)","There are more than one starred expressions (*x) in an assignment. This is a SyntaxError.",[],{"shortcode":1139,"title":1140,"description":1141,"category":19,"severity":946,"tags":1142,"isRecommended":825},"PYL-E1111","Assigning result of a function call, where the function has no return","An assignment is done on a function call but the inferred function doesn't return anything. While this is not an error in Python, it is a critical anti-pattern and can lead to unexpected bugs.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef square(number):\n    '''Returns the square of a number'''\n    number ** 2  # Forgot a `return` here\n\nresult = square(4)\n```\n### Recommended\n```python\ndef square(number):\n    '''Returns the square of a number'''\n    return number ** 2\n\nresult = square(4)\n```",[],{"shortcode":1144,"title":1145,"description":1146,"category":19,"severity":946,"tags":1147,"isRecommended":825},"PYL-E1120","Missing argument in function call","A required function parameter isn't provided while calling the function. This is an error.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef add_student(student, section):\n    students[section].append(student)\n\nadd_student(\"Aaron\")  # Missing parameter `section`\n```\n\n### Recommended\n```python\ndef add_student(student, section):\n    students[section].append(student)\n\nadd_student(\"Aaron\", \"10A\")\n```",[],{"shortcode":1149,"title":1150,"description":1151,"category":19,"severity":946,"tags":1152,"isRecommended":825},"PYL-E1121","Too many positional arguments in function call","Too many positional arguments are provided while calling the function. Check the function signature of the function being called to make sure that you are passing the right arguments.\n\n\u003C!--more-->\n### Bad practice\n```python\nstring = 'abcd'\nstring.center(10, '=', ' ')  # center only takes 2 arguments\n```\n### Recommended\n```python\nstring = 'abcd'\nstring.center(10, '=')\n```",[],{"shortcode":1154,"title":1155,"description":1156,"category":19,"severity":946,"tags":1157,"isRecommended":825},"PYL-E0101","`return` found in `__init__`","The `__init__()` method is required to return `None`, but an explicit return value in its body was detected.\nReturning a value other than `None` will raise a `TypeError`.\nEven if the return value is `None` explicit return statement shall always be avoided.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass NotCorrect:\n    def __init__(self):\n        self.attr = 100\n        return self.attr\n\n\nclass ExplicitReturn:\n    def __init__(self):\n        self.attr = 100\n        return None\n```\n\n### Recommended\n```python\nclass Correct:\n    def __init__(self):\n        self.attr = 100\n\n\nclass NoReturn:\n    def __init__(self):\n        self.attr = 100\n```",[],{"shortcode":1159,"title":1160,"description":1161,"category":19,"severity":946,"tags":1162,"isRecommended":825},"PYL-E0104","`return` used outside of a function","Using a `return` statement only makes sense in the context of functions. Using it outside a function would raise a `SyntaxError`.\n\u003C!--more-->\n`return` in a loop would raise a `SyntaxError`:\n```python\nfor x in range(100):\n    if x == 45:\n        return\n    print(x)\n```\n\nBut, if this loop is inside a function, it is okay:\n```python\ndef my_func():\n    for x in range(100):\n        if x == 45:\n            return\n        print(x)\n```",[],{"shortcode":1164,"title":1165,"description":1166,"category":19,"severity":946,"tags":1167,"isRecommended":825},"PYL-E0105","`yield` used outside of function","Using a `yield` statement only makes sense in the context of functions.\nUsing it outside a function would raise a `SyntaxError`.\n\n\u003C!--more-->\n### Bad practice\n\n`yield` in a loop would raise a `SyntaxError`:\n```python\nfor x in range(100):\n    yield x\n```\n\n### Recommended\nBut, if this loop is inside a function, it works as it would convert the function into a generator:\n```python\ndef my_func():\n    for x in range(100):\n        yield x\n```",[],{"shortcode":1169,"title":1170,"description":1171,"category":15,"severity":946,"tags":1172,"isRecommended":825},"PYL-W0101","Statement not reachable on execution","This statement is unreachable, as the control flow will never reach upto this point. Consider removing this part of code or re-evaluating the control flow.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef count_pairs(users):\n    pairs = 0\n    for user in users:\n        if user.type == \"student\":\n            pairs += 1\n    return pairs\n    pairs /= 2  # \u003C-- Unreachable\n```\n\n### Preferred\n```python\ndef count_pairs(users):\n    pairs = 0\n    for user in users:\n        if user.type == \"student\":\n            pairs += 1\n    pairs /= 2\n    return pairs\n```",[],{"shortcode":1174,"title":1175,"description":1176,"category":19,"severity":946,"tags":1177,"isRecommended":825},"PYL-W0102","Dangerous default argument","Do not use a mutable like `list` or `dictionary` as a default value to an argument. Python’s default arguments are evaluated once when the function is defined. Using a mutable default argument and mutating it will mutate that object for all future calls to the function as well.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef my_function(elem, l=[]):\n    l.append(elem)\n    return l\n\nprint(my_function(2)) # [2]\nprint(my_function(5)) # [2, 5]\n```\n\n## Recommended:\n```python\ndef my_function(elem, l=None):\n    if l is None:\n        l = []\n    l.append(elem)\n    return l\n\nprint(my_function(2)) # [2]\nprint(my_function(5)) # [5]\n```",[],{"shortcode":1179,"title":1180,"description":1181,"category":19,"severity":946,"tags":1182,"isRecommended":825},"PYL-W0199","`assert` called on tuple","A call of `assert` on a tuple will always evaluate to `True` if the tuple is not empty, and will always evaluate to `False` if it is. If you meant to pass the 2nd argument as a message, it is recommended to remove the parenthesis around your assert values.\n\n\u003C!--more-->\n\n### Bad practice\n```python\ndef test_abc():\n    a = 1\n    assert (a != 1, \"Some message\")\n```\n\n### Recommended\n```python\ndef test_abc():\n    a = 1\n    assert a != 1, \"Some message\"\n```",[],{"shortcode":1184,"title":1185,"description":1186,"category":19,"severity":946,"tags":1187,"isRecommended":825},"PYL-W0705","Catching previously caught exception","An exception should be caught only once in a `try`-`except` block.\nIt is useless to catch the previously caught exception later in other else blocks as the previous exception block handling the exception would be executed every time.\n\n### Not preferred\n```python\ntry:\n    1 / 0\nexcept ZeroDivisionError:\n    print(\"Divided by zero\")\nexcept (OSError, ZeroDivisionError):\n    print(\"Handles an exception which was caught before.\")\n```\n\n### Preferred\n```python\ntry:\n    1 / 0\nexcept ZeroDivisionError:\n    print(\"Divided by zero\")\nexcept OSError:\n    print(\"Handles a unique exception\")\n```",[],{"shortcode":1189,"title":1190,"description":1191,"category":19,"severity":946,"tags":1192,"isRecommended":825},"PYL-W0706","Except handler raises immediately","Using `raise` as the first or only operator of an except handler is useless because it raises back the exception immediately.\nRemove the `raise` operator or the entire `try-except-raise` block.\n\n\u003C!--more-->\n### Bad practice\n```python\ntry:\n    run_transaction(transaction_id)\nexcept ValueError as e:\n    raise TransactionError(e)\nexcept:\n    raise  # This is unnecessary\n```\n\n### Preferred\n```python\ntry:\n    run_transaction(transaction_id)\nexcept ValueError as e:\n    raise TransactionError(e)\n```",[],{"shortcode":1194,"title":1195,"description":1196,"category":19,"severity":946,"tags":1197,"isRecommended":825},"PYL-W0716","Invalid operation on exceptions","An operation is being performed on an exception, which is not valid for the exception in question.\nPlease note: Binary operations between exceptions in except handlers are not valid.\n\u003C!--more-->\n### Bad practice\nOr operation is being performed on the exceptions here, which is an error:\n```python\ntry:\n    some_call()\nexcept (ValueError | TypeError):\n    pass\n```\n### Recommended\nIf the intention is to catch either of the two exceptions, a tuple would do the work:\n```python\ntry:\n    some_call()\nexcept (ValueError, TypeError):\n    pass\n```",[],{"shortcode":1199,"title":1200,"description":1201,"category":37,"severity":946,"tags":1202,"isRecommended":825},"PTC-W0029","Flask app detected with DEBUG mode enabled","Running Flask applications in debug mode results in the Werkzeug debugger being enabled. This includes a feature that allows arbitrary code execution. Documentation for both Flask and Werkzeug strongly suggests that debug mode should never be enabled on production systems.\n\u003C!--more-->\n### Bad practice\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef main():\n    return 'Hello!'\n\napp.run(debug=True)  # Don't do this\n```\n### Recommended\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef main():\n    return 'Hello!'\n\napp.run()\n```",[1203,1204],"a05","owasp-top-10",{"shortcode":1206,"title":1207,"description":1208,"category":19,"severity":946,"tags":1209,"isRecommended":825},"PYL-E0601","Variable used before assignment","This local variable name is being used before it is defined. This will throw an `UnboundLocalError`.\nIt is recommended to refactor this code.\n\n\u003C!--more-->\n\n### Bad practice\n```python\ndef used_before_assignment(a):\n    if x == a:  # x is defined in the next line\n        for x in [1, 2]:\n            pass\n```\n\n### Recommended\n```python\ndef correct_usage(a):\n    for x in [1, 2]:\n        if x == a:\n            pass\n```",[],{"shortcode":1211,"title":1212,"description":1213,"category":19,"severity":946,"tags":1214,"isRecommended":825},"PYL-E0602","Undefined name detected","The variable name is not defined where it is used.\nThis will lead to an error during the runtime.\nMake sure there is no typo. If the name was supposed to be imported, verify that you've actually imported the name.\n\n\u003C!--more-->\n### Bad practice\n```python\nimport os.path\n\nif os.path.exits('setup.cfg'):  # misspelled `exists`\n    print('Found config file')\n```\n\n### Preferred:\n```python\nimport os.path\n\nif os.path.exists('setup.cfg'):\n    print('Found config file')\n```",[],{"shortcode":1216,"title":1217,"description":1218,"category":19,"severity":946,"tags":1219,"isRecommended":825},"PYL-E0603","Undefined name detected in `__all__`","`__all__`  is a list of strings defining what objects in a module will be exported when `from \u003Cmodule> import *` is used on the module.\nHence, all the object names mentioned in `__all__` shall be defined in the module.\n\nThis issue is raised because `__all__` contains atleast one name (See issue title for the exact name) which is not defined in the module.\nWhen a wildcard import is attempted on the module with this guilty code, Python will throw an `AttributeError` while trying to import the undefined object.\n\u003C!--more-->\nHere is an example:\n\n`guilty.py`\n```python\ndef my_awesome_function():\n    print(\"This is my awesome function.\")\n\n__all__ = [\"my_awesome_function\", \"something_undefined\"]\n```\n\n`foo.py`\n```python\nfrom guilty import *\n\nmy_awesome_function()\n```\n\nWhen `foo.py` is run, Python will throw this error:\n`AttributeError: module 'guilty' has no attribute 'something_undefined'`\n\n*_Note: During autofixing this issue, DeepSource will remove all the undefined name. If the there's a missing comma which implicitly concatenate the names, DeepSource will separate all the concatenated strings._*\n\n### Bad practice\nIn the following snippet, `connection` and `frame` is undefined.\nThere's also a missing comma between `predict` and \"ClearMap\".\n```python\n...\n__all__ = [\"connection\", \"predict\" \"ClearMap\", \"frame\"]\n```\n\n### Recommended\nThe autofix will remove undefined `connection` and `frame` and add a comma between `predict` and \"ClearMap\".\n```python\n...\n__all__ = [\"predict\", \"ClearMap\"]\n```",[],{"shortcode":1221,"title":1222,"description":1223,"category":19,"severity":946,"tags":1224,"isRecommended":825},"PYL-W0601","`global` variable is undefined","A variable has been defined global in a nested scope which wasn't defined in the global namespace earlier.\nIn this case, python will create the variable in the global namespace.\nThis is confusing and can lead to runtime bugs.\n\n\u003C!--more-->\nHere's an example:\n```python\nIn [1]: def example():\n   ...:     global NOT_VAR\n   ...:     NOT_VAR = \"Setting value inside `example` function.\"\n   ...:\n\nIn [2]: # Accessing NOT_VAR will cause a `NameError` until `example` is called\n\nIn [3]: NOT_VAR\n---------------------------------------------------------------------------\nNameError                                 Traceback (most recent call last)\n\u003Cipython-input-3-fc2d63c1ce6d> in \u003Cmodule>\n----> 1 NOT_VAR\n\nNameError: name 'NOT_VAR' is not defined\n\nIn [4]: # After calling example, the variable is created in the global namespace.\n\nIn [5]: example()\n\nIn [6]: NOT_VAR\nOut[6]: 'Setting value inside `example` function.'\n```",[],{"shortcode":1226,"title":1227,"description":1228,"category":19,"severity":946,"tags":1229,"isRecommended":825},"PYL-E0242","Class variable conflicts with slots","`__slots__` contain a name which is same as class variable, thus raising a conflict.\nDuring execution, Python will raise a `ValueError` complaining of the conflict.\n\n\u003C!--more-->\n`__slots__` is a special attribute to explicitly declare data members (like properties) and deny the creation of `__dict__` and `__weakref__` (unless explicitly declared in `__slots__` or available in a parent).\n\nIf the name of any slot variable conflicts with any class variable, it is recommended to rename or remove it.\n\n### Bad practice\n```python\nclass C:\n    some_class_var = \"Foo\"\n    __slots__ = [\"some_class_var\", \"voila\"]\n\n    ...\n```\n\n### Recommended\n```python\nclass C:\n    some_class_var = \"Foo\"\n    __slots__ = [\"voila\"]\n\n    ...\n```\n\n## References\n- [slots](https://docs.python.org/3/reference/datamodel.html#slots)",[],{"shortcode":1231,"title":1232,"description":1233,"category":19,"severity":946,"tags":1234,"isRecommended":825},"PYL-E1701","not-async-context-manager","Async context manager is being used with an object that does not implement the async context management protocol (`__aenter__` and `__aexit__`).\nThis will raise `AttributeError` during runtime since the attributes `__aexit__` and `__aenter__` are missing.\n\n\u003C!--more-->\nYou can use following decorators to make an async context manager object:\n\n- For Python 3.7 and above: `asynccontextmanager` decorator from `contextlib`.\n- For Python 3.6: `asynccontextmanager` decorator from `async_genetator`.\n- For Python 3.5: You'd need to use both `asynccontextmanager` and `async_generator` from the package `async_generator`.\n\n### Bad practice\n```python\nclass ContextManager:\n    def __enter__(self):\n        pass\n\n    def __exit__(self, *exc):\n        pass\n\n\nasync def foo():\n    async with ContextManager():\n        pass\n```\n\n### Recommended\n```python\nclass AsyncContextManager:\n    def __aenter__(self):\n        pass\n\n    def __aexit__(self, *exc):\n        pass\n\n\nasync def foo():\n    async with AsyncContextManager():\n        pass\n```",[],{"shortcode":1236,"title":1237,"description":1238,"category":19,"severity":946,"tags":1239,"isRecommended":825},"PTC-W0055","Set size changed during iteration","Sets are represented by a hash table and adding or removing items while iterating over it will alter the iteration order.\nThis will cause a `RuntimeError`.\n\n\u003C!--more-->\nIf you need to modify the set during iteration, it is recommended to iterate over a [shallow copy]((https://docs.python.org/3/library/copy.html of the dictionary) of the set. A shallow copy creates a new object which stores the reference of the original elements.\n\nFor further reading, check\n\n- [Shallow copy in Python](https://docs.python.org/3/library/copy.html)\n\n### Bad practice\n```python\nmagic_numbers = {0, 1, 1, 2, 3, 5}\n\nfor elem in magic_numbers:\n    magic_numbers.add(get_next(elem))  # This will raise a `RuntimeError`.\n```\n\n### Recommended\n```python\nmagic_numbers = {0, 1, 1, 2, 3, 5}\n\nfor elem in magic_numbers.copy():\n    magic_numbers.add(get_next(elem))\n```\n\n## References\n- [Shallow copy in Python](https://docs.python.org/3/library/copy.html)",[],{"shortcode":1241,"title":1242,"description":1243,"category":19,"severity":946,"tags":1244,"isRecommended":825},"PY-W0076","Assigning to an attribute not defined in class `__slots__`","Assigning to an attribute which is not defined in the class slots will raise an error.\nIt is recommended to add the name in `__slots__`.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass E:\n    __slots__ = [\"foo\"]\n\n    def __init__(self):\n        self.not_foo = \"Not foo\"\n        self.not_bar = \"Not Bar\"\n```\n\n### Recommended\n```python\nclass E:\n    __slots__ = [\"foo\", \"not_foo\", \"not_bar\"]\n\n    def __init__(self):\n        self.not_foo = \"Not foo\"\n        self.not_bar = \"Not Bar\"\n```\n\nNote: During Autofix, DeepSource will add the missing names in `slots`.",[],{"shortcode":1246,"title":1247,"description":1248,"category":19,"severity":946,"tags":1249,"isRecommended":825},"PYL-W0711","Exception to catch is the result of a binary operation","If an except clause needs to catch multiple exceptions, they must be expressed as a parenthesized tuple, for example: ``except (ValueError, TypeError)``\nYou can look at the docs [here](https://docs.python.org/3/tutorial/errors.html#handling-exceptions).\nWhen `or` is used, only the first operand exception type of the conditional statement will be caught.\n\n\u003C!--more-->\n#### Here's the inconsistency:\n```python\nIn [1]: class Exc1(Exception):\n    ...:     pass\n    ...:\nIn [2]: class Exc2(Exception):\n    ...:     pass\n    ...:\nIn [3]: try:\n    ...:     raise Exc1()\n    ...: except Exc1 or Exc2:\n    ...:     print(\"caught!\")\n    ...:\n    caught!\nIn [4]: try:\n    ...:     raise Exc2()\n    ...: except Exc1 or Exc2:\n    ...:     print(\"caught!\")\n    ...:\n---------------------------------------------------------------------------\nExc2                                      Traceback (most recent call last)\n\u003Cipython-input-5-5d29c1589cc0> in \u003Cmodule>\n    1 try:\n----> 2     raise Exc2()\n    3 except Exc1 or Exc2:\n    4     print(\"caught!\")\n    5\nExc2:\n```",[],{"shortcode":1251,"title":1252,"description":1253,"category":19,"severity":946,"tags":1254,"isRecommended":825},"FLK-F706","`return` statement used outside of a function or method","A `return` statement should not be used outside of a function or method. This will raise a `SyntaxError`. Make sure that your code and indentation are correct.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef fibonacci(n):\n    '''Returns n'th fibonacci number'''\n    if n \u003C= 1:\n        return 1\n\nreturn fibonacci(n-1) + fibonacci(n-2)  # Bad indentation, returning outside function\n```\n### Recommended\n```python\ndef fibonacci(n):\n    '''Returns n'th fibonacci number'''\n    if n \u003C= 1:\n        return 1\n\n    return fibonacci(n-1) + fibonacci(n-2)\n```",[],{"shortcode":1256,"title":1257,"description":1258,"category":15,"severity":946,"tags":1259,"isRecommended":825},"PTC-W0010","File opened without the `with` statement","Opening a file using `with` statement is preferred as function `open` implements the context manager protocol that releases the resource when it is outside of the `with` block. Not doing so requires you to manually release the resource.\n\n\u003C!--more-->\n### Bad practice\n```python\nf = open('/tmp/.deepsource.toml', 'w')\nf.write(\"config file.\")\n\n# No `f.close()` statement: file may remain unaccessible\n```\n\n### Preferred:\n```python\nwith open('/tmp/.deepsource.toml', 'w') as f:\n    f.write(\"config file.\")\n```",[],{"shortcode":1261,"title":1262,"description":1263,"category":19,"severity":946,"tags":1264,"isRecommended":825},"PYL-E1305","Format string contains excess arguments","Format string has been given excess variables to unpack. This can cause an error.\n\u003C!--more-->\n### Bad practice\n```python\nprint('Hey Bob,{} sent you a message'.format('Bob', 'Alex'))\n```\n\n### Recommended\n```python\nprint('Hey {},{} sent you a message'.format('Bob', 'Alex'))\n```",[],{"shortcode":1266,"title":1267,"description":1268,"category":19,"severity":946,"tags":1269,"isRecommended":825},"PTC-W0014","Debugger activation detected","Debuggers should only be used temporarily and locally. It is highly recommended not to leave debug statements in checked-in code. This may cause your application to have unintended side-effects.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef some_function(values):\n    breakpoint()  # Will cause the code to stop and go into debug mode.\n    print(values)\n```\n\n### Recommended\nRemove the debugger statement:\n```python\ndef some_function(values):\n    print(values)\n```",[],{"shortcode":1271,"title":1272,"description":1273,"category":19,"severity":946,"tags":1274,"isRecommended":825},"PYL-E0100","`init` method converted to generator","The `__init__` method contains a `yield` statement, which converts it into a generator function. This is not allowed as `__init__` must return `None`. Any attempt to use `yield` in `__init__` will raise a `TypeError`.\n\n\nThe `__init__` method is a special method in Python classes that initializes new instances. It has strict requirements:\n- Must return `None` (implicitly or explicitly)\n- Cannot be a generator function (no `yield` statements)\n- Cannot return any other value\n\nHere's an example of incorrect usage:\n\n```python\nclass DataProcessor:\n    def __init__(self, data):\n        self.data = data\n        yield from self.process_data()  # TypeError: __init__() should return None\n\n    def process_data(self):\n        for item in self.data:\n            yield item * 2\n```\n\nTo fix this, you should:\n1. Remove any `yield` statements from `__init__`\n2. Move generator functionality to a separate method\n\nHere's the corrected version:\n\n```python\nclass DataProcessor:\n    def __init__(self, data):\n        self.data = data\n        # Initialize only, no generators\n\n    def process_data(self):\n        # Generator functionality belongs in a separate method\n        for item in self.data:\n            yield item * 2\n\n# Usage\nprocessor = DataProcessor([1, 2, 3])\nfor result in processor.process_data():\n    print(result)  # Outputs: 2, 4, 6\n```\n\nCommon mistakes that lead to this error:\n1. Trying to implement initialization and iteration in the same method\n2. Confusing `__init__` with `__iter__`\n3. Attempting to make the class itself iterable through `__init__`\n\nIf you need to make your class iterable, use the appropriate special methods instead:\n```python\nclass IterableDataProcessor:\n    def __init__(self, data):\n        self.data = data  # Clean initialization\n\n    def __iter__(self):\n        # Generator functionality belongs here\n        for item in self.data:\n            yield item * 2\n\n# Now the class itself is iterable\nprocessor = IterableDataProcessor([1, 2, 3])\nfor result in processor:\n    print(result)  # Outputs: 2, 4, 6\n```\n\nRemember:\n- `__init__` is for initialization only\n- Use `__iter__` for making a class iterable\n- Generator functionality should be in separate methods\n- `__init__` must implicitly or explicitly return `None`\n\n## References:\n- [Python Special Methods](https://docs.python.org/3/reference/datamodel.html#special-method-names)\n- [Python Generators](https://docs.python.org/3/tutorial/classes.html#generators)\n- [Python Iterator Protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types)",[],{"shortcode":1276,"title":1277,"description":1278,"category":19,"severity":946,"tags":1279,"isRecommended":825},"FLK-F702","`continue` statement outside of a `while` or `for` loop","Using a `continue` statement outside of a `while` or `for` loop is a syntax error in Python. The `continue` statement can only be used inside loops to skip the rest of the current iteration and move to the next one.\n\n\u003C!--more-->\n\nThe `continue` statement serves a specific purpose in loops:\n- It skips the remaining code inside the current loop iteration\n- Control flow jumps to the loop's condition check\n- If the condition is true, the next iteration begins\n\nHere's an example of incorrect usage:\n\n```python\ndef process_data(value):\n    if value \u003C 0:\n        continue  # SyntaxError: 'continue' not properly in loop\n    return value * 2\n```\n\nThe correct way would be to use `continue` within a loop:\n\n```python\ndef process_numbers(numbers):\n    results = []\n    for value in numbers:\n        if value \u003C 0:\n            continue  # Correctly skips negative numbers\n        results.append(value * 2)\n    return results\n```\n\nIf you need to skip execution in a non-loop context, consider using:\n- Early returns with `return`\n- Conditional statements with `if`/`else`\n- Function structure reorganization\n\n## References:\n- [Python continue statement documentation](https://docs.python.org/3/reference/simple_stmts.html#the-continue-statement)\n- [Python control flow tools](https://docs.python.org/3/tutorial/controlflow.html)",[],{"shortcode":1281,"title":1282,"description":1283,"category":19,"severity":946,"tags":1284,"isRecommended":825},"PYL-E0110","Abstract class instantiated","An attempt was made to create an instance of an abstract class that contains abstract methods. This will raise a `TypeError` because abstract classes are meant to serve as templates and cannot be instantiated directly until all their abstract methods are implemented.\n\n\u003C!--more-->\nAbstract classes in Python, defined using `abc.ABCMeta` as metaclass, serve as base classes that declare abstract methods which must be implemented by their concrete subclasses. Trying to create an instance of an abstract class will raise: `TypeError: Can't instantiate abstract class \u003Cclass_name> with abstract methods \u003Cmethod_name>`.\n\nHere's an example of incorrect usage:\n\n```python\nfrom abc import ABCMeta, abstractmethod\n\nclass Shape(metaclass=ABCMeta):\n    @abstractmethod\n    def area(self):\n        pass\n\n# This will raise TypeError\nshape = Shape()  # TypeError: Can't instantiate abstract class Shape with abstract methods area\n```\n\nTo fix this, you need to either create a concrete subclass that implements all abstract methods, or remove the `@abstractmethod` decorator if the class is meant to be instantiated.\n\nCommon scenarios where this error occurs:\n1. Accidentally instantiating the base class instead of a subclass\n2. Forgetting to implement all abstract methods in a subclass\n3. Using `@abstractmethod` on methods that should be concrete\n4. Misunderstanding the purpose of abstract classes\n\nRemember:\n- Abstract classes are meant to be inherited from, not instantiated\n- All abstract methods must be implemented in concrete subclasses\n- Abstract methods define an interface that subclasses must follow\n- If you need to create instances directly, don't mark the class or its methods as abstract\n\n## References:\n- [Python abc module documentation](https://docs.python.org/3/library/abc.html)\n- [PEP 3119 - Introducing Abstract Base Classes](https://www.python.org/dev/peps/pep-3119/)\n- [Abstract Base Classes in Python](https://docs.python.org/3/glossary.html#term-abstract-base-class)",[],{"shortcode":1286,"title":1287,"description":1288,"category":19,"severity":946,"tags":1289,"isRecommended":825},"PYL-E1132","Multiple values found for keyword argument","A function call contains multiple values for the same keyword argument. This results in a `TypeError` as Python does not allow duplicate keyword arguments in function calls.\n\n\u003C!--more-->\n\nThis error occurs when:\n- The same keyword argument is specified multiple times in a function call\n- A keyword argument is provided both positionally and as a keyword\n- Dictionary unpacking with `**` results in duplicate keys\n\nHere are examples of incorrect function calls:\n\n```python\n# Same keyword argument specified twice\ndef greet(name, age):\n    print(f\"{name} is {age} years old\")\n\ngreet(name=\"Alice\", name=\"Bob\")  # TypeError: multiple values for argument 'name'\n\n# Argument provided both positionally and as keyword\ngreet(\"Alice\", name=\"Bob\")  # TypeError: multiple values for argument 'name'\n\n# Duplicate keys when unpacking dictionaries\nuser1 = {\"name\": \"Alice\", \"age\": 25}\nuser2 = {\"name\": \"Bob\", \"age\": 30}\ngreet(**user1, **user2)  # TypeError: multiple values for argument 'name'\n```\n\nTo fix this, ensure that:\n1. Each keyword argument appears exactly once in the function call\n2. Arguments are not provided both positionally and as keywords\n3. When unpacking dictionaries, there are no overlapping keys\n\nThis error is particularly common when:\n- Merging dictionaries for function calls\n- Refactoring function calls with mixed positional and keyword arguments\n- Working with automated argument generation or dynamic function calls\n\n## References:\n- [Python Function Calls](https://docs.python.org/3/reference/expressions.html#calls)\n- [Python Keywords Arguments](https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments)\n- [PEP 3102 - Keyword-Only Arguments](https://www.python.org/dev/peps/pep-3102/)",[],{"shortcode":1291,"title":1292,"description":1293,"category":37,"severity":1294,"tags":1295,"isRecommended":825},"BAN-W1004","Audit required: Insecure cipher","Cipher used is not secure. It is recommended to replace with a known secure cipher such as AES.","MAJOR",[],{"shortcode":1297,"title":1298,"description":1299,"category":19,"severity":1294,"tags":1300,"isRecommended":825},"FLK-F602","Dictionary key variable name repeated with different values","All dictionary keys should be unique.",[],{"shortcode":1302,"title":1303,"description":1304,"category":15,"severity":1294,"tags":1305,"isRecommended":825},"PYL-R5103","Redundant `content_type` parameter for `JsonResponse()` detected","`JsonResponse()` contains `content_type` parameter. This is either redundant or the content_type is not JSON, which is probably an error.",[],{"shortcode":1307,"title":1308,"description":1309,"category":19,"severity":1294,"tags":1310,"isRecommended":825},"PYL-W1305","Combined specification detected for format string","Format string contains both automatic field numbering (e.g. `{}`) and manual field specification (e.g. `{0}`). This is an error. Please use only one of the specifications.",[],{"shortcode":1312,"title":1313,"description":1314,"category":19,"severity":1294,"tags":1315,"isRecommended":825},"PYL-E1507","Invalid value passed to access env variable","Env manipulation functions support only string type arguments.",[],{"shortcode":1317,"title":1318,"description":1319,"category":19,"severity":1294,"tags":1320,"isRecommended":825},"PYL-W1660","Accessed a removed attribute on the `sys` module","This attribute of `sys` module has been removed in Python 3. Please consult the documentation.",[],{"shortcode":1322,"title":1323,"description":1324,"category":19,"severity":1294,"tags":1325,"isRecommended":825},"PYL-W1606","Use of `execfile` built-in detected","The built-in function being accessed has been removed from Python 3. Please consult the [documentation](https://docs.python.org/3/library/functions.html#built-in-functions).",[],{"shortcode":1327,"title":1328,"description":1329,"category":15,"severity":1294,"tags":1330,"isRecommended":825},"PYL-R5102","`HttpResponse()` returns `application/json` content type","It is recommended to use `JsonResponse` to return JSON content.\n`HttpResponse(content_type='application/json)` can be replaced with just `JsonResponse()`.",[],{"shortcode":1332,"title":1333,"description":1334,"category":19,"severity":1294,"tags":1335,"isRecommended":825},"PYL-W1307","Invalid format index","Format string is using a lookup specifier e.g. `{a[1]}`, but the argument passed for formatting doesn't contain or doesn't have that key as an attribute.\nThis is an error.",[],{"shortcode":1337,"title":1338,"description":1339,"category":37,"severity":1294,"tags":1340,"isRecommended":825},"BAN-W1003","Audit required: Insecure hash function","D2, MD4, MD5, SHA1 signature algorithms are known to be vulnerable to collision attacks. Attackers can exploit this to generate another certificate with the same digital signature, allowing them to masquerade as the affected service.",[],{"shortcode":1342,"title":1343,"description":1344,"category":19,"severity":1294,"tags":1345,"isRecommended":825},"PTC-W0013","Debugger import detected","Debuggers should only be used temporarily and locally. It is highly recommended to remove debug statements in checked-in code.",[],{"shortcode":1347,"title":1348,"description":1349,"category":19,"severity":1294,"tags":1350,"isRecommended":825},"PYL-E0113","Invalid star assignment target","A star expression is being used as a starred assignment target.\nIn order to do that, the starred assignment target must be in a list or tuple,\notherwise Python will throw a `SyntaxError`.\n\n\u003C!--more-->\n### Bad practice\n```python\n*var = [1, 2, 3, 4]  # SyntaxError\n```\n\n### Recommended\n```python\n(*var,) = [1, 2, 3, 4]\n\n# This is also valid\nfoo, *var = [1, 2, 3, 4]\n```",[],{"shortcode":1352,"title":1353,"description":1354,"category":19,"severity":1294,"tags":1355,"isRecommended":825},"PYL-W1505","Method used has been deprecated","The method is marked as deprecated and will be removed in a future version of Python. Consider looking for an alternative in the documentation.",[],{"shortcode":1357,"title":1358,"description":1359,"category":37,"severity":1294,"tags":1360,"isRecommended":825},"BAN-B325","Use of `tempnam` detected","Use of `os.tempnam()` and `os.tmpnam()` is vulnerable to symlink attacks. Consider using `tmpfile()` instead.\n\n\u003C!--more-->\n### Bad practice\n```python\nimport os\n\nfilename = os.tmpnam()\nwith open(filename, 'w') as f:\n    # Do things with the file object\n```\n### Recommended\n```python\nimport os\n\nwith os.tmpfile() as f:\n    # Do things with the file object\n```",[1361,1362,1204],"a04","a06",{"shortcode":1364,"title":1365,"description":1366,"category":15,"severity":1294,"tags":1367,"isRecommended":825},"PTC-W0017","Redundant call","It is unnecessary to use, e.g., `list` around a list comprehension since it is equivalent without it.\nSame goes for `set` and `dict` comprehensions.\n\n\u003C!--more-->\n### Not preferred\n```python\nmy_list = list([i for i in range(10)])\nmy_set = set({i for i in range(10)})\nmy_dict = dict({i: i*i for i in range(10)})\n```\n### Preferred\n```python\nmy_list = [i for i in range(10)]\nmy_set = {i for i in range(10)}\nmy_dict = {i: i*i for i in range(10)}\n```",[],{"shortcode":1369,"title":1370,"description":1371,"category":19,"severity":1294,"tags":1372,"isRecommended":825},"PYL-E1128","Assigning result of a function call, where the function returns `None`","An assignment is done on a function call but the inferred function returns `None`. While this is allowed in Python, it is an anti-pattern and can lead to unexpected bugs.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef greet(name):\n    f'Hello, {name}!'  # Forgot to return the value\n\ngreeting = greet('John')\n```\n\n### Recommended\n```python\ndef greet(name):\n    return f'Hello, {name}!'\n\ngreeting = greet('John')\n```",[],{"shortcode":1374,"title":1375,"description":1376,"category":45,"severity":1294,"tags":1377,"isRecommended":825},"TYP-007","Unexpected return value","A return statement has been encountered in the callable which is not expected to return anything.",[],{"shortcode":1379,"title":1380,"description":1381,"category":19,"severity":1294,"tags":1382,"isRecommended":825},"PYL-E1134","Value is not a mapping","A non-mapping value is used in place where a mapping is expected. This is an error.\nIt is recommended to review the value and make sure you're not doing something wrong.\n\u003C!--more-->\n### Bad practice\n```python\ndef test(**kwargs):\n    print(kwargs)\n\ndict_value = dict(a=1, b=2, c=3)\nlist_value = [1, 2, 3]\n# This is an error, as a mapping was expected.\ntest(**list_value)\n```\n\n### Recommended\n```python\ndef test(**kwargs):\n    print(kwargs)\n\ndict_value = dict(a=1, b=2, c=3)\n# This is fine\ntest(**dict_value)\n```",[],{"shortcode":1384,"title":1385,"description":1386,"category":19,"severity":1294,"tags":1387,"isRecommended":825},"PYL-E1307","Bad string format type","The type required by this format string is not the same as the actual argument type. This can cause an error.\n\n\u003C!--more-->\n### Bad practice\n```python\nprint(\"%d\" % \"Cat\")  # %d expects an integer.\n```\n### Recommended\n```python\nprint(\"%s\" % \"Cat\")\nprint(\"%d\" % 43)\n```",[],{"shortcode":1389,"title":1390,"description":1391,"category":19,"severity":1294,"tags":1392,"isRecommended":825},"PYL-E1601","`print` statement detected","`print` is being used as a statement here. It has been converted to a function in Python 3. This will cause an error.\n\n\u003C!--more-->\n### Bad practice\n```python\nx = 1\nprint x\n```\n### Recommended\n```python\nx = 1\nprint(x)\n```",[],{"shortcode":1394,"title":1395,"description":1396,"category":15,"severity":1294,"tags":1397,"isRecommended":825},"PY-W0075","Consider using `all`","It is recommended to use `all` for this loop, as it will make your code smaller and more readable.\n\n\u003C!--more-->\n\n### Bad practice\n\n```python\ndef all_even(items):\n    for item in items:\n        if item % 2 != 0:\n            return False\n    return True\n```\n\n### Recommended\n\n```python\ndef all_even(items):\n    return all(item % 2 == 0 for item in items)\n```",[],{"shortcode":1399,"title":1400,"description":1401,"category":19,"severity":1294,"tags":1402,"isRecommended":825},"PYL-E1604","Old `raise` syntax deteted","The alternate raise syntax `raise SomeError, context` is used instead of `raise SomeError(context)`.\nThis has been deprecated and is a syntax error in Python 3.\n\u003C!--more-->\n### Bad practice\n```python\nraise SomeError, context\n```\n### Recommended\n```python\nraise SomeError(context)\n```",[],{"shortcode":1404,"title":1405,"description":1406,"category":15,"severity":1294,"tags":1407,"isRecommended":825},"PY-W0080","Prefer `list.extend(x)` over `list.append(*x)`","The `append` list method only takes one argument. So, if you have a list\n`items`, a call like `list.append(*items)` only works if `items` has a single\nelement in it. If there is more than one element in `items`, this code will crash.\n\nConsider using `list.extend(items)` instead of `list.append(*items)`, as the\nformer is more readable and will not crash when `items` contains multiple elements.\n\n\u003C!-- more -->\n\n## Bad practice\n\n```python\ntrees = ['Mango', 'Cedar']\nfavorite_tree = ['Oak']\n\ntrees.append(*favorite_tree)  # `append` is error-prone.\n```\n\n## Recommended\n\n```python\ntrees = ['Mango', 'Cedar']\nfavorite_tree = ['Oak']\n\ntrees.extend(favorite_tree)  # Prefer `extend`.\n```",[],{"shortcode":1409,"title":1410,"description":1411,"category":15,"severity":1294,"tags":1412,"isRecommended":825},"PYL-R0124","Comparison with itself","Comparison of an object with itself always returns `True`.\nThis is redundant.\n\n\u003C!--more-->\n### Bad practice\n```python\nif x >= x:\n    y = square(x)\n\nif y != y:\n    y = 0\n\nreturn y\n```\n\n### Recommended\n```python\ny = square(x)\n\nreturn y\n```",[],{"shortcode":1414,"title":1415,"description":1416,"category":15,"severity":1294,"tags":1417,"isRecommended":825},"PYL-R0203","No `@staticmethod` decorator","It is recommended to use the decorator syntax to declare a staticmethod.\nRead more about staticmethod [here](https://docs.python.org/3/library/functions.html#staticmethod)\n\u003C!--more-->\n### Not preferred\n```python\nclass MyClass:\n\n    def smethod():\n        '''static method-to-be'''\n\n    # Convert smethod to `staticmethod`\n    smethod = staticmethod(smethod)\n```\n\n### Preferred\n```python\nclass MyClass:\n\n    @staticmethod\n    def smethod():\n        '''static method-to-be'''\n```",[],{"shortcode":1419,"title":1420,"description":1421,"category":15,"severity":1294,"tags":1422,"isRecommended":825},"PYL-R1704","Argument redefined from local","A local name is redefining an argument, which might suggest a potential error. This is taken into account only for a handful of name binding operations, such as `for` iterations, `with` statements, and exception handler assignments.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef print_files(filename):\n    with open(filename) as f:\n        files = f.readlines()\n\n    for filename in files:  # `filename` is already defined outside!\n        print(filename)\n```\n### Recommended\n```python\ndef print_files(filename):\n    with open(filename) as f:\n        files = f.readlines()\n\n    for file in files:  # renamed it to `file` to avoid conflict\n        print(file)\n```",[],{"shortcode":1424,"title":1425,"description":1426,"category":15,"severity":1294,"tags":1427,"isRecommended":825},"PYL-W0104","Statement has no effect","The expression or statement is pointless and will not affect the program's execution. It should be removed.\n\n\u003C!--more-->\nIt is recommended to remove the statement as it adds unnecessary complexity to the codebase.\n### Bad practice\n```python\nx = input()\nx == 3  # Line doesn't do anything, it can be safely removed\n\ncalculate_res(x)\n```\n\n### Preferred:\n```python\nx = input()\n\ncalculate_res(x)\n```",[],{"shortcode":1429,"title":1430,"description":1324,"category":19,"severity":1294,"tags":1431,"isRecommended":825},"PYL-W1605","Use of `coerce` built-in detected",[],{"shortcode":1433,"title":1434,"description":1324,"category":19,"severity":1294,"tags":1435,"isRecommended":825},"PYL-W1607","Use of `file` built-in detected",[],{"shortcode":1437,"title":1438,"description":1324,"category":19,"severity":1294,"tags":1439,"isRecommended":825},"PYL-W1608","Use of `long` built-in detected",[],{"shortcode":1441,"title":1442,"description":1324,"category":19,"severity":1294,"tags":1443,"isRecommended":825},"PYL-W1610","Use of `reduce` built-in detected",[],{"shortcode":1445,"title":1446,"description":1324,"category":19,"severity":1294,"tags":1447,"isRecommended":825},"PYL-W1611","use of `standarderror` built-in detected",[],{"shortcode":1449,"title":1450,"description":1451,"category":19,"severity":1294,"tags":1452,"isRecommended":825},"PYL-W1640","Use of `cmp` argument detected","A custom comparator is being passed for sorting. In Python 3.0, the `cmp` parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the `__cmp__` methods).",[],{"shortcode":1454,"title":1455,"description":1456,"category":19,"severity":1294,"tags":1457,"isRecommended":825},"PYL-W1645","`message` attribute accessed on Exception","`Exception.message` has been removed in Python 3.\nIt is recommended to use `str(exception)` instead to access the exception message.",[],{"shortcode":1459,"title":1460,"description":1461,"category":19,"severity":1294,"tags":1462,"isRecommended":825},"PYL-W1647","Use of deprecated `sys.maxint` detected","`sys.maxint` has been removed in Python 3. It is recommended to use `sys.maxsize` instead.",[],{"shortcode":1464,"title":1465,"description":1466,"category":19,"severity":1294,"tags":1467,"isRecommended":825},"PYL-W0642","Assignment to `self` or `cls` detected","Assignment to `self` and `cls` is invalid and strongly discouraged. Doing so can cause errors when accessing the object or the class.\n\u003C!--more-->\n### Bad practice\n```python\nclass Foo:\n    def __init__(self, x):\n        self = x  # Does nothing\n```\n### Recommended\n```python\nclass Foo:\n    def __init__(self, x):\n        self.x = x\n```",[],{"shortcode":1469,"title":1470,"description":1471,"category":19,"severity":1294,"tags":1472,"isRecommended":825},"FLK-W606","`async` and `await` are reserved keywords starting with Python 3.7","Using these symbols as names can break your code in future versions of Python.\n\n\u003C!--more-->\nRenaming any variables named `async` or `await` in your code to something else will help in code migration later. You should rename the specific variable to something else.\n\n### Bad practice\n```python\ndef func(async=False):\n    print(async)\n```\n### Recommended\n```python\ndef func(is_async=False):\n    print(is_async)\n```",[],{"shortcode":1474,"title":1475,"description":1476,"category":15,"severity":1294,"tags":1477,"isRecommended":825},"PYL-R1712","Use `tuple` unpacking to swap variables","It is recommended not to use a temporary variable in order to swap variables. Using tuple unpacking to directly swap variables makes the intention more clear.\n\n\u003C!--more-->\n### Bad practice\nNot preferred:\n```python\ntemp = a\na = b\nb = temp\n```\n\n### Recommended\n```python\na, b = b, a\n```\nswaps the values of `a` and `b`.",[],{"shortcode":1479,"title":1480,"description":1481,"category":19,"severity":1294,"tags":1482,"isRecommended":825},"PYL-W1651","Use of a deprecated `itertools` function","The `itertools` function you're trying to access has been deprecated in Python 3.\nPlease consult the documentation [here](https://docs.python.org/3/library/itertools.html).\n\u003C!--more-->\nThe issue is raised for the following functions from the `itertools` module, that have been removed in the latest version of Python.\n\n- `izip`\n- `ifilter`\n- `imap`\n- `izip_longest`\n- `ifilterfalse`",[],{"shortcode":1484,"title":1485,"description":1486,"category":19,"severity":1294,"tags":1487,"isRecommended":825},"PYL-W1652","Use of a deprecated `types` field","The field being accessed has been deprecated in the `types` module in Python 3.\nPlease consult the documentation [here](https://docs.python.org/3/library/types.html).\n\u003C!--more-->\nThis issue is raised for the following `types`, that have been removed in the latest version of Python:\n\n- `EllipsisType`\n- `XRangeType`\n- `ComplexType`\n- `StringType`\n- `TypeType`\n- `LongType`\n- `UnicodeType`\n- `ClassType`\n- `BufferType`\n- `StringTypes`\n- `NotImplementedType`\n- `NoneType`\n- `InstanceType`\n- `FloatType`\n- `SliceType`\n- `UnboundMethodType`\n- `ObjectType`\n- `IntType`\n- `TupleType`\n- `ListType`\n- `DictType`\n- `FileType`\n- `DictionaryType`\n- `BooleanType`\n- `DictProxyType`",[],{"shortcode":1489,"title":1490,"description":1491,"category":19,"severity":1294,"tags":1492,"isRecommended":825},"PYL-W1658","Accessed a removed attribute on the `urllib` module","This attribute of `urllib` module has been removed or moved to Python 3. Please consult the documentation.",[],{"shortcode":1494,"title":1495,"description":1496,"category":19,"severity":1294,"tags":1497,"isRecommended":825},"PYL-W1659","Accessed the removed xreadlines attribute","This attribute has been removed in Python 3. Please consult the documentation.",[],{"shortcode":1499,"title":1500,"description":1501,"category":37,"severity":1294,"tags":1502,"isRecommended":825},"BAN-B315","Use of an insecure `expatreader` method","Using various XML methods to parse untrusted XML data is known to be vulnerable to XML attacks. Using the [defusedxml](https://pypi.org/project/defusedxml) module is recommended. Methods should be replaced with their `defusedxml` equivalents.",[1503,1362,1204],"a03",{"shortcode":1505,"title":1506,"description":1507,"category":19,"severity":1294,"tags":1508,"isRecommended":825},"FLK-F402","import module shadowed by loop variable","Loop variables should not redefine the name of modules that are imported.",[],{"shortcode":1510,"title":1511,"description":1512,"category":37,"severity":1294,"tags":1513,"isRecommended":825},"BAN-B411","Insecure `xmlrpclib` import detected","XMLRPC is particularly dangerous as it is also concerned with communicating data over a network. Use `defused.xmlrpc.monkey_patch()` function to monkey-patch xmlrpclib and mitigate remote XML attacks.",[1503,1362,1204],{"shortcode":1515,"title":1516,"description":1517,"category":37,"severity":1294,"tags":1518,"isRecommended":825},"BAN-B304","Audit required: Use of insecure cipher","Use of insecure cipher or cipher mode. Replace with a known secure cipher such as AES.",[],{"shortcode":1520,"title":1521,"description":1517,"category":37,"severity":1294,"tags":1522,"isRecommended":825},"BAN-B305","Audit required: Use of insecure cipher mode",[],{"shortcode":1524,"title":1525,"description":1526,"category":15,"severity":1294,"tags":1527,"isRecommended":825},"PYL-E0213","Method should have `self` as the first argument","The first argument of instance methods must be named `self`. This is considered an error since this convention is so common that you shouldn't break it.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass Car:\n    def __init__(this, color):\n        this.color = color\n    def run(this):\n        print(f'I am a {this.color} car')\n```\n### Recommended\n```python\nclass Car:\n    def __init__(self, color):\n        self.color = color\n    def run(self):\n        print(f'I am a {self.color} car')\n```",[],{"shortcode":1529,"title":1530,"description":1531,"category":37,"severity":1294,"tags":1532,"isRecommended":825},"BAN-W1005","Audit required: Insecure cipher mode","Use of insecure cipher mode such as `ECB` is not recommended for use in cryptographic protocols at all.\n\nIn case of `ECB`, it encrypts identical plaintext blocks into identical ciphertext blocks; and does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality.\n\nRead more about different cipher modes here --\n[https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#module-cryptography.hazmat.primitives.ciphers.modes](https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#module-cryptography.hazmat.primitives.ciphers.modes)",[],{"shortcode":1534,"title":1535,"description":1536,"category":31,"severity":1294,"tags":1537,"isRecommended":825},"PYL-W5198","New column added in database with a default value","The preferred way is to add a new DB column with `null=True` because it will be created instantly and then possibly populate the table with the desired default values. Adding a default value will lead to a performance issue if the existing table has a large number of rows.",[],{"shortcode":1539,"title":1540,"description":1541,"category":15,"severity":1294,"tags":1542,"isRecommended":825},"PYL-R0401","Cyclic import found","Cyclic imports shall be avoided.\nRead why are they fatal [here](https://datagrok.org/python/circularimports/).\n\nRead more about avoiding cyclic imports [here](https://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python).",[],{"shortcode":1544,"title":1545,"description":1546,"category":19,"severity":1294,"tags":1547,"isRecommended":825},"PYL-E1304","Undefined format string key","This format string with named placeholders is being used with a dictionary that doesn't contain all the keys required by the format string.\nThis is an error.\nPlease revisit the statement and add the necessary keys or remove them from the format string.\n\n#### Not Preferred:\n```python\ndef greet_user(user):\n    print(\n        \"Hi %(name)s!. Welcome to %(location)s.\"\n        % {\"name\": user.first_name, \"age\": user.age}\n    )\n```\n\n#### Preferred:\n```python\ndef greet_user(user):\n    print(\n        \"Hi %(name)s!. Welcome to %(location)s.\"\n        % {\"name\": user.first_name, \"location\": user.updated_loc}\n    )\n```",[],{"shortcode":1549,"title":1550,"description":1551,"category":19,"severity":1294,"tags":1552,"isRecommended":825},"PYL-E1302","Mixed format string","The format string contains both named (e.g. `%(foo)d`) and unnamed (e.g. `%d`) conversion specifiers.\nThis issue is also raised when the named conversion specifier contains * for the minimum field width and/or precision. This may give you an error.",[],{"shortcode":1554,"title":1555,"description":1556,"category":15,"severity":1294,"tags":1557,"isRecommended":825},"PYL-W1113","Keyword argument defined before variable positional arguments","On defining a keyword argument before variable positional arguments, one can end up in having multiple values passed for the aforementioned parameter in case the method is called with keyword arguments. It is recommended to define keyword arguments after variable positional arguments.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef create_list(double=False, *args):  # first argument will end up in `double`\n    return list(args)\n\nprint(create_list(1, 2, 3))  # prints `[2, 3]`\n```\n### Recommended\n```python\ndef create_list(*args, double=False):\n    return list(args)\n\nprint(create_list(1, 2, 3))  # prints `[1, 2, 3]`\n```",[],{"shortcode":1559,"title":1560,"description":1561,"category":15,"severity":1294,"tags":1562,"isRecommended":825},"PYL-W0604","Use of `global` at module level","The global statement is used to specify that the assignment to that name is an assignment to the variable in the global (module) scope, rather than in the local scope. At the module level, this statement is redundant because the local scope and global scope are the same.\nIt is recommended to remove the `global` statement.",[],{"shortcode":1564,"title":1565,"description":1566,"category":45,"severity":1294,"tags":1567,"isRecommended":825},"TYP-036","Type hint for with statement is unreliable","Type hint is unreliable for the `with` statement. Please check the issue occurrence message for details.",[],{"shortcode":1569,"title":1570,"description":1571,"category":19,"severity":1294,"tags":1572,"isRecommended":825},"FLK-F901","raising `NotImplemented` is not allowed","While returning `NotImplemented` would be fine, raising it doesn't work and will cause a `TypeError` because `NotImplemented` is not an exception type.\n\u003C!--more-->\n\n`NotImplemented` signals to the runtime that it should ask someone else to satisfy the operation. In the expression `a == b`, if `a.__eq__(b)` returns `NotImplemented`, then Python tries `b.__eq__(a)`. If `b` knows enough to return `True` or `False`, then the expression can succeed. If it doesn't, the runtime will fall back to the built-in behavior (based on identity for `==` and `!=`).\n\n### Bad practice\n\n```python\nclass MyClass:\n    def __lt__(self, other):\n        raise NotImplemented  # This will raise a TypeError, as NotImplemented cannot be raised\n```\n\n### Recommended\nIf you want to disallow comparison with this class completely:\n\n```python\nclass MyClass:\n    def __lt__(self, other):\n        raise NotImplementedError  # Will raise the exception\n```\n\nIf you want the comparison to be possible, and let Python figure out which\ncomparison operations will be possible by default, you can\n`return NotImplemented` instead:\n\n```python\nclass MyClass:\n    def __lt__(self, other):\n        return NotImplemented  # Will allow Python to figure out the fallback\n```",[],{"shortcode":1574,"title":1575,"description":1576,"category":19,"severity":1294,"tags":1577,"isRecommended":825},"PYL-W1626","Use of `reload` built-in detected","`reload()` builtin function has been removed in Python 3.\nIt is recommended to use `imp.reload()` or `importlib.reload()` instead.",[],{"shortcode":1579,"title":1580,"description":1581,"category":19,"severity":1294,"tags":1582,"isRecommended":825},"PYL-W1657","Accessed a removed attribute on the operator module","The attribute you are trying to access has been removed in the version of Python you are using (Python 3). Please consult the documentation.",[],{"shortcode":1584,"title":1585,"description":1586,"category":19,"severity":1294,"tags":1587,"isRecommended":825},"PYL-E0115","Name defined is both `nonlocal` and `global`","A name is being defined as `nonlocal` and `global` in the same scope.\nThis will error out in the runtime as a name can't be both `nonlocal` and `global`.\n\nThe `nonlocal` statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.\nIt is to note here that the names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope, which is being violated here.\n\nExample:\n```python\ndef func():\n    x = \"local\"\n\n    def nested():\n        nonlocal x\n        global x\n        x = \"nonlocal\"\n        ...\n```\n\nHere, x is `nonlocal` and `global`.\nPython will throw an error here `SyntaxError: name 'x' is nonlocal and global`",[],{"shortcode":1589,"title":1590,"description":1591,"category":19,"severity":1294,"tags":1592,"isRecommended":825},"FLK-F621","Too many expressions in an assignment with star-unpacking","Too many expressions found in starred assignment. This can be error prone.",[],{"shortcode":1594,"title":1595,"description":1596,"category":19,"severity":1294,"tags":1597,"isRecommended":825},"PYL-W1601","Use of `apply` built-in detected","The `apply` built-in function has been deprecated since Python 2.3.\nIt's use shall be avoided.\nUse `function(*args, **keywords)` instead of `apply(function, args, keywords)`\nRef: https://docs.python.org/2/library/functions.html#apply",[],{"shortcode":1599,"title":1600,"description":1601,"category":15,"severity":1294,"tags":1602,"isRecommended":825},"PYL-R1701","Consider merging `isinstance` calls","You can pass a tuple of types you want to check as the second argument to `isinstance`.\nIf the object matches with any of the types, it will return `True` else `False`.\n\nIt is therefore recommended to merge multiple consecutive `isinstance` calls into one. It is clearer and improves readability.\n\n```python\n# Instead of\nif isinstance(i, int) or isinstance(i, float):\n    print('A number')\n\n# Do this\nif isinstance(i, (int, float)):\n    print('A number')\n```",[],{"shortcode":1604,"title":1605,"description":1324,"category":19,"severity":1294,"tags":1606,"isRecommended":825},"PYL-W1604","Use of `cmp` built-in detected",[],{"shortcode":1608,"title":1609,"description":1610,"category":19,"severity":1294,"tags":1611,"isRecommended":825},"FLK-F707","`except:` is not the last exception handler","All exception handlers should be placed before an empty `except` block.\nA bare exception catcher will catch any exception it encounters making the exception handlers after it useless.\n\n#### Not Preferred:\n```python\ntry:\n    some_func()\n\nexcept Exception1:\n    some_handler()\n\nexcept:\n    general_handler()\n\nexcept Exception2:\n    some_other_handler()\n```\n\n#### Preferred\n```python\ntry:\n    some_func()\n\nexcept Exception1:\n    some_handler()\n\nexcept Exception2:\n    some_other_handler()\n\nexcept:\n    general_handler()\n```",[],{"shortcode":1613,"title":1614,"description":1615,"category":31,"severity":1294,"tags":1616,"isRecommended":825},"PYL-C1802","Built-in function `len` used as condition","Using the `len` function to check if a sequence is empty is not idiomatic and can be less performant than checking the truthiness of the object.\n\n`len` doesn't know the context in which it is called, so if computing the length means traversing the entire sequence, it must; it doesn't know that the result is just being compared to 0.\nComputing the boolean value can stop after it sees the first element, regardless of how long the sequence actually is.\n\nNot preferred:\n```python\nif not len(my_sequence):\n    print(\"Empty sequence.\")\nelse:\n    print(\"Sequence is not empty.\")\n```\n\nPreferred:\n```python\nif not my_sequence:\n    print(\"Empty sequence.\")\nelse:\n    print(\"Sequence is not empty.\")\n```",[],{"shortcode":1618,"title":1619,"description":1620,"category":19,"severity":1294,"tags":1621,"isRecommended":825},"PYL-E1303","Format needs mapping","The format string that uses named conversion specifiers is used with an argument that is not a mapping. This will raise a `TypeError`.\nIt is recommended to convert the argument into a mapping, e. g. a dictionary.",[],{"shortcode":1623,"title":1624,"description":1625,"category":37,"severity":1294,"tags":1626,"isRecommended":825},"BAN-B323","Use of `_create_unverified_context` detected","By default, Python will create a secure, verified ssl context for use in such classes as `HTTPSConnection`. However, it still allows using an insecure context via the `_create_unverified_context` that reverts to the previous behavior that does not validate certificates or perform hostname checks.\n\nIt is recommended to replace this call with the default HTTPS context.",[1627,1362,1204],"a02",{"shortcode":1629,"title":1630,"description":1631,"category":45,"severity":1294,"tags":1632,"isRecommended":825},"TYP-002","No return value expected","Callable is returning a value where no return value was expected.\n\u003C!--more-->\nThis usually means you didn't update your function's signature after updating its body, or you accidentally returned something you didn't mean to.\n### Bad practice\n```python\ndef main() -> None:\n    try:\n        run_app()\n    except:\n        return 1\n\n    return 0\n```\n### Recommended\nTwo ways to fix this would be to either update the signature:\n```python\ndef main() -> int:  # Returning an int\n    try:\n        run_app()\n    except:\n        return 1\n\n    return 0\n```\nor, to not return anything instead:\n```python\nimport sys\n\ndef main() -> None:\n    try:\n        run_app()\n    except:\n        sys.exit(1)  # Instead of returning, we can exit\n```",[],{"shortcode":1634,"title":1635,"description":1636,"category":19,"severity":1294,"tags":1637,"isRecommended":825},"PYL-W0111","Assignment to a new keyword","A variable whose identifier is a keyword in a future Python release is assigned a value. This variable, which is currently named properly, will result in an error in the next Python version. It is recommended that you rename this variable.\n\u003C!--more-->\n### Bad practice\n```python\n# This is a SyntaxError starting from Python 3.7\nasync = \"async\"\nawait = \"await\"\n```",[],{"shortcode":1639,"title":1640,"description":1641,"category":15,"severity":1294,"tags":1642,"isRecommended":825},"PYL-W0622","Re-definition found for builtin function","Defining a local variable or function with the same name as a built-in object makes the built-in object unusable within the current scope and makes the code prone to bugs.\n\n\u003C!--more-->\n### Bad practice\n```python\ndict = {}  # dict is a Python builtin!\nfor idx, student in enumerate(students):\n    dict[student] = idx\n```\n### Preferred:\n```python\nroll_number = {}\nfor idx, student in enumerate(students):\n    roll_number[student] = idx\n```",[],{"shortcode":1644,"title":1338,"description":1645,"category":37,"severity":1294,"tags":1646,"isRecommended":825},"PTC-W1003","D2, MD4, MD5, SHA1 signature algorithms are known to be vulnerable to [collision attacks](https://en.wikipedia.org/wiki/Collision_attack). Attackers can exploit this to generate another certificate with the same digital signature, allowing them to masquerade as the affected service.\n\n\u003C!--more-->\nA hash function takes a variable-length digital input and coverts it into a fixed-length random hash value. \n\nHasing algorthems like MD5 and SHA-1 are [vulnerable](http://merlot.usc.edu/csac-f06/papers/Wang05a.pdf) to collision attacks. In a collision attack an attacker finds two messages with the same hashed output and sends the incorrect one to the receiver.\n\nIt is recommended to use safer alternatives, such as SHA-256, SHA-512, SHA-3.\n\n### Bad practice\n```python\nimport hashlib\nimport Crypto\n\nm1 = hashlib.md5() # Insecure, Use of MD5\nm2 = hashlib.sha1() # Insecure, Use of SHA1\nm3 = Crypto.Hash.MD5.new() # Insecure, Use of MD5\n```\n\n### Recommended\n\nIt is recommended to either use stronger hash algorithms:\n\n```python\nimport hashlib\nimport Crypto\n\nm1 = hashlib.sha512()\nm2 = hashlib.sha256()\nm3 = Crypto.Hash.SHA256.new()\n```\n\nOR, if the use-case is not security sensitive, set the `usedforsecurity` argument\nto `False` as a way to signal that:\n\n```python\nimport hashlib\n\nhasher = hashlib.md5(usedforsecurity=False)  # issue will no longer be raised.\n```\n\n## References:\n- OWASP Top 10 2021 Category A02 - [Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [CWE 327](hhttps://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm\n- [Breaking MD5 and other hash functions](http://merlot.usc.edu/csac-f06/papers/Wang05a.pdf)",[1647,1627,1648,1362,1204],"cwe","cwe-327",{"shortcode":1650,"title":1651,"description":1324,"category":19,"severity":1294,"tags":1652,"isRecommended":825},"PYL-W1612","Use of `unicode` built-in detected",[],{"shortcode":1654,"title":1655,"description":1656,"category":15,"severity":1294,"tags":1657,"isRecommended":825},"PYL-R5101","`HttpResponse` used to return JSON response","It is recommended to use `JsonResponse` to return JSON data instead of HttpResponse.\n`HttpResponse(json.dumps(data))` can be replaced with `JsonResponse(data)`, where `data` is a JSON-serializable object.",[],{"shortcode":1659,"title":1660,"description":1661,"category":15,"severity":1294,"tags":1662,"isRecommended":825},"PYL-R1715","Use `get()` method to access values from a dictionary","In case of checking if key exists in the dictionary and then fetching the value, it is recommended to use the built-in method `dict.get(key[, default])`.\n\u003C!--more-->\nA pattern where you first ensure if a key exist in a dictionary and then get the value requires the dictionary lookup twice, which can be avoided by using `get`.\n`get()` returns the respective value if key exists in the dictionary, else returns a default value, avoiding the dictionary lookup twice.\n\n### Bad practice\n```python\nif key in my_mapping:\n    value = my_mapping[key]\nelse:\n    value = \"Not Found\"\n```\n\n### Recommended\n```python\nvalue = my_mapping.get(key, \"Not Found\")\n```\n\nNote: DeepSource has stopped raising this issue when multiple keys are checked to set the value. Using `get` here would make code hard to read.**\n\n```python\ndictionary = {}\nif 'key1' in dictionary: \n    variable = dictionary['key1']\nelif 'key2' in dictionary:  # Issue not raised\n    variable = dictionary['key2']\nelse:\n    variable = 'default'\n```",[],{"shortcode":1664,"title":1665,"description":1666,"category":19,"severity":1294,"tags":1667,"isRecommended":825},"PTC-W0021","I/O operation on a closed file detected","The I/O operation is being performed on a resource that is closed.\nThis will lead to a runtime error.\nIt is recommended to perform I/O operation on files inside `with` blocks, as the file is automatically closed when the scope of `with` ends.\n\u003C!--more-->\n### Bad practice\nThis is a very visible case of an I/O operation on a closed resource.\n```python\nfp = open(resource_path, \"w\")\n# do some operations on fp\nfp.close()\n# some code\n\nfp.write(\"This will throw an error!\")\n```\n\n### Recommended\nIt is best to use a `with` statement context maneger here. Using `with`, you don't need to worry about closing the resource when you're done using it.\n```python\nwith open(resource_path, \"w\") as fp:\n    # Do some operations on fp\n    ...\n```\n\n## References:\n- Python Docs - [`with` statements](https://docs.python.org/3/reference/compound_stmts.html#with).\n- Python Docs - [`with` statement context managers](https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers).",[],{"shortcode":1669,"title":1670,"description":1671,"category":19,"severity":1294,"tags":1672,"isRecommended":825},"PYL-W0150","Exception might be lost","The `finally` block may swallow any exceptions raised in the `try` block. This can pose a bug risk.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef some_function():\n    try:\n        with open('myfile.txt') as file:\n            data = file.read()\n    except FileNotFoundError:\n        print(fnf_error)\n    finally:\n        return data\n```\n\n### Recommended\n```python\ndef some_function():\n    try:\n        with open('myfile.txt') as file:\n            data = file.read()\n    except FileNotFoundError:\n        print(fnf_error)\n\n    return data\n```",[],{"shortcode":1674,"title":1675,"description":1676,"category":19,"severity":1294,"tags":1677,"isRecommended":825},"PYL-W0404","Multiple imports for an import name detected","A module or an import name is reimported multiple times. This can be confusing and should be fixed.\nPlease refer to the occurrence message to see the reimported name and the line number where it was imported for the first time.\n\n\u003C!--more-->\n### Bad practice\n```python\nimport os\nfrom os import path\nfrom sys import path\nimport os\n```\n\nHere, the import name `path` from the module `os` has been imported twice.\n\n### Recommended\n```python\nimport os\nfrom os import path\n```",[],{"shortcode":1679,"title":1680,"description":1681,"category":19,"severity":1294,"tags":1682,"isRecommended":825},"PYL-W1308","Duplicate string formatting argument found","String argument is repeating an argument. Consider passing arguments as named arguments.\n\n\u003C!--more-->\n### Bad practice\nprint('{} scored higher than {}. So, {} won!'.format(player_a, player_b, player_a))\n### Recommended\nprint('{a} scored higher than {b}. So, {a} won!'.format(a=player_a, b=player_b))",[],{"shortcode":1684,"title":1685,"description":1686,"category":31,"severity":1294,"tags":1687,"isRecommended":825},"PTC-W0016","Unnecessary comprehension","The built-in function being used does not require comprehension and can work directly with a generator expression.\n\n\u003C!--more-->\nUsing a generator expression within these functions is faster than using a comprehension:\n\n- `all`\n- `any`\n- `enumerate`\n- `iter`\n- `itertools.cycle`\n- `itertools.accumulate`\n\nThe inbuilt functions `all()` and `any()` in Python also support short-circuiting (evaluation stops as soon as the overall return value of the function is known), but this behavior is lost if you use a list comprehension. This affects performance.\n\n### Bad practice\n```python\n# Takes a very long time to run\nall_evens = all([n % 2 == 0 for n in range(100000000)])\nif all_evens:\n    print('All numbers are even!')\n```\n### Recommended\n```python\n# No list comprehension, runs instantly as `1` is found to be not even\nall_evens = all(n % 2 == 0 for n in range(100000000))\nif all_evens:\n    print('The numbers are all even!')\n```",[],{"shortcode":1689,"title":1690,"description":1691,"category":37,"severity":1294,"tags":1692,"isRecommended":825},"BAN-B101","Assert statement used outside of tests","Usage of `assert` statement in application logic is discouraged. `assert` is removed with compiling to optimized byte code. Consider raising an exception instead. Ideally, `assert` statement should be used only in tests.\n\n\u003C!--more-->\nPython has an option to compile the optimized bytecode and create the respective `.pyo` files by using the options `-O` and `-OO`. When used, these basic optimizations are done:\n\n- All the assert statements are removed\n- All docstrings are removed (when -OO is selected)\n- Value of the `__debug__` built-in variable is set to `False`\n\nIt is recommended not to use `assert` in non-test files. A better way for internal self-checks is to check explicitly and raise respective error using an if statement.\n\nTip: Make sure `test_patterns` are defined in `.deepsource.toml` to avoid false-positives. Please check the [documentation](https://deepsource.io/docs/concepts/#test_patterns) to know more.\n\nConsider this code snippet:\n\n```python\ndef read_secret(self):\n    assert self.is_admin, \"You are unauthorized to read this\"\n    return self._secret\n```\n\nIf `python` is run with the `-O` flag, the check for `self.is_admin` is\ncompletely ignored, which can cause secrets to be leaked.\n\nThis is how you can ensure the code always works:\n\n```python\ndef read_secret(self):\n    if not self.is_admin:\n        raise AssertionError(\"You are unauthorized to read this\")\n\n    return self._secret\n```\n\nHere's a more detailed example. Consider the following script `foo.py`:\n\n```python\nimport sys\n\ndef run():\n    assert len(sys.argv)  == 5 # Insecure, statement will be removed when compiled to optimized byte code\n    print(\"Argument variables are: \", sys.argv)\n\nrun()\n```\nWhen optimization is disabled:\n```\n$ python foo.py 1 2 3 4 5\nTraceback (most recent call last):\n  File \"foo.py\", line 7, in \u003Cmodule>\n    run()\n  File \"foo.py\", line 4, in run\n    assert len(sys.argv)  == 5 # Insecure, statement will be removed when compiled to optimized byte code\nAssertionError\n```\nWhen optimization is enabled:\n```\n$ python -O foo.pyo 1 2 3 4 5 6\nArgument variables are:  ['foo.pyo', '1', '2', '3', '4', '5', '6']\n```\n\nHere, all the internal self-checks using the assert statements are removed, as we can see. Therefore, there's a chance for an application to behave strangely in this case. It is better do raise the Exception explicitly:\n\n```python\nimport sys\n\ndef run():\n    if not len(sys.argv)  == 5:\n        raise ValueError\n    print(\"Argument variables are: \", sys.argv)\n\nrun()\n```\n\nNote: During autofix, DeepSource will change the `assert` statements to `if` statements raising `AssertionError`.\nThis is done to replicate the existing behavior.\n\n## References:\n- [-O flag in python](https://docs.python.org/3/using/cmdline.html?highlight=oo#cmdoption-o)\n- [-OO flag in python](https://docs.python.org/3/using/cmdline.html?highlight=oo#cmdoption-oo)\n- Discuss blogpost - [Using assert outside tests](https://discuss.deepsource.io/t/using-assert-outside-tests/79/2)",[1361,1204],{"shortcode":1694,"title":1695,"description":1696,"category":19,"severity":1294,"tags":1697,"isRecommended":825},"PYL-W1506","Thread has no target function","`threading.Thread` class is instantiated without the target function being passed. By default, the first parameter is the group param, not the target param.\nYou can read more about this [here](https://docs.python.org/3/library/threading.html#threading.Thread).\n\n\u003C!--more-->\n### Bad practice\n```python\nimport threading\n\ndef do_work():\n    for _ in range(10000):\n        pass\n\nmy_thread = threading.Thread(do_work)\n```\n### Recommended\n```python\nimport threading\n\ndef do_work():\n    for _ in range(10000):\n        pass\n\nmy_thread = threading.Thread(target=do_work)\n```",[],{"shortcode":1699,"title":1700,"description":1701,"category":37,"severity":1294,"tags":1702,"isRecommended":825},"BAN-B103","Insecure permissions set on a file","Files should be created with restrictive file permissions to prevent vulnerabilities such as information disclosure and code execution. In particular, any files which may contain confidential information should be set to only permit access by the owning user/service and group (i.e., no world/other access).\n\n\u003C!--more-->\nPOSIX based operating systems utilize a permissions model to protect access to parts of the file system. Every file in the POSIX file system has the following permissions:\n\n- Owner permissions - Determines what actions the owner of the file can perform on the file.\n- Group permissions - Determines what actions a user who is a member of the group that a file belongs to can perform on the file.\n- Other permissions - Determines what action all other users can perform on the file.\n\nGranting permissions to `others` can lead to unintended access and modification to files. Discretion should be used when granting write access to files such as configuration files to prevent vulnerabilities, including denial of service and remote code execution.\n\nIt is recommended to assign the most restrictive permissions to files and directories.\n\n### Bad practice\n```python\nimport os\n\n\nos.chmod('/etc/passwd', 0o227) # Insecure, read and write permission granted to others\nos.chmod('~/.bashrc', 511) # Insecure, write permission granted to others\nos.chmod('/etc/hosts', 0o777) # Insecure, write permission granted to group and others\n```\n\n### Recommended\n```python\nimport os\n\n\nos.chmod('/etc/passwd', 0o664)\nos.chmod('~/.bashrc', 0o644)\nos.chmod('/etc/hosts', 0o700)\n```\n\n# References:\n- OWASP Top 10 2021 Category A5 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- [os.chmod](https://docs.python.org/3/library/os.html#os.chmod)\n- CWE 732 - [Incorrect Permission Assignment for Critical Resource](https://cwe.mitre.org/data/definitions/732.html)",[1647,1203,1703,1704,1204],"cwe-732","sans-top-25",{"shortcode":1706,"title":1707,"description":1708,"category":37,"severity":1294,"tags":1709,"isRecommended":825},"BAN-B306","Use of deprecated function: `mktemp`","Creating and using insecure temporary files can leave application and system data vulnerable to attacks.\n\u003C!--more-->\nThe insecure way is to first generate a file name with the `mktemp()` function and then create a file using this name. Unfortunately, this is not secure, because a different process may create a file with this name in the time between the call to `mktemp()` and the subsequent attempt to create the file by the first process. A malicious user can predict the name of the temporary file, resulting in other files being accessed, modified, corrupted, or deleted.\n\nThe solution is to combine the two steps and create the file immediately. This can be achieved using `NamedTemporaryFile()` or `mkstemp`.\n\n### Bad practice\n```python\nimport tempfile\n\nfilename = tempfile.mktemp() # Insecure\ntemp_file = open(filename, file)\n```\n\n### Recommended\n```python\nimport tempfile\n\ntemp_file1 = tempfile.NamedTemporaryFile(delete=False) # Secure, replacement to tempfile.mktemp()\ntemp_file2 = tempfile.NamedTemporaryFile() # Secure, temporary file created will be automatically deleted\ntempfile3 = tempfile.mkstemp() # Secure\n```\n\n## References:\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [CWE 377](https://cwe.mitre.org/data/definitions/377) - Insecure Temporary File\n- [Python tempfile module](https://docs.python.org/3/library/tempfile.html#deprecated-functions-and-variables)",[1647,1710,1362,1204],"cwe-377",{"shortcode":1712,"title":1713,"description":1714,"category":37,"severity":1294,"tags":1715,"isRecommended":825},"BAN-B314","Use of an insecure method from `xml.etree.ElementTree` detected","Using various XML methods to parse untrusted XML data is known to be vulnerable to XML attacks. Using the [defusedxml](https://pypi.org/project/defusedxml) module is recommended. Methods should be replaced with their `defusedxml` equivalents.\n\n\u003C!--more-->\nThe `xml.etree.ElementTree` module implements a simple and efficient API for parsing and creating XML data. But it makes the application vulnerable to:\n\n- [Billion Laughs attack](https://en.wikipedia.org/wiki/Billion_laughs_attack): It is a type of denial-of-service attack aimed at XML parsers. It uses multiple levels of nested entities. If one large entity is repeated with a couple of thousand chars repeatedly, the parser gets overwhelmed.\n- [Quadratic blowup attack](https://www.acunetix.com/vulnerabilities/web/xml-quadratic-blowup-denial-of-service-attack/): It is similar to a Billion Laughs attack. It abuses entity expansion, too. Instead of nested entities, it repeats one large entity with a couple of thousand chars repeatedly.\n\nReplace vulnerable imports with the equivalent [defusedxml](https://pypi.org/project/defusedxml) package, or make sure `defusedxml.defuse_stdlib()` is called.\n\n### Bad practice\n```python\nimport xml.etree.ElementTree as ET\ntree = ET.parse('some_fie.xml') # Use of method from etree.ElementTree\n```\n### Recommended\n```python\nfrom defusedxml.ElementTree import parse\ntree = parse('some_fie.xml')\n```\n\n## References:\n- [xml.etree](https://docs.python.org/3/library/xml.etree.elementtree.html)\n- [defusedxml](https://pypi.org/project/defusedxml/)\n- [XML vulnerabilities](https://docs.python.org/3/library/xml.html#xml-vulnerabilities)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [CWE-611](https://cwe.mitre.org/data/definitions/611.html)",[1647,1503,1716,1362,1704,1204],"cwe-611",{"shortcode":1718,"title":1719,"description":1720,"category":37,"severity":1294,"tags":1721,"isRecommended":825},"BAN-B401","Telnet related module imported","A telnet-related module is being imported. Using `telnet` is considered insecure.\n\u003C!--more-->\nConsider the following points when using Telnet protocol:\n\n- Telnet is a plain-text protocol, anyone watching your Telnet packets on the wire will see your username, password, and everything you do on the remote system.\n- There are no authentication policies used in telnet causing huge security threat. Communication is carried out between the two desired hosts can be intercepted in the middle.\n\nUse [`ssh`](https://www.ssh.com/academy/ssh/protocol) as an alternative to `telnet`. It protects user identities, passwords, and data from network snooping attacks, and allows secure logins and file transfers. Use of `telnet` has been replaced by `ssh` in almost all cases.\n\n### Bad practice\n```python\nimport telnetlib # Sensitive, Import of telnetlib\n\nurl = \"telnet://a@somedomain.com\"\nconnection = telnetlib.Telnet(\"somehost\") # Sensitive, Using telnet protocol\n```\n\n### Recommended\n```python\nfrom paramiko import SSHClient\n\nclient = SSHClient()\nurl = \"telnet://a@somedomain.com\"\nclient.connect(url, username='user', password='secret')\n```\n\n## References:\n- [telnetlib module in Python](https://docs.python.org/3/library/telnetlib.html)\n- [Telnet security problems](https://www.ssh.com/academy/ssh/telnet)\n- [Paramiko module](http://www.paramiko.org/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-200](https://cwe.mitre.org/data/definitions/200.html)",[1647,1722,1362,1704,1204],"cwe-200",{"shortcode":1724,"title":1725,"description":1726,"category":37,"severity":1294,"tags":1727,"isRecommended":825},"BAN-B501","No certificate validation detected for HTTP request","Disabling certificate validation for HTTP request leave application vulnerable to [man-in-the-middle](https://owasp.org/www-community/attacks/Manipulator-in-the-middle_attack) attacks.\n\n\u003C!--more-->\nWhen request methods are used, certificates are validated automatically which is the desired behavior. If certificate validation is explicitly turned off, requests will accept any TLS certificate presented by the server and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle attacks.\n\nUsing TLS can greatly increase security by guaranteeing the identity of the party you are communicating with. This is accomplished by one or both parties presenting trusted certificates during the connection initialization phase of TLS.\n\n### Bad practice\n```python\nimport requests\n\nrequests.get('https://gmail.com', verify=False) # Insecure. No certificate validation\n```\n\n### Recommended\n```python\nimport requests\n\nrequests.get('https://gmail.com', verify=True) # Secure. Certificate validation enabled.\nrequests.get('https://deepsource.io') # Secure. Certificate validation enabled by default\n```\n\n## References:\n- [SSL Cert verification in requests](https://2.python-requests.org/en/master/user/advanced/#ssl-cert-verification)\n- [Man in the middle attack](https://owasp.org/www-community/attacks/Manipulator-in-the-middle_attack)\n- OWASP Top 10 2021 Category A07 - [Identification and Authentication Failures](https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/)\n- [CWE 300](https://cwe.mitre.org/data/definitions/300.html) - Channel Accessible by Non-Endpoint",[1647,1728,1729,1204],"cwe-300","a07",{"shortcode":1731,"title":1732,"description":1733,"category":19,"severity":1294,"tags":1734,"isRecommended":825},"PTC-W0022","Illegal operation on file","Trying to write on a file opened in read mode (`r`), or the other way around, will raise an `IOError`.\nIt is recommended to open the file in the appropriate mode.\n\n\u003C!--more-->\n### Bad practice\n```python\nwith open(some_file, \"r\") as fp:\n    ...\n    fp.write(\"This is not allowed!\")\n```\n\n### Recommended\n```python\nwith open(some_file, \"w\") as fp:\n    ...\n    fp.write(\"This is okay now, since the file has been opened in the write mode.\")\n```",[],{"shortcode":1736,"title":1737,"description":1738,"category":37,"severity":1294,"tags":1739,"isRecommended":825},"BAN-B507","Missing host key validation in SSH","Host keys are used to verify the identity of remote hosts when SSH protocol is used. Accepting unknown host keys leave the connection vulnerable to man-in-the-middle attacks.\n\n\u003C!--more-->\nParamiko library provides the ability to set policy for missing hostkey using [MissingHostKeyPolicy](http://docs.paramiko.org/en/stable/api/client.html#paramiko.client.MissingHostKeyPolicy) method. By default, it uses [RejectPolicy](http://docs.paramiko.org/en/stable/api/client.html#paramiko.client.RejectPolicy) or automatically rejecting the unknown hostname & key.\n\nDo not set the default missing host key policy for the Paramiko library to either `AutoAddPolicy` or `WarningPolicy`. When paramiko methods are used, host keys are verified by default.\n\n### Bad practice\n```python\nfrom paramiko.client import SSHClient, AutoAddPolicy\n\nclient = SSHClient()\nclient.set_missing_host_key_policy(AutoAddPolicy) # Insecure. Host key validation policy set to AutoAddPolicy\nclient.connect(\"abc@domain.com\")\n```\n\n### Recommended\n```python\nfrom paramiko.client import SSHClient\n\nclient = SSHClient()\nclient.connect(\"abc@domain.com\") # Safe. Uses RejectPolicy by default\n```\n\n## References:\n- [SSHclient](http://docs.paramiko.org/en/stable/api/client.html#paramiko.client.SSHClient)\n- [MissingHostKeyPolicy](http://docs.paramiko.org/en/stable/api/client.html#paramiko.client.MissingHostKeyPolicy)\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- OWASP Top 10 2021 Category A07 - [Identification and Authentication Failures](https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/)\n- [CWE 295](https://cwe.mitre.org/data/definitions/295.html) - Improper Certificate Validation",[1647,1203,1729,1740,1704,1204],"cwe-295",{"shortcode":1742,"title":1743,"description":1744,"category":37,"severity":1294,"tags":1745,"isRecommended":825},"BAN-B601","Possible shell injection via Paramiko call","Paramiko is a Python library designed to work with the SSH2 protocol for secure (encrypted and authenticated) connections to remote machines. It is intended to run commands on a remote host. These commands are run within a shell on the target and are thus vulnerable to various [shell injection attacks](https://owasp.org/www-community/attacks/Command_Injection).\n\nUse of Paramiko's `exec_command` or `invoke_shell` methods should be reviewed to ensure that the input is sanitized. It is recommended to use [`shlex.quote`](https://pypi.org/project/shellescape/) to santize the input.\n\n\u003C!--more-->\n\n### Bad practice\n```python\nimport paramiko\n\nclient = paramiko.SSHClient(...)\nret = client.exec_command(input)\n```\n\n### Recommended\nimport paramiko, shlex\n\nclient = paramiko.SSHClient(...)\nret = client.exec_command(shlex.quote(input))\n```\n\n## References:\n- [Paramiko library](http://www.paramiko.org/)\n- [shlex](https://docs.python.org/3/library/shlex.html)\n- [Shell injection attacks](https://owasp.org/www-community/attacks/Command_Injection)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [CWE-77](https://cwe.mitre.org/data/definitions/77.html)",[1647,1503,1746,1204],"cwe-77",{"shortcode":1748,"title":1749,"description":1750,"category":19,"severity":1294,"tags":1751,"isRecommended":825},"FLK-E112","Expected an indented block","This block of code should be indented.\n\u003C!--more-->\n### Bad practice\n```python\nfor i in range(10):\nprint(i)  # Incorrect indentation\n```\n### Recommended\n```python\nfor i in range(10):\n    print(i)\n```",[],{"shortcode":1753,"title":1754,"description":1755,"category":15,"severity":1294,"tags":1756,"isRecommended":825},"FLK-E713","Test for membership should be 'not in'","Tests for membership should use the form `x not in the_list` rather than `not x in the_list`. The former example is simply more readable.\n\n\u003C!--more-->\n### Bad practice\n```python\nif not x in authors:\n    authors.append(x)\n```\n\n### Recommended\n```python\nif x not in authors:\n    authors.append(x)\n```",[],{"shortcode":1758,"title":1759,"description":1760,"category":15,"severity":1294,"tags":1761,"isRecommended":825},"PYL-C0113","Use of an unneeded `not` detected","The boolean expression contains an unneeded negation and can be re-written without using the `not` statement.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef categorize_number(num):\n    if not num % 2 == 0:\n        print(\"The number is odd.\")\n    else:\n        print(\"The number is even.\")\n```\nHere, the condition `not num % 2 == 0` contains an unneeded `not` and can be changed into `num % 2 != 0`.\nA clearer and more straightforward approach would look like this:\n### Recommended\n```python\ndef categorize_number(num):\n    if num % 2 != 0:\n        print(\"The number is odd.\")\n    else:\n        print(\"The number is even.\")\n```",[],{"shortcode":1763,"title":1764,"description":1765,"category":15,"severity":1294,"tags":1766,"isRecommended":825},"PYL-C0201","Consider iterating dictionary","Consider iterating the dictionary directly instead of calling `.keys()`.\nUsing `for key in dictionary` would always iterate the dictionary keys.\n\n\u003C!--more-->\n### Bad practice\n```python\nsounds = {\"cow\": \"moo\", \"dog\": \"bark\"}\nfor key in sounds.keys():\n    print(key)\n```\n\n### Recommended\n```python\nsounds = {\"cow\": \"moo\", \"dog\": \"bark\"}\nfor key in sounds:\n    print(key)\n```",[],{"shortcode":1768,"title":1769,"description":1770,"category":41,"severity":1294,"tags":1771,"isRecommended":825},"PYL-C0202","Bad classmethod argument","It is recommended to name the first argument of a classmethod as `cls` so that it's easy to differentiate them from regular instance methods.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass SpaceShip:\n\n    @classmethod\n    def trajectory(self, x, y, z):  # `self` here can be very confusing\n        ...\n```\n\n### Recommended\n```python\nclass SpaceShip:\n\n    @classmethod\n    def trajectory(cls, x, y, z):\n        ...\n```",[],{"shortcode":1773,"title":1774,"description":1775,"category":41,"severity":1294,"tags":1776,"isRecommended":825},"PYL-C0203","Bad metaclass-method argument","Use of `cls` as the first named argument in a metaclass method is recommended so it's easy to differentiate them from regular instance methods.\n\n\u003C!--more-->\n### Not preferred\n```python\nclass MyMeta(type):\n    def some_method(self):\n       ...\n```\n\n### Preferred\n```python\nclass MyMeta(type):\n    def some_methon(cls):\n        ...\n```",[],{"shortcode":1778,"title":1779,"description":1780,"category":41,"severity":1294,"tags":1781,"isRecommended":825},"PYL-C0205","Slots are recommended to be an iterable, simple string detected","While it's technically correct to have simple strings as slot values, it is recommended to use an iterable like a `tuple` or a `list`. It's very common to add more than one property names in the slots, and even if there's one property name at the present, having that as a one-member iterable is more clear than a string.\n\nThis is a convention and helps it easier to understand and extend your code.\n\n\u003C!--more-->\n### Not preferred\n```python\nclass Example:\n    __slots__ = 'my_attr'\n```\n\n### Preferred\n```python\nclass Example:\n    __slots__ = ['my_attr']\n```",[],{"shortcode":1783,"title":1784,"description":1785,"category":15,"severity":1294,"tags":1786,"isRecommended":825},"PYL-C0414","Import alias same as original package name","Import alias is same as original package name, thus making the alias unnecessary. This is probably not what's intended.\n\n\u003C!--more-->\n### Bad practice\n```python\nimport my_package as my_package\n```\n\n### Recommended\n```python\nimport my_package as mp\n```\nor, remove the import alias\n```python\nimport my_package\n```\n\n*_Note: During autofix, DeepSource will remove the unnecessary alias._*",[],{"shortcode":1788,"title":1789,"description":1790,"category":41,"severity":1294,"tags":1791,"isRecommended":825},"PYL-C2201","Misplaced comparison constant","The constant is placed on the left side of a comparison. It is usually clearer in intent to place it in the right hand side of the comparison.\n\n\u003C!--more-->\n### Bad practice\n```python\nif 0 == x % 2:\n    ...\n```\n\n## Recommended:\n```python\nif x % 2 == 0:\n    ...\n```",[],{"shortcode":1793,"title":1794,"description":1795,"category":41,"severity":1294,"tags":1796,"isRecommended":825},"PYL-R1705","Unnecessary `else` / `elif` used after `return`","The use of `else` or `elif` becomes redundant and can be dropped if the last statement under the leading `if` / `elif` block is a `return` statement.\nIn the case of an `elif` after `return`, it can be written as a separate `if` block.\nFor `else` blocks after `return`, the statements can be shifted out of `else`. Please refer to the examples below for reference.\n\nRefactoring the code this way can improve code-readability and make it easier to maintain.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef classify_number(x):\n    if x % 2 == 0:\n        return 'Even'\n    else:\n        return 'Odd'\n\n\ndef what_is_this_number(x):\n    if x % 2 == 0 and x >= 0:\n        return 'Even'\n    elif x % 2 == 0 and x \u003C 0:\n        return 'Even and Negative'\n    elif x % 2 != 0 and x \u003C 0:\n        return 'Odd and Negative.'\n    else:\n        return 'Odd'\n```\n\n### Preferred:\n```python\ndef classify_number(x):\n    if x % 2 == 0:\n        return 'Even'\n\n    return 'Odd'\n\n\ndef what_is_this_number(x):\n    if x % 2 == 0 and x >= 0:\n        return 'Even'\n\n    if x % 2 == 0 and x \u003C 0:\n        return 'Even and Negative'\n\n    if x % 2 != 0 and x \u003C 0:\n        return 'Odd and Negative'\n\n    return 'Odd'\n```",[],{"shortcode":1798,"title":1799,"description":1800,"category":41,"severity":1294,"tags":1801,"isRecommended":825},"PYL-R1708","`StopIteration` detected in a generator","According to [PEP479](https://www.python.org/dev/peps/pep-0479/), the raise of `StopIteration` to end the loop of a generator may lead to hard to find bugs. This PEP specifies that `raise StopIteration` has to be replaced by a simple `return` statement.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef some_generator(n):\n    for i in range(n):\n        yield i\n        if i >= 5:\n            raise StopIteration  # Will raise an exception\n```\n\n### Recommended\n```python\ndef some_generator(n):\n    for i in range(n):\n        yield i\n        if i >= 5:\n            return  # Will close the generator\n```",[],{"shortcode":1803,"title":1804,"description":1805,"category":31,"severity":1294,"tags":1806,"isRecommended":825},"PYL-R1713","Consider using `join`","Consider using `str.join(sequence)` instead of joining the elements of a sequence using `for` loop iteration.\n`str.join(sequence)` is faster, uses less memory and increases readability compared to a `for` loop iteration.\n\u003C!--more-->\n### Bad practice\n```python\nmy_string = \"\"\nfor element in data:\n    my_string += element\n```\n\n### Recommended\n```python\nmy_string = \"\".join(data)\n```",[],{"shortcode":1808,"title":1809,"description":1810,"category":31,"severity":1294,"tags":1811,"isRecommended":825},"PYL-R1714","Consider using `in`","To check if a variable is equal to one of many values, combine the values into a tuple and check if the variable is contained `in` it instead of checking for equality against each of the values.\nThis is faster, less verbose, and more readable.\n\n\u003C!--more-->\n### Bad practice\n```python\nif x == 1 or x == 2 or x == 3:\n    do_something()\n```\n\n### Recommended\n```python\nif x in (1, 2, 3):\n    do_something()\n```",[],{"shortcode":1813,"title":1814,"description":1815,"category":31,"severity":1294,"tags":1816,"isRecommended":825},"PYL-R1717","Consider using a dictionary comprehension","Although there is nothing syntactically wrong with this code, it is hard to read and can be simplified to a dict comprehension.\nUsing dictionary comprehension is more performant since there is no need to create a transient list.\n\u003C!--more-->\n### Bad practice\n```python\nmapping = dict([(num, str(num)) for num in my_magic_nums])\n```\n\n### Recommended\n```python\nmapping = {num: str(num) for num in my_magic_nums}\n```",[],{"shortcode":1818,"title":1819,"description":1820,"category":31,"severity":1294,"tags":1821,"isRecommended":825},"PYL-R1718","Consider using a set comprehension","Although there is nothing syntactically wrong with this code, it is hard to read and can be simplified to a set comprehension.\nUsing set comprehension is more performant since there is no need to create a transient list.\n\u003C!--more-->\n### Bad practice\n```python\nmapping = set([num for num in my_magic_nums])\n```\n\n### Recommended\n```python\nmapping = {num for num in my_magic_nums}\n```",[],{"shortcode":1823,"title":1824,"description":1825,"category":15,"severity":1294,"tags":1826,"isRecommended":825},"PYL-W0108","Unnecessary lambda expression","A lambda that calls a function without modifying any of its parameters is unnecessary. Python functions are first-class objects and can be passed around in the same way as the resulting lambda. It is recommended to remove the lambda and use the function directly.\n\n\u003C!--more-->\nIt is preferred to use the function `hash` directly as the lambda function calls the same function without any modifications.\nAnother reason to avoid the lambda function here is that it makes debugging difficult.\nLambdas show as `\u003Clambda>` in tracebacks, where functions will display the function’s name.\n\n### Bad practice\n```python\nitems = [1, 2, 3]\n\nhashify = lambda x: hash(x)\nhashed_items = map(hashify, items)\n```\n### Recommended\n```python\nitems = [1, 2, 3]\n\n# pass the builtin `hash` instead of the wrapper `hashify`\nhashed_items = map(hash, items)\n```",[],{"shortcode":1828,"title":1829,"description":1830,"category":19,"severity":1294,"tags":1831,"isRecommended":825},"PYL-W0109","Duplicate dictionary keys","This dictionary expression binds the same key multiple times.\nThis may lead to unintentional behaviour as the key will always map the last value provided to it.\nIt is recommended to have unique keys.\n\n\u003C!--more-->\n### Bad practice\nHere, the key `random` is provided twice.\n```python\nDICT = {\n    \"some\": \"some\",\n    \"random\": \"random\",\n    \"dict\": \"dict\",\n    \"values\": \"values\",\n    \"random\": \"different\",\n}\n```\n\n### Recommended\nAll keys should be unique.\n```python\nDICT = {\n    \"some\": \"some\",\n    \"dict\": \"dict\",\n    \"values\": \"values\",\n    \"random\": \"different\",\n}\n```",[],{"shortcode":1833,"title":1834,"description":1835,"category":19,"severity":1294,"tags":1836,"isRecommended":825},"PYL-W0120","Useless else clause detected on the loop","When a loop specifies no break statement, the else clause will always execute when the loop sequence is empty, thus making it useless.\nIt is recommended to have the statements under else in the same scope as the loop itself.\nIf the else clause does not always execute at the end of a loop clause, then the code should add a break statement within the loop block.\n\n\u003C!--more-->\n### Bad practice\n```python\nwhile condition:\n    # body doesn't have `break` anywhere\n    ...\nelse:\n    print(\"This is in the else block\")\n```\n\n### Recommended\n```python\nwhile condition:\n    if other_condition:\n        break\n    ...\nelse:\n    print(\"This is in the else block\")\n```\nOr, if there is no need for a `break` statement in the loop, refactor it like this:\n\n```python\nwhile condition:\n    # body doesn't have `break` anywhere\n    ...\n\nprint(\"This is in the else block\")\n```",[],{"shortcode":1838,"title":1839,"description":1840,"category":19,"severity":1294,"tags":1841,"isRecommended":825},"PYL-W0124","`as` with another context manager looks like a tuple","This `with` statement component returns multiple values and uses name binding with `as` only for a part of those values, as in `with ctx() as a, b`. This can be misleading since it's unclear if the context manager returns a tuple or if the node without a name binding is another context manager.\n\u003C!--more-->\n### Bad practice\n```python\ndatabase = open('sqlite.db')\n\n# Here we are entering two separate context managers, but it is unclear\nwith open('file.txt') as myfile, database:\n    myfile.read()\n```\n### Recommended\nOne way to clarify this would be to use an `ExitStack`:\n```python\nfrom contextlib import ExitStack\n\ndatabase = open('sqlite.db')\n\nwith ExitStack() as stack:\n    myfile = stack.enter_context(open('file.txt'))\n    stack.enter_context(database)\n```",[],{"shortcode":1843,"title":1844,"description":1845,"category":15,"severity":1294,"tags":1846,"isRecommended":825},"PYL-W0125","Conditional statement used with a constant value","Using a conditional statement with a constant value is pointless and will always evaluate to either True or False. This might not be what is intended.\n\n\u003C!--more-->\n### Bad practice\n```python\nif 100:\n    print('This will always run')\n\nif False:\n    print('This will never run')\n```\n### Recommended\nGetting rid of the always `True` check, and removing the block that is never run will have the same behaviour:\n```python\nprint('This will always run')\n```",[],{"shortcode":1848,"title":1849,"description":1850,"category":19,"severity":1294,"tags":1851,"isRecommended":825},"PYL-W0143","Comparison with callable detected","A comparison with a callable has been detected, which suggests you may have forgotten to actually call the function or method.\nIf you intended to check if both of these callables are the same, it's recommended to use the `is` operator for comparison.\nOtherwise, if you intended to compare against the value returned by this callable, please consider changing this to the actual function call.\n\u003C!--more-->\n### Bad practice\n```python\nsome_callable == some_other_callable\n```\n\n### Recommended\n```python\nsome_callable is some_other_callable  # using the `is` operator\n\n# or\n\nsome_value == some_callable()\n```",[],{"shortcode":1853,"title":1854,"description":1855,"category":19,"severity":1294,"tags":1856,"isRecommended":825},"PYL-W0211","Bad `staticmethod` argument detected","It is customary for instance or class methods to take `self` or `cls`, respectively, as their first arguments, a method that uses either of these names but is found to be a static method may have been defined incorrectly. Choose names other than `self` or `cls` for arguments to avoid confusing other programmers looking at your code.\n\u003C!--more-->\n### Bad practice\n```python\nclass API:\n    @staticmethod\n    def get_endpoint(self):  # The `self` here can be confusing\n        return self + '/api/v2/users'\n```\n### Recommended\n```python\nclass API:\n    @staticmethod\n    def get_endpoint(origin):  # Any other, more suitable variable name\n        return origin + '/api/v2/users'\n```",[],{"shortcode":1858,"title":1859,"description":1860,"category":19,"severity":1294,"tags":1861,"isRecommended":825},"PYL-W0222","Signature differs in overridden method","There are one (or more) legal parameters for an overridden method that are not legal for an overriding method. This will cause an error when the overriding method is called with a number of parameters that are legal for the overridden method. This violates the Liskov substitution principle.\n\u003C!--more-->\nRead more about LSP [here] (https://en.wikipedia.org/wiki/Liskov_substitution_principle).\n### Bad practice\n```python\nclass A:\n\n    def foobar(x, y=0):\n        return x + y\n\nclass B(A):\n\n    def foobar(x, y):\n        return x + 2*y\n\na = A()\na.foobar(1) # Valid\n\nb = B()\nb.foobar(1) # Invalid\n```\n### Recommended\n```python\nclass A:\n\n    def foobar(x, y=0):\n        return x + y\n\nclass B(A):\n\n    def foobar(x, y=1):\n        return x + 2*y\n\n\na = A()\na.foobar(1) # Valid\n\nb = B()\nb.foobar(1) # Valid\n```",[],{"shortcode":1863,"title":1864,"description":1865,"category":19,"severity":1294,"tags":1866,"isRecommended":825},"PYL-W0223","Abstract method not overridden","A method marked with `@abstractmethod` is not defined in the concrete class. This can result in unintended behavior.\n\nIt is recommended to implement all abstract methods in the derived classes.\n\u003C!--more-->\n### Bad practice\n```python\nfrom abc import ABC, abstractmethod\n\nclass Vehicle(ABC):\n\n    @abstractmethod\n    def start():\n        pass\n\nclass Car(Vehicle):\n\n    # No overridden `start` method here. Can cause unintended behavior\n\n    def stop():\n        self.speed = 0\n```\n\n### Recommended\n```python\nfrom abc import ABC, abstractmethod\n\nclass Vehicle(ABC):\n\n    @abstractmethod\n    def start():\n        pass\n\nclass Car(Vehicle):\n\n    def start():\n        self.speed = 3\n\n    def stop():\n        self.speed = 0\n```",[],{"shortcode":1868,"title":1869,"description":1870,"category":19,"severity":1294,"tags":1871,"isRecommended":825},"PYL-W0410","Future import(s) name after other statements","Imports from `__future__` should be the first imports in a file.\nIf it's not, it will raise a `SyntaxError`.\n\u003C!--more-->\nIn Python 2, dividing two integers results in an integer result.\nHowever, you can import `division` from the `__future__` module to enable float division everywhere.\nFor it to consistently work, you need to ensure that it's the first statement in the file.\n\n### Bad practice\n```python\n8 / 7  # Gives output: 1\n...\nfrom __future__ import division  # Will raise `SyntaxError`.\n```\n\n### Recommended\n```python\nfrom __future__ import division\n...\n8 / 7  # Gives output: 1.1428571428571428\n```",[],{"shortcode":1873,"title":1874,"description":1875,"category":19,"severity":1294,"tags":1876,"isRecommended":825},"PYL-W0602","Global variable is declared but not used","The variable is defined through the `global` statement but no assignment to this variable is done. It is recommended to remove it if not necessary.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef my_func():\n    global a\n    return a\n```\n\n### Recommended\nIf it is a newly defined global, make sure to assign a value to it.\n\n```python\ndef my_func():\n    global a\n    a = 1    # Assign to the newly defined global value.\n    return a\n```\n\nOr if the global should be already defined, you can remove the `global` statement.\n\n```python\na = 1\n\ndef my_func():\n    return a  # The global statement can be removed\n```\n\nNote: DeepSource will remove the `global` statement during autofix.",[],{"shortcode":1878,"title":1879,"description":1880,"category":15,"severity":1294,"tags":1881,"isRecommended":825},"PYL-W0612","Unused variable found","An unused variable takes up space in the code, and can lead to confusion, and it should be removed. If this variable is necessary, name the variable `_` to indicate that it will be unused, or start the name with `unused` or `_unused`.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef update():\n    for i in range(10): # Usused variable `i`\n        time.sleep(0.01)\n        display_result()\n```\n### Preferred:\n```python\ndef update():\n    for _ in range(10):\n        time.sleep(0.01)\n        display_result()\n```",[],{"shortcode":1883,"title":1884,"description":1885,"category":15,"severity":1294,"tags":1886,"isRecommended":825},"PYL-W0613","Function contains unused argument","An unused argument can lead to confusions. It should be removed. If this variable is necessary, name the variable `_` or start the name with `unused` or `_unused`.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef square(x, y=1):\n    return x * x\n\nclass MySubClass(MyClass):\n    def __init__(self, number):\n        self.value = 42  # argument `number` remains unused\n```\n### Preferred:\n```python\ndef square(x):\n    return x * x\n\nclass MySubClass(MyClass):\n    def __init__(self, _):\n        self.value = 42\n```",[],{"shortcode":1888,"title":1889,"description":1890,"category":15,"severity":1294,"tags":1891,"isRecommended":825},"PYL-W0621","Re-defined variable from outer scope","The local variable name hides the variable defined in the outer scope, making it inaccessible and might confuse.\n\n\u003C!--more-->\n\n### Bad practice\n\n```python\nfilename = 'myfile.txt'\n\ndef read_file(filename):  # This shadows the global `filename`\n    with open(filename) as file:\n        return file.readlines()\n```\n\n### Preferred:\n\n```python\nFILENAME = 'myfile.txt'  # renamed global to UPPER_CASE as convention\n\ndef read_file(filename):\n    with open(filename) as file:\n        return file.readlines()\n```\n\n### Bad practice\n\nAnother usual suspect of this is when you use the same parameter name inside a function as the global variable you are using. For example:\n\n```python\ndef run_app(app):\n    # This `app` shadows the global app...\n    app.run()\n\nif __name__ == '__main__':\n    app = MyApp()  # This is a global variable!\n    run_app(app)\n```\n\n### Preferred:\n\nTo avoid this re-defining of a global, consider not defining `app` as a global, but inside a `main()` function instead:\n\n```python\ndef run_app(app):\n    # There is no longer a global `app` variable.\n    app.run()\n\ndef main():\n    app = MyApp()\n    run_app(app)\n\nif __name__ == '__main__':\n    main()\n```",[],{"shortcode":1893,"title":1894,"description":1895,"category":15,"severity":1294,"tags":1896,"isRecommended":825},"PYL-W0703","Exception caught is very general","If the except block catches a very general exception, it is likely to catch any\nunrelated errors too. Try to be more explicit about which exception(s) you're\ntrying to catch.\n\n\u003C!--more-->\nIf you need to catch every other exception, then mark it as intentional by\nadding a `# skipcq` comment.\n\n### Bad practice\n\n```python\ntry:\n    x = a / b\nexcept Exception:\n    x = a / (b + 1)\n```\n\n```python\ntry:\n    line = input('Enter numbers:')\n    numbers = [int(i) for i in line.split()]\nexcept BaseException:\n    print('Only use numbers for the input')\n```\n\n### Preferred:\n\n```python\ntry:\n    x = a / b\nexcept ZeroDivisionError:\n    x = a / (b + 1)\n```\n\n```python\ntry:\n    event_loop.run()\nexcept Exception as exc:  # skipcq: PYL-W0703 - Loop can sometimes crash.\n    sentry.report(exc)\n```\n\n```python\ntry:\n    line = input('Enter numbers:')\n    numbers = [int(i) for i in line.split()]\nexcept ValueError:\n    print('Only use numbers for the input')\n```",[],{"shortcode":1898,"title":1899,"description":1900,"category":19,"severity":1294,"tags":1901,"isRecommended":825},"PYL-W1303","Missing format argument key","The format string has one or more named fields which are not provided by the keyword arguments. This will raise a `KeyError`.\n\nIt is recommended to remove the unused field or provide an argument for it.\n\u003C!--more-->\n### Bad practice\n```python\nformat_string = \"The coordinates are ({x}, {y}, {z})\".format(x=1, y=2)\nprint(format_string)\n```\n### Recommended\n```python\nformat_string = \"The coordinates are ({x}, {y}, {z})\".format(x=1, y=2, z=-4)\nprint(format_string)\n```",[],{"shortcode":1903,"title":1904,"description":1905,"category":19,"severity":1294,"tags":1906,"isRecommended":825},"PYL-W1306","Missing format attribute","The format string uses an attribute specifier like `{0.length}`, but the argument passed for formatting doesn't have that attribute. This is an error.\n\n\u003C!--more-->\nNote: String formatting uses a limited Python-like syntax. Calls are not supported in this syntax; only subscription (indexing by number or unquoted (!) name) and attribute access is supported.\n\n### Bad practice\n```python\nclass API:\n    endpoint = 'example.com/api'\n\napi = API()\nprint('{0.endopint}'.format(api))  # Misspelled property `endpoint`\n```\n### Recommended\n```python\nclass API:\n    endpoint = 'example.com/api'\n\napi = API()\nprint('{0.endpoint}'.format(api))\n```",[],{"shortcode":1908,"title":1909,"description":1910,"category":19,"severity":1294,"tags":1911,"isRecommended":825},"PYL-W1403","Implicit string concatenation detected in the sequence","String literals are implicitly concatenated in a literal iterable definition when they are not separated by a comma.\nThis may lead to undesirable results. It is recommended to look at the highlighted code for possible missing commas.\n\n\u003C!--more-->\n### Bad practice\n```python\nsample_seq = ['A', 'B' 'C', 'D']\n```\nHere, `sample_seq` will have `['A', 'BC', 'D']` which, possibly, is not what was intended.\n\n### Recommended\n```python\nsample_seq = ['A', 'B', 'C', 'D']\n```",[],{"shortcode":1913,"title":1914,"description":1915,"category":19,"severity":1294,"tags":1916,"isRecommended":825},"PYL-W1501","Bad open mode for file","The mode with which the file is opened is not valid. Python supports: `r`, `w`, `a`, and `x` modes with `t` and `b` modifiers, for `t`ext files and `b`inary files respectively. The `+` mode can also be used to open the file for updating (reading and writing).\n\n\u003C!--more-->\n### Bad practice\n```python\nwith open('log.txt', 'rw') as logfile:  # Doesn't work\n    text = logfile.read()\n    logfile.write('test log')\n```\n### Recommended\n```python\nwith open('log.txt', 'r+') as logfile:\n    text = logfile.read()\n    logfile.write('test log')\n```\n## References:\n- [Python open function](https://docs.python.org/3/library/functions.html#open)",[],{"shortcode":1918,"title":1919,"description":1920,"category":19,"severity":1294,"tags":1921,"isRecommended":825},"PYL-W1507","Shallow copy of `os.environ` detected","`os.environ` is not a `dict` but `proxy` object.\nThe use of `copy.copy(os.environ)` will make a shallow copy of `os.environ` therefore, any changes made in the copy would be reflected in `os.environ` as well.\nIt is recommended to use `os.environ.copy()` instead.\nSee https://bugs.python.org/issue15373 for reference.\n\n\u003C!--more-->\n\n```bash\n>>> # Making a copy of the environment variables using `copy.copy`\n>>> shallow_copy = copy.copy(os.environ)\n>>>\n>>> # Fetching value for a non-existent key from `os.environ`\n>>> os.environ.get(\"test-1\", \"Not found\")\n'Not found'\n>>>\n>>> # Adding this in the shallow copy:\n>>> shallow_copy[\"test-1\"] = \"This was added in the copy of os.environ\"\n>>>\n>>> # Query os.environ for the key again:\n>>> os.environ.get(\"test-1\", \"Not found\")\n'This was added in the copy of os.environ'\n>>>\n>>> # Using os.environ.copy() directly:\n>>> deep_copy = os.environ.copy()\n>>>\n>>> # Fetching value for a non-existent key from `os.environ`\n>>> os.environ.get(\"test-2\", \"Not found\")\n'Not found'\n>>>\n>>> # Adding this in the deep_copy:\n>>> deep_copy[\"test-2\"] = \"This was added in the copy of os.environ\"\n>>>\n>>> # Query os.environ for the key again:\n>>> os.environ.get(\"test-2\", \"Not found\")\n'Not found'\n```",[],{"shortcode":1923,"title":1924,"description":1925,"category":45,"severity":1294,"tags":1926,"isRecommended":825},"TYP-010","Invalid return `type hint` for async generator function","The return type of an async generator function should be `AsyncGenerator` or one of its supertypes.",[],{"shortcode":1928,"title":1929,"description":1930,"category":45,"severity":1294,"tags":1931,"isRecommended":825},"TYP-029","`Final[...]` shall have at most one type argument","More than one `Type` argument given to `Final[...]`. This is invalid. Read all about `Final` [here](https://mypy.readthedocs.io/en/latest/final_attrs.html).",[],{"shortcode":1933,"title":1934,"description":1935,"category":45,"severity":1294,"tags":1936,"isRecommended":825},"TYP-053","Incompatible redefinition detected","The redefinition is incompatible. Please see the issue message for details.",[],{"shortcode":1938,"title":1939,"description":1940,"category":45,"severity":1294,"tags":1941,"isRecommended":825},"TYP-025","Inconsistent type signature","Type signature has been provided with either fewer or more arguments than what is actually needed.",[],{"shortcode":1943,"title":1944,"description":1945,"category":45,"severity":1294,"tags":1946,"isRecommended":825},"TYP-075","Invalid assignation to class variable","Assignation to the highlighted class variable can not be done via instance. Please see the occurrence message for more details.",[],{"shortcode":1948,"title":1949,"description":1950,"category":15,"severity":1294,"tags":1951,"isRecommended":825},"PY-W0074","Consider using `any`","It is recommended to use `any` for this loop, as it will make your code smaller and more readable.\n\n\u003C!--more-->\n\n### Bad practice\n\n```python\ndef has_ten(my_list):\n    for item in my_list:\n        if item == 10:\n            return True\n    return False\n```\n\n### Recommended\n\n```python\ndef has_ten(my_list):\n    return any(item == 10 for item in my_list)\n```",[],{"shortcode":1953,"title":1954,"description":1955,"category":45,"severity":1294,"tags":1956,"isRecommended":825},"TYP-017","Invalid property override","`read-only` property can not overwrite `read-write` property.",[],{"shortcode":1958,"title":1959,"description":1960,"category":45,"severity":1294,"tags":1961,"isRecommended":825},"TYP-035","Invalid type comment detected","This is not a valid type comment. You can read more about valid type comments [here](//https://www.python.org/dev/peps/pep-0484/#type-comments).",[],{"shortcode":1963,"title":1964,"description":1965,"category":15,"severity":1294,"tags":1966,"isRecommended":825},"PTC-W0033","Formatted string used as docstring","Formatted string literals cannot be used as docstrings, even if they do not include expressions.\nIf used, the formatted strings are just evaluated as an expression in the function body.\n\n\u003C!--more-->\nDocstrings in Python need to be a constant, which means that trying to format a docstring at runtime, using `.format()` or f-strings simply doesn't work.\n\nFor example:\n\n```python\ndef foo():\n    f'''This is intended to be the docstring for {__name__}'''\n    ...\n```\nThe value of `foo.__doc__` would be `None` here.",[],{"shortcode":1968,"title":1969,"description":1970,"category":45,"severity":1294,"tags":1971,"isRecommended":825},"TYP-023","Wrong implementation of `overload`","Wrong implementation of `overload` function. See the occurrence messages for more details.",[],{"shortcode":1973,"title":1974,"description":1975,"category":45,"severity":1294,"tags":1976,"isRecommended":825},"TYP-024","Wrong implementation of `final` decorator","Wrong implementation of `final` decorator. See the occurrence messages for more details.",[],{"shortcode":1978,"title":1979,"description":1980,"category":45,"severity":1294,"tags":1981,"isRecommended":825},"TYP-005","Unexpected return type found","The return type of this callable is different from what is defined in the type hint.",[],{"shortcode":1983,"title":1984,"description":1985,"category":19,"severity":1294,"tags":1986,"isRecommended":825},"PTC-W0025","Found `yield` statement inside a comprehension","Do not use `yield` inside a comprehension as it will return a generator object.\nUse a generator expression instead.\n\n**Note**: Use of `yield` inside a comprehension was allowed till Python 3.7 but is a syntax error from Python 3.8 onwards.\n\u003C!--more-->\n### Bad practice\n```python\nnumber_generator = [(yield num) for num in range(1,1000)]\n```\n\n### Recommended\n```python\nnumber_generator = (num for num in range(1,1000))\n```",[],{"shortcode":1988,"title":1989,"description":1990,"category":19,"severity":1294,"tags":1991,"isRecommended":825},"PTC-W0026","Found `yield` statement inside a generator expression","It is redundant to use `yield` inside a generator expression as it will return a generator object just like a generator expression.\n**Note**: Use of `yield` inside a generator expression was allowed until Python 3.7 but is a syntax error from Python 3.8 onwards.\nIt is recommended to remove the yield statement here.\n\u003C!--more-->\n### Bad practice\n```python\nnumber_generator = ((yield num) for num in range(1,1000))\n```\n\n### Recommended\n```python\nnumber_generator = (num for num in range(1,1000))\n```",[],{"shortcode":1993,"title":1994,"description":1995,"category":19,"severity":1294,"tags":1996,"isRecommended":825},"PTC-W0032","Explicit exception raised in the assert message","Raising a built-in or a custom exception when `assert` fails is ineffective.\nAsserts always raise an `AssertionError`, making the provided exception which the user is expecting useless.\nThis may lead to runtime errors if this detail is not understood during the exception handling.\nIt is therefore recommended to use `if` to check the condition and raise the expression explicitly if something is not right.\n\u003C!--more-->\n\n### Bad practice\n```python\nassert isinstance(num_channels, int), ValueError(\"Field is not an integer\")\n```\nRunning this will give `AssertionError: Field is not an integer` and not the expected `ValueError`.\n\nA better way is to check the condition using an `If` statement and `raise` the exception if condition is not satisfied.\nLike this:\n\n### Recommended\n```python\nif not isinstance(nem_channels, int):\n    raise ValueError(\"Field is not an integer\")\n```\n\nThis gives the expected output `ValueError: Field is not an integer` when the condition fails.\n\n**Note: If this issue is autofixed, DeepSource will change `assert` statements to `if` checks to raise the exception mentioned in the assert fail message.**",[],{"shortcode":1998,"title":1999,"description":2000,"category":15,"severity":1294,"tags":2001,"isRecommended":825},"PYL-W1300","Format string key is not a string","Format string that uses named conversion specifiers is used with a dictionary whose keys are not all strings.\nA format string named conversion specifier is always a string. So, make sure all the dictionary keys are strings as well.\n\n#### Not preferred:\n```python\ndef greet_user(user):\n    print(\n        \"Hi %(1)s!. Welcome to %(location)s.\"\n        % {1: user.first_name, \"location\": user.updated_loc}\n    )\n```\n\n#### Preferred:\n```python\ndef greet_user(user):\n    print(\n        \"Hi %(name)s!. Welcome to %(location)s.\"\n        % {\"name\": user.first_name, \"location\": user.updated_loc}\n    )\n```",[],{"shortcode":2003,"title":2004,"description":2005,"category":19,"severity":1294,"tags":2006,"isRecommended":825},"PYL-E0102","Function or method is being redefined","A function, method or class is being redefined in the same scope.\nThis would override the original definition, and doing this is strongly discouraged.\nPlease verify that this is something that you intended to do.\n\u003C!--more-->\nRedefining anything can lead to confusion, decreases code readability and may cause bugs that are difficult to diagnose.\nIt is recommended either to refactor the function/method/class, or choose different names.\n\n### Bad practice\n```python\ndef calc(x, y):\n    return x + y\n\n\ndef calc(x, y):\n    return x * y\n```\n\n### Recommended\n```python\ndef calc_sum(x, y):\n    return x + y\n\n\ndef calc_product(x, y):\n    return x * y\n```",[],{"shortcode":2008,"title":2009,"description":2010,"category":41,"severity":1294,"tags":2011,"isRecommended":825},"PYL-R1723","Unnecessary `else` / `elif` used after `break`","The use of `else` or `elif` becomes redundant and can be dropped if the last statement under the leading `if` / `elif` block is a `break` statement.\nIn the case of an `elif` after `break`, it can be written as a separate `if` block.\nFor `else` blocks after `break`, the statements can be shifted out of `else`. Please refer to the examples below for reference.\n\nRefactoring the code this way can improve code-readability and make it easier to maintain.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef changing_denominators(p, q):\n    while True:\n        if q == 0:\n            break\n        else:\n            print(p/q)\n            q = q - 1\n\n```\n\n### Preferred:\n```python\ndef changing_denominators(p, q):\n    while True:\n        if q == 0:\n            break\n\n        print(p/q)\n        q = q - 1\n```",[],{"shortcode":2013,"title":2014,"description":2015,"category":41,"severity":1294,"tags":2016,"isRecommended":825},"PYL-R1724","Unnecessary `elif` / `else` block after `continue`","The use of `else` or `elif` becomes redundant and can be dropped if the last statement under the leading `if` / `elif` block is a `continue` statement.\nIn the case of an `elif` after `continue`, it can be written as a separate `if` block.\nFor `else` blocks after `continue`, the statements can be shifted out of `else`. Please refer to the examples below for reference.\n\nRefactoring the code this way can improve code-readability and make it easier to maintain.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef classify_number(x):\n    for num in range(x):\n        if x % 2 == 0:\n            continue\n        else:\n            print(f\"{num} is Odd}\")\n```\n\n### Preferred:\n```python\ndef classify_number(x):\n    for num in range(x):\n        if x % 2 == 0:\n            continue\n        print(f\"{num} is Odd}\")\n```",[],{"shortcode":2018,"title":2019,"description":2020,"category":19,"severity":1294,"tags":2021,"isRecommended":825},"PYL-W0128","Variable redeclared during assignment","A variable is being redeclared in the same assignment.\nIn this case, the variable will contain the last value assigned to it.\n\nIn most cases, the variable re-assignment is a result of a typing mistake, which can lead to unintentional results during the runtime.\nIt is therefore recommended to take another look at the assignments highlighted in the issues.\n\u003C!--more-->\n### Bad practice\n```python\nfor x, y, x in zip(range(1, 5), range(5, 10), range(15, 20)):  # Variable x is being redeclared.\n     ...\n```\n\n### Recommended\nConsider giving the variable a new name.\n```python\nfor x, y, z in zip(range(1, 5), range(5, 10), range(15, 20)):\n     ...\n```",[],{"shortcode":2023,"title":2024,"description":2025,"category":19,"severity":1294,"tags":2026,"isRecommended":825},"PYL-W0236","Inconsistent overridden method","You're changing the method's type while overriding it in the child class.\nThis may lead to unintentional bugs during runtime because of the incinsistency.\n\u003C!--more-->\nSome of the cases where this issue would be raised are:\n\n- Overriding a method as a property, or the other way around.\n- Changing a method to async during overriding, or vice versa.\n\n```python\nclass BaseClass(metaclass=abc.ABCMeta):\n    @property\n    @abc.abstractmethod\n    def prop(self):\n        ...\n\n    @abc.abstractmethod\n    def credit(self):\n        ...\n\n    async def yell(self):\n        ...\n```\n\n### Bad practice\n\n```python\nclass InvalidDerived(BaseClass):\n    def prop(self):  # Method was a property in the base class.\n        ...\n\n    @property\n    def credit(self):  # Method is being overridden as a `property`\n        ...\n\n    def yell(self):  # This was async in the base class\n        ...\n```\n\n### Recommended\n```python\nclass ValidDerived(BaseClass):\n    @property\n    def prop(self):\n        return None\n\n    def credit(self):\n        return None\n\n    async def yell(self):\n        ...\n```",[],{"shortcode":2028,"title":2029,"description":2030,"category":45,"severity":1294,"tags":2031,"isRecommended":825},"TYP-003","Missing `return` statement","This callable is expected to return a value but is missing a `return` statement.\n\n\u003C!--more-->\nDouble check that you didn't forget to return the correct value, or if the function doesn't actually return anything, fix the type annotation to `-> None` instead.\n\n### Bad practice\n```python\ndef greet(name: str) -> str:\n    f'Hello, {name}!'  # Forgot to print or return\n```\n### Recommended\n```python\ndef greet(name: str) -> str:\n    return f'Hello, {name}!'\n\n# Alternatively,\ndef greet(name: str) -> None:  # as this doesn't return anything\n    print(f'Hello, {name}!')\n```",[],{"shortcode":2033,"title":2034,"description":2035,"category":45,"severity":1294,"tags":2036,"isRecommended":825},"TYP-006","Missing return value","This callable is expected to return a value but nothing is being returned.\nEither make sure you return a value, or change the annotation to `-> None`.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef magic_number() -> int:\n    42  # Missing `return`\n```\n### Recommended\n```python\ndef magic_number() -> int:\n    return 42\n```",[],{"shortcode":2038,"title":2039,"description":2040,"category":19,"severity":1294,"tags":2041,"isRecommended":825},"PYL-W0640","Cell variable defined in loop","A variable used in a closure is defined in a loop.\nThis will result in all closures using the same value for the closed-over variable, which can pave way for a hideous bug.\n\n\u003C!--more-->\nConsider the following code snippet:\n```python\n# Motivation: Create 3 functions that return `x**2`, `x**3`, and `x**4`.\n# Note: This will be using the loop variable to show the bug.\npowers = [lambda x: x**i for i in range(2,5)]\n```\nSo, `powers` is supposed to contain 3 functions to return 2nd, 3rd and 4th powers of a given number.\nOn execution, these are the results:\n\n```bash\nIn [1]: powers = [lambda x: x**i for i in range(2,5)]\n\nIn [2]: powers[0](2)  # Expected result: 4 (2**2)\nOut[2]: 16\n\nIn [3]: powers[1](2)  # Expected result: 8 (2**3)\nOut[3]: 16\n\nIn [4]: powers[2](2)  # Expected result: 16 (2**4)\nOut[4]: 16\n```\nThis happens because i is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of i is 4, so all the functions now return x**4.\n\n### Recommended\nIn order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global `i`:\n```python\nIn [1]: powers = [lambda x, n =i: x**n for i in range(2,5)]\n\nIn [2]: powers[0](2)\nOut[2]: 4\n\nIn [3]: powers[1](2)\nOut[3]: 8\n\nIn [4]: powers[2](2)\nOut[4]: 16\n```\n## References\n- [Python Loops and closures](http://stupidpythonideas.blogspot.com/2016/01/for-each-loops-should-define-new.html)\n- [foreach-lambda problem](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result)",[],{"shortcode":2043,"title":2044,"description":2045,"category":15,"severity":1294,"tags":2046,"isRecommended":825},"PYL-W0714","Exceptions are overlapping","Two or more exceptions in the same exception handler clause that are identical or parts of the same inheritance hierarchy (i.e. overlapping).\nIt is recommmend to refactor this.\n\n#### Not preferred:\n```python\nclass SomeException(Exception):\n    pass\n\nclass SubclassException(SomeException):\n    pass\n\ntry:\n    raise SubclassException()\nexcept (SomeException, SubclassException):\n    pass\n```\n\nHere, `SubclassException` has been derived from `SomeException`, which makes it overlapping.\n\n#### Preferred:\n```python\nclass SomeException(Exception):\n    pass\n\nclass SubclassException(SomeException):\n    pass\n\ntry:\n    raise SubclassException()\nexcept SomeException:\n    pass\n```",[],{"shortcode":2048,"title":2049,"description":2050,"category":19,"severity":1294,"tags":2051,"isRecommended":825},"PYL-E0112","Assignment target contains multiple star expressions","More than one starred expression is being used in assignment. This is a `SyntaxError`.\n\n\u003C!--more-->\nPython allows a tuple or a list of variables to appear on the left side of an assignment operation.\nEach variable in the tuple receives one value (or more, if we use the * operator) from an iterable on the right side of the assignment.\n\nThe * operator collects or pack multiple values in a single variable.\nConsider the following snippet:\n```python\n*a, = 1, 2, 3\nprint(a) # Output = [1, 2, 3]\n```\nHere we pack a tuple of values into a single variable `a` by using the * operator.\n\n### Bad practice\n```python\n*foo, *bar = [1, 2, 3]\n```\n\n### Recommended\n```python\n*foo, bar = [1, 2, 3]\n```",[],{"shortcode":2053,"title":2054,"description":2055,"category":15,"severity":1294,"tags":2056,"isRecommended":825},"PYL-E1141","Missing `.items()`","You're trying to iterate through a dictionary without using the `.items()` (for Python 3) or `.iteritems()` (Python 2) method.\nThis is a `ValueError`.\n\n\u003C!--more-->\n### Bad practice\n```python\ndata = {'x': 1, 'y': 2, 'z': 3}\nfor key, value in data:\n    print(f'key: {key} => value: {value}')\n```\n\n### Recommended\n```python\ndata = {'x': 1, 'y': 2, 'z': 3}\nfor key, value in data.items():\n    print(f'key: {key} => value: {value}')\n```",[],{"shortcode":2058,"title":2059,"description":2060,"category":19,"severity":1294,"tags":2061,"isRecommended":825},"PYL-E1700","`yield from` inside an `async` function","Use of `yield from` is not permitted inside an async function. This is a syntax error.\nIt is recommend to rewrite coroutine without using `yield from`.\n\n\u003C!--more-->\n#### Bad practice\n```python\nasync def my_coroutine():\n    yield 1\n    yield from [2, 3, 4, 5, 6] # Syntax Error\n```\n\n### Recommended\n```python\nasync def my_coroutine():\n    yield 1\n    for i in [2, 3, 4, 5, 6]:\n        yield i\n```",[],{"shortcode":2063,"title":2064,"description":2065,"category":19,"severity":1294,"tags":2066,"isRecommended":825},"PYL-R0206","Property defined with parameters","A class `property` should not define any additional parameters since it can not be passed while accessing it.\n\n\u003C!--more-->\nIf a property with additional parameters is attempted to be accessed using additional parameters, those parameters would be applied to the return value of the called property, which can result in an unintended bug (explained in the example below).\n\nIf passing parameters is absolutely necessary, it is recommended to convert the property to a method.\n\n### Bad practice\n```python\nclass SomeClass:\n    @property\n    def get_my_lucky_number(self, num=5):\n        if num > 5:\n            return num\n\n        return 0\n```\nHere, the property `get_my_lucky_number` has been defined with a default argument `num`.\nA call like `SomeClass().get_my_lucky_number(num=7)` will raise  `TypeError: 'int' object is not callable`.\nThis is because parameter is passed to the return value of the property, which is an `int` here.\n\n### Recommended\n\nA class property shouldn't have any parameters. Here's how a property signature should look like:\n```python\nclass SomeClass:\n    @property\n    def get_my_lucky_number(self):\n        return 5\n```",[],{"shortcode":2068,"title":2069,"description":2070,"category":15,"severity":1294,"tags":2071,"isRecommended":825},"PYL-R1703","`if` statement can be simplified","The highlighted `if` block can be refactored into a simplified statement, increasing its readability.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef simplifiable_if(arg, arg2):\n    if arg and not arg2:\n        var = True\n    else:\n        var = False\n\n    return var\n```\n\n### Recommended\n```python\ndef simplifiable_if(arg, arg2):\n    var = bool(arg and not arg2)\n\n    return var\n```",[],{"shortcode":2073,"title":2074,"description":2075,"category":31,"severity":1294,"tags":2076,"isRecommended":825},"PYL-R1721","Unnecessary use of comprehension","It is unnecessary to use a comprehension just to loop over the `iterable` and create a `list`/`set`/`dict` out of it.\nPython has a specialized set of tools for this task: the `list`/`set`/`dict` constructors, which are faster and more readable.\n\n### Bad practice\n```python\nstates = [\n    ('AL', 'Alabama'),\n    ('AK', 'Alaska'),\n    ('AZ', 'Arizona'),\n    ('AR', 'Arkansas'),\n    ('CA', 'California'),\n    # ...\n]\n\nabbreviations_to_names = {\n    abbreviation: name\n    for abbreviation, name in states\n}\n```\n\n### Recommended\n```python\nstates = [\n    ('AL', 'Alabama'),\n    ('AK', 'Alaska'),\n    ('AZ', 'Arizona'),\n    ('AR', 'Arkansas'),\n    ('CA', 'California'),\n    # ...\n]\n\nabbreviations_to_names = dict(states)\n```",[],{"shortcode":2078,"title":2079,"description":2080,"category":19,"severity":1294,"tags":2081,"isRecommended":825},"PYL-R1722","Use of `exit()` or `quit()` detected","The `exit` or `quit` functions don't exist at top-level if python is started with the `-S` flag, and will raise an error. Use `sys.exit()` instead.\n\n\u003C!--more-->\nThe `exit` and `quit` functions are actually `site.Quitter` objects and are loaded, at interpreter start up, from `site.py`.\nHowever, if the interpreter is started with the `-S` flag, or a custom `site.py` is used then `exit` and `quit` may not be present.\nIt is recommended to use `sys.exit()` which is built into the interpreter and is guaranteed to be present.\n\n### Bad practice\n```python\ntry:\n    patch_diffs()\nexcept Exception as exc:\n    print(exc)\n    exit(1)\n```\nHere, `exit()` is used and will fail if the python is run with the `-S` option.\n\n### Recommended\n```python\nimport sys\n\n\ntry:\n    patch_diffs()\nexcept Exception as exc:\n    print(exc)\n    sys.exit(1)\n```\n`sys.exit()` is guaranteed to work, regardless of the interpreter options.",[],{"shortcode":2083,"title":2084,"description":2085,"category":19,"severity":1294,"tags":2086,"isRecommended":825},"PYL-W0126","Missing parentheses for a call in test","Conditional statement `if` or ternary `if` seems to wrongly call a function due to missing parentheses.\nThis may lead to unintended behaviour.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef bool_function():\n    return True\n\ndef nonbool_function():\n    return 42\n\nif bool_function: # Function not called\n    pass\n\nif nonbool_function: # Function not called\n    pass\n```\n\n### Recommended\n```python\ndef bool_function():\n    return True\n\ndef nonbool_function():\n    return 42\n\nif bool_function():\n    pass\n\nif nonbool_function():\n    pass\n```",[],{"shortcode":2088,"title":2089,"description":2090,"category":15,"severity":1294,"tags":2091,"isRecommended":825},"PYL-W0235","Useless super delegation","Any method in a child class which is only calling the overridden method of any of its base class using `super` and doing nothing else is unnecessary.\nIf the method isn't present in the child class, Python implicitly looks for the method in its base classes.\n\nThis issue is valid only if the method in the child class and the method in the base class has the same signature.\n\n### Bad practice\n```python\nclass Egg:\n    def __init__(self, first, second):\n        pass\n\n\nclass Spam(Egg):\n    def __init__(self, first, second):\n        super().__init__(first, second)\n\n    def __repr__(self):\n        return f'Spam({first}, {second})'\n\nclass UselessSuper:\n\n    def useless(self, first, *, second=None, **kwargs):\n        super().useless(first, second=second, **kwargs)\n\n```\n\n## Recommended:\n```python\nclass Egg:\n    def __init__(self, first, second):\n        pass\n\n\nclass Spam(Egg):\n    # `__init__` method removed entirely\n\n    def __repr__(self):\n        return f'Spam({first}, {second})'\n\n\nclass UselessSuper:\n    ...\n\n```",[],{"shortcode":2093,"title":2094,"description":2095,"category":19,"severity":1294,"tags":2096,"isRecommended":825},"PYL-W1302","Format string is not valid","The PEP-3101 format string is not valid and will give an error during the runtime.\n\n\u003C!--more-->\nNote: String formatting uses a limited Python-like syntax. Calls are not supported in this syntax; only subscription (indexing by number or unquoted (!) name) and attribute access is supported.\n\n### Bad practice\n```python\nprint('{a[0] + a[1]}'.format(a=[0, 1]))  # Operations, like `+` are not allowed inside format strings\n```\n### Recommended\n```python\nprint('{a[0]} + {a[1]}'.format(a=[0, 1]))  # Prints '0 + 1'\n```\n\n## References\n- [PEP-3101](https://www.python.org/dev/peps/pep-3101/#specification) - Advanced String Formatting",[],{"shortcode":2098,"title":2099,"description":2100,"category":19,"severity":1294,"tags":2101,"isRecommended":825},"PYL-W1502","`datetime.time` used in a boolean context","Using `datetime.time` in a boolean context can hide subtle bugs when the time they represent matches midnight UTC.\n\n\u003C!--more-->\nMidnight is represented by `datetime.time(0, 0, 0)`. However, this time (unlike all other valid times, including `datetime.time(0,0,1)`) evaluates to `false` in `if` conditions for Python 3.4 and older versions.\n\n### Bad practice\n```\nimport datetime\n\nstart_time = datetime.time(0, 0, 0)\nif start_time:  # Evaluates to False\n    doSomething()\n```\n### Recommended\n```\nimport datetime\n\nstart_time = datetime.time(0, 0, 0)\nif start_time is not None:  # Evaluates to True\n    doSomething()\n```\n\n## References\n```python\n- [Issue 13936](https://bugs.python.org/issue13936)\n- [A false midnight](https://lwn.net/Articles/590299/) - LWN article regarding behavior of datetime.time at midnight",[],{"shortcode":2103,"title":2104,"description":2105,"category":15,"severity":1294,"tags":2106,"isRecommended":825},"PTC-W0060","Implicit enumerate calls found","Using `range(len(...))` is not pythonic. Python does not have not index-based loops. Instead, it uses collection iterators.\n\nPython has a built-in method `enumerate` which adds a counter to an iterable.\nUsing this, you can access the counter and the value from the iterable at the same time.\nIt is therefore recommended to replace `range(len(...))` with `enumerate(...)`.\n### Not Preferred:\n```python\nfor index in range(len(mylist)):\n    ...\n```\n\n### Preferred:\n```python\nfor index, element in enumerate(mylist):\n    ...\n```",[],{"shortcode":2108,"title":2109,"description":2110,"category":15,"severity":1294,"tags":2111,"isRecommended":825},"PTC-W0037","Private attribute declared but not used","A private attribute defined in the class should be only accessible inside the class.\nThe names of attributes which are supposed to be public should not start with `_` or `__`.\n\u003C!--more-->\nThis issue concerns that one or more private attributes have been declared but are nowhere used in the class.\nIt is recommended either to remove the unused private attributes or remove the `__` prefix if it is intended to be accessed from outside the class.\n\n**Note**:\nA private attribute can not be accessed like other attributes.\nConsider a class `MyClass` with a private attribute: `__x`.\n\nNow, doing this will raise an `AttributeError`:\n```python\nc = MyClass()\nprint(c.__x)\n```\n\nBut you can access the private attribute like this (which is not recommended, just for the record):\n```python\nc = MyClass()\nprint(c._MyClass__x)\n```\n\nSo, if you want to fix this issue:\n* Make sure the private attribute is being used in the class it is declared.\n* Rename the attribute to comply with the conventions (Check References).\n* If the attribute is unnecessary, remove it.\n\n```python\nclass Example:\n\n    def __init__(self, attr=10):\n        self.__private = \"Placeholder\"\n        self.attr = attr\n\n    def init_val(self):\n        print(f\"class was initialised with the value: {self.attr}\")\n\n```\n\nHere, the attribute `self.__private` is unused and would not be accessible outside of the class directly.\n\n*_Note: This attribute would be removed during autofix._*\n\n## References:\n* [Python documentation for Private Variables](https://docs.python.org/3.8/tutorial/classes.html#private-variables).\n* [PEP 8 Style Guide: Designing for inheritance](https://www.python.org/dev/peps/pep-0008/#designing-for-inheritance).",[],{"shortcode":2113,"title":2114,"description":2115,"category":15,"severity":1294,"tags":2116,"isRecommended":825},"PTC-W0038","Private method declared but not used","A private method defined in the class should be only accessible inside the class.\nThe names of methods which are supposed to be public should not start with `_` or `__`.\n\u003C!--more-->\nThis issue concerns that one or more private methods have been declared but are nowhere used in the class.\nIt is recommended either to remove the unused private methods or remove the `__` prefix if it is intended to be accessed from outside the class.\n\n**Note**:\nA private method can not be accessed like other methods.\nConsider a class `MyClass` with a private method: `__x`.\n\nNow, doing this will raise an `AttributeError`:\n```python\nc = MyClass()\nprint(c.__x)\n```\n\nBut you can access the private method like this (which is not recommended, just for the record):\n```python\nc = MyClass()\nprint(c._MyClass__x)\n```\n\nSo, if you want to fix this issue:\n* Make sure the private method is being used in the class it is declared.\n* Rename the method to comply with the conventions (Check References).\n* If the method is unnecessary, remove it.\n\n```python\nclass Example:\n\n    def example_method(self):\n        print(\"I am accessible from outside the class\")\n\n    def __private(self):\n        print(\"I am an unused Private method\")\n```\n\nHere, the method `__private` is unused and would not be accessible outside of the class directly.\n\n*_Note: This method would be removed during autofix._*\n\n## References:\n* [Python documentation for Private Variables](https://docs.python.org/3.8/tutorial/classes.html#private-variables).\n* [PEP 8 Style Guide: Designing for inheritance](https://www.python.org/dev/peps/pep-0008/#designing-for-inheritance).",[],{"shortcode":2118,"title":2119,"description":2120,"category":19,"severity":1294,"tags":2121,"isRecommended":825},"PYL-E1602","Parameter unpacking detected","Tuple parameter unpacking has been removed from Python 3 and using it raises `SyntaxError`.\n\n\u003C!--more-->\nTuple parameter unpacking is the use of a tuple as a parameter in a function signature so as to have a sequence argument automatically unpacked.\n\nConsider the following code snippet when run using Python 2:\n```\ndef foo(a, (b, c), d):\n    print a, b, c, d\n\nt = (-5, 5)\nfoo(1, t, 3) ## Output: 1, -5, 5, 4\n```\nThe tuple `t` is passed to `foo`. The tuple gets unpacked and `b` and `c` gets assigned the first and second element of tuple respectively.\nRunning the code snippet using Python 3 will raise `SyntaxError`.\n\n### Bad practice\n```python\ndef some_function(a, (b, c), d):\n    ...\n```\n\n### Recommended\n```python\ndef some_function(a, b, c, d):\n    ...\n```\n\n## References:\n- [PEP-3113](https://www.python.org/dev/peps/pep-3113/)",[],{"shortcode":2123,"title":2124,"description":2125,"category":15,"severity":1294,"tags":2126,"isRecommended":825},"PY-W2000","Imported name is not used anywhere in the module","An object has been imported but is not used anywhere in the file.\nIt should either be used or the import should be removed.\n\u003C!--more-->\n\n### Bad practice\n```python\nimport os\n\ndef example():\n    print(\"This snippet is not using the `os` import anywhere.\")\n```\n\n### Recommended\n```python\ndef example():\n    print(\"This looks good now!\")\n```\n\n### But this import is used by other modules!\n\nOne major reason why this issue can cause confusion is when it's raised for\nimports that are meant to be exported, for use in other places.\n\nFor example, consider this file, `mypackage/__init__.py`:\n\n```python\nfrom mypackage.foo import is_foo\nfrom mypackage.bar import bar_function\n```\n\nThis is a very common pattern to export common functionality from modules, to\nthe top level of a package. But there is a major problem with this approach.\nConsider this file, `mypackage/foo.py`:\n\n```python\nimport os\n\ndef is_foo(item):\n    return os.path.exists(item)\n```\n\nSince `os` is imported inside `foo.py`, you can actually do this:\n\n```python\n>>> from mypackage.foo import os\n```\n\nAlthough weird, Python automatically exports all imports in a file. In practice\nhowever, it is ill-advised to rely on this behaviour.\n\nIf you want to explicitly export an imported item in a file, add it to the\nspecial variable named `__all__`:\n\n```python\nfrom mypackage.foo import is_foo\nfrom mypackage.bar import bar_function\n\n__all__ = ['is_foo', 'bar_function']  # Notice that these are strings!\n```\n\nDeepSource won't raise an issue if the imported item is present in `__all__`.",[],{"shortcode":2128,"title":2129,"description":2130,"category":15,"severity":1294,"tags":2131,"isRecommended":825},"PTC-W0064","Private nested class declared but not used","A private class defined in the class should be only accessible inside the class.\nThe names of nested classes which are supposed to be public should not start with `_` or `__`.\n\u003C!--more-->\nThis issue concerns that one or more private classes have been declared but are nowhere used in the class.\nIt is recommended either to remove the unused private classes or remove the `__` prefix if it is intended to be accessed from outside the class.\n\n**Note**:\nA private attribute can not be accessed like other attributes.\nConsider a class `MyClass` with a nested private class: `__PrivateClass`.\nNow, doing this will raise an `AttributeError`:\n```python\nc = MyClass()\nc.__PrivateClass()\n```\n\nBut you can access the private class like this (which is not recommended, just for the record):\n```python\nc = MyClass()\nc._MyClass__PrivateClass()\n```\n\nSo, if you want to fix this issue:\n* Make sure the nested private class is being used in the class it is declared.\n* Rename the class to comply with the conventions (Check References).\n* If the nested class is unnecessary, remove it.\n\n**At the moment, DeepSource can automatically fix the issue by removing the unused private classes.**\n\n### Bad practice\n```python\nclass AS:\n    class __NonPublicClass():  # Noncompliant\n        pass\n```\n\n### Recommended\n```python\nclass Compliant:\n    class __MyNonPublicClass():\n        pass\n\n    def process(self):\n        return Compliant.__MyNonPublicClass()\n```\n\n## References:\n* [Python documentation for Private Variables](https://docs.python.org/3.8/tutorial/classes.html#private-variables).\n* [PEP 8 Style Guide: Designing for inheritance](https://www.python.org/dev/peps/pep-0008/#designing-for-inheritance).",[],{"shortcode":2133,"title":2134,"description":2135,"category":19,"severity":1294,"tags":2136,"isRecommended":825},"PTC-W0068","Consider using identity comparison with singleton","Comparisons to the singleton objects, like `True`, `False`, and `None`, should be done with identity, not equality. Use `is` or `is not`.\n\n\u003C!--more-->\nIdentity checks are faster than equality checks.\n\nAlso, the equality checks can result in unintended behaviour in some cases:\n```python\n>>> 1 is True\nFalse\n>>> 1 == True\nTrue\n\n>>> 1.0 is True\nFalse\n>>> 1.0 == True\nTrue\n```\n\n### Bad practice\n```python\nvalue = fx()\nif value == True:  # `==` can cause unintended behaviour\n    print(value)\n\nif value != None:\n    print(value)\n```\n\n### Recommended\n```python\nvalue = fx()\nif value is True:  # `is` for Identity comparison\n    print(value)\n\nif value is not None:\n    print(value)\n```\n\n## Exceptions:\nEquality comparisons might be required in some cases, especially in SQLAlchemy, SQLObject, ORMs, etc.\nIn these cases, it is safe to ignore this issue.",[],{"shortcode":2138,"title":2139,"description":2140,"category":15,"severity":1294,"tags":2141,"isRecommended":825},"PY-W0069","Consider removing the commented out code block","It is recommended to remove any commented code in your codebase.\n\n\u003C!--more-->\n\n### Bad practice\n```python\nfor item in sequence:\n    # print(item)\n    do_something(item)\n\n# def old_function():\n#     '''Older implementation that has been replaced'''\n#     data = get_data()\n#     api.post(data)\n```\n\n### Recommended\n```python\nfor item in sequence:\n    do_something(item)\n```",[],{"shortcode":2143,"title":2144,"description":2145,"category":15,"severity":1294,"tags":2146,"isRecommended":825},"PY-W0070","Appending to list immediately following its definition","Instead of appending items to a list just after creation, it should be refactored to add those items into the list definition itself.\n\n\u003C!--more-->\n### Bad practice\n```python\nprocArgs = []\nprocArgs.append('terraform-analyzer')\nprocArgs.append('terraform-docs')\n```\n\n### Recommended\n```python\nprocArgs = ['terraform-analyzer', 'terraform-docs']\n```",[],{"shortcode":2148,"title":2149,"description":2150,"category":15,"severity":1294,"tags":2151,"isRecommended":825},"PY-W0071","Adding to set immediately following its definition","Instead of addepts items to a set just after creation, it should be refactored to add those items into the set definition itself.\n\n\u003C!--more-->\n### Bad practice\n```python\ntrees = set()\ntrees.add('cedar')\ntrees.add('oak')\n```\n\n### Recommended\n```python\ntrees = {'cedar', 'oak'}\n```",[],{"shortcode":2153,"title":2154,"description":2155,"category":15,"severity":1294,"tags":2156,"isRecommended":825},"PY-W0072","Appending to dictionary immediately following its definition","Instead of adding items to a dictionary just after creation, it should be refactored to add those items into the dict definition itself.\n\n\u003C!--more-->\n### Bad practice\n```python\nenv = {}\nenv['HOST'] = 'example.com'\nenv['PORT'] = 8080\n```\n\n### Recommended\n```python\nenv = {'HOST': 'example.com', 'PORT': 8080}\n```",[],{"shortcode":2158,"title":2159,"description":2160,"category":19,"severity":1294,"tags":2161,"isRecommended":825},"PY-W0073","Anomalous backslash detected","Backslash is present in the literal string but is not a valid escape sequence. If it is intended to be an escape sequence, use the correct escape characters. If it is intended to be a literal backslash, it can either be replaced with with an escaped backslash `\\\\`, or you can add an `r` prefix to make it a \"raw\" string.\n\n\u003C!--more-->\n### Bad practice\n```python\nfilepath =  \"C:\\myfiles\\run.py\"\n```\n\n### Recommended\n```python\nfilepath =  \"C:\\\\myfiles\\\\run.py\"  # use `\\\\` to render one backslash\nfilepath =  r\"C:\\myfiles\\run.py\"  # use the `r` prefix to avoid unnecessary escapes\n```",[],{"shortcode":2163,"title":2164,"description":2165,"category":19,"severity":1294,"tags":2166,"isRecommended":825},"PY-W0800","Logical operators used when combining SQL column expressions","Column expressions inside a sqlalchemy `where` or `having` clause must be combined using the bitwise `&` and `|` operators, not the logical `and` / `or`. Using logical operators cause various expressions to be ignored, leading to unintended behaviour.\n\n\u003C!--more-->\nYou can read about the ways to combine SQL expressions in sqlalchemy [here](https://docs.sqlalchemy.org/en/14/core/tutorial.html#conjunctions).\n\n### Bad practice\n```python\nfrom sqlalchemy import select\n\nselect([user.id, user.name]).where(\n    (user.org == my_org) and (user.active == True)  # Using `and` here won't work as you expect.\n)\n```\n\n### Recommended\n```python\nfrom sqlalchemy import select\n\nselect([user.id, user.name]).where(\n    (user.org == my_org) & (user.active == True)  # Replaced `and` with bitwise `&`.\n)\n```",[],{"shortcode":2168,"title":2169,"description":2170,"category":15,"severity":1294,"tags":2171,"isRecommended":825},"PY-W0079","Unnecessary use of `json.dumps()` for file data","The `json` module provides two ways to write JSON data: a `.dumps()` method that\naccepts a JSON string, and a `.dump()` method, that works with files directly.\nSo instead of using `json.dumps()` and writing to a file manually, it is\nrecommended to use `json.dump()` directly.\n\n\u003C!-- more -->\n\n### Bad practice\n\n```python\nwith open('data.json', 'w') as file:\n    file.write(json.dumps(data))  # Writing to file manually\n\nclass Socket:\n    def write_data(self, data):\n        self.socket.write(json.dumps(data))  # Writing to socket manually\n        self.socket.close()\n```\n\n### Recommended\n\n```python\nwith open('data.json', 'w') as file:\n    json.dump(data, file)  # Directly passing the file object\n\nclass Socket:\n    def write_data(self, data):\n        json.dump(data, self.socket)  # Directly passing the socket object\n        self.socket.close()\n```",[],{"shortcode":2173,"title":2174,"description":2175,"category":15,"severity":1294,"tags":2176,"isRecommended":825},"PY-W0078","Unnecessary use of `json.loads()` for file data","The `json` module provides two ways to read JSON data: a `.loads()` method that\naccepts a JSON string, and a `.load()` method, that works on files directly.\nSo instead of reading a file manually and passing it to `json.loads()`, it is\nrecommended to use `json.load()` directly.\n\n\u003C!-- more -->\n\n### Bad practice\n\n```python\nwith open('data.json') as file:\n    data = json.loads(file.read())  # Reading file manually\n\nclass Socket:\n    def read_json(self, data):\n        json.loads(self.socket.read())  # Reading socket manually\n        self.socket.close()\n```\n\n### Recommended\n\n```python\nwith open('data.json') as file:\n    data = json.load(file)  # Directly passing the file object\n\nclass Socket:\n    def read_json(self, data):\n        json.load(self.socket)  # Directly passing the socket object\n        self.socket.close()\n```",[],{"shortcode":2178,"title":2179,"description":2180,"category":19,"severity":1294,"tags":2181,"isRecommended":825},"PTC-W0067","Use of `sys.maxint` detected","`sys.maxint` has been removed in Python 3. It is recommended to use `sys.maxsize` instead.\n\n\u003C!--more-->\nThe sys.maxint constant was removed as there is no limit to the value of integers in Python 3. However, `sys.maxsize` can be used as an integer larger than any practical list or string index.\n\n### Bad practice\n```python\nimport sys\n\ncur_min = sys.maxint\n\nfor i in range(some_list):\n    if i \u003C cur_min:\n        cur_min = i\n```\n\n### Preferred\n```python\nimport sys\n\ncur_min = sys.maxsize\n\nfor i in range(some_list):\n    if i \u003C cur_min:\n        cur_min = i\n```",[],{"shortcode":2183,"title":2184,"description":2185,"category":15,"severity":1294,"tags":2186,"isRecommended":825},"PY-W0077","Consider merging `startswith`/`endswith` checks","The methods `startswith` and `endswith` for string instances accept two types of Python constructs as the first argument. The types are:\n\n* a Python string, or\n* a tuple of strings\n\nIt is recommended to merge the arguments of multiple calls to `startswith`/`endswith` connected by `or`.\n\n\u003C!--more-->\n\n### Bad practice\n```python\nif s.startswith('a') or s.startswith('b'):\n    ...\n```\n\n### Recommended\n```python\nif s.startswith(('a', 'b')):\n    ...\n```",[],{"shortcode":2188,"title":2189,"description":2190,"category":15,"severity":1294,"tags":2191,"isRecommended":825},"PYL-R0202","No `@classmethod` decorator","It is recommended to use the decorator syntax to declare a classmethod.\nRead more about classmethod [here](https://docs.python.org/3/library/functions.html#classmethod)\n\n\u003C!--more-->\n### Not preferred\n```python\nclass MyClass:\n\n    def cmethod(cls):\n        '''class method-to-be'''\n\n    # Convert cmethod to `classmethod`\n    cmethod = classmethod(cmethod)\n```\n\n### Preferred\n```python\nclass MyClass:\n\n    @classmethod\n    def cmethod(cls):\n        '''class method-to-be'''\n```",[],{"shortcode":2193,"title":2194,"description":2195,"category":15,"severity":1294,"tags":2196,"isRecommended":825},"FLK-W602","Deprecated form of raising exception detected","The `raise Exception, message` form of raising exceptions is deprecated in Python2, and removed in Python3.\n`raise Exception(message)` is the new form, and should be preferred.\n\u003C!--more-->\n### Bad practice\n```python\nraise ValueError, 'Expected \"foo\" to be > 0'\n```\n### Recommended\n```python\nraise ValueError('Expected \"foo\" to be > 0')\n```",[],{"shortcode":2198,"title":2199,"description":2200,"category":19,"severity":1294,"tags":2201,"isRecommended":825},"PYL-W1648","Bad Python 3 import","The module being imported may no longer be available in Python 3.\nPlease consult the documentation.\n\u003C!--more-->\nThe issue is raised for the following modules, that have been removed in the latest version of Python.\n\n- `anydbm`\n- `BaseHTTPServer`\n- `__builtin__`\n- `CGIHTTPServer`\n- `ConfigParser`\n- `copy_reg`\n- `cPickle`\n- `cStringIO`\n- `Cookie`\n- `cookielib`\n- `dbhash`\n- `dumbdbm`\n- `dumbdb`\n- `Dialog`\n- `DocXMLRPCServer`\n- `FileDialog`\n- `FixTk`\n- `gdbm`\n- `htmlentitydefs`\n- `HTMLParser`\n- `httplib`\n- `markupbase`\n- `Queue`\n- `repr`\n- `robotparser`\n- `ScrolledText`\n- `SimpleDialog`\n- `SimpleHTTPServer`\n- `SimpleXMLRPCServer`\n- `StringIO`\n- `dummy_thread`\n- `SocketServer`\n- `test`est_support\",\n- `Tkinter`\n- `Tix`\n- `Tkconstants`\n- `tkColorChooser`\n- `tkCommonDialog`\n- `Tkdnd`\n- `tkFileDialog`\n- `tkFont`\n- `tkMessageBox`\n- `tkSimpleDialog`\n- `UserList`\n- `UserString`\n- `whichdb`\n- `_winreg`\n- `xmlrpclib`\n- `audiodev`\n- `Bastion`\n- `bsddb185`\n- `bsddb3`\n- `Canvas`\n- `cfmfile`\n- `cl`\n- `commands`\n- `compiler`\n- `dircache`\n- `dl`\n- `exception`\n- `fpformat`\n- `htmllib`\n- `ihooks`\n- `imageop`\n- `imputil`\n- `linuxaudiodev`\n- `md5`\n- `mhlib`\n- `mimetools`\n- `MimeWriter`\n- `mimify`\n- `multifile`\n- `mutex`\n- `new`\n- `popen2`\n- `posixfile`\n- `pure`\n- `rexec`\n- `rfc822`\n- `sets`\n- `sha`\n- `sgmllib`\n- `sre`\n- `stringold`\n- `sunaudio`\n- `sv`\n- `test`estall\",\n- `thread`\n- `timing`\n- `toaiff`\n- `user`\n- `urllib2`\n- `urlparse`",[],{"shortcode":2203,"title":2204,"description":2205,"category":19,"severity":1294,"tags":2206,"isRecommended":825},"PYL-W5104","`exclude` used in a `ModelForm`","It is recommended to use explicit fields instead of `exclude` in a `ModelForm`. This prevents accidentally setting fields, especially when adding new fields to a model.",[],{"shortcode":2208,"title":2209,"description":2210,"category":37,"severity":1294,"tags":2211,"isRecommended":825},"PYL-W1509","Unsafe parameter given to `subprocess.Popen`","The `preexec_fn` parameter is not safe to use in the presence of threads in your application. The child process could deadlock before exec is called. If you must use it, keep it trivial. Minimize the number of libraries you call into.\nRef: https://docs.python.org/3/library/subprocess.html#popen-constructor",[1361,1204],{"shortcode":2213,"title":2214,"description":2215,"category":15,"severity":1294,"tags":2216,"isRecommended":825},"PTC-W0011","Use `items()` to iterate over a dictionary","The preferred way to iterate over the key-value pairs of a dictionary is to declare two variables in a for loop, and then call `dictionary.items()` (or `dictionary.iteritems()` for Python2), where dictionary is the name of your variable representing a dictionary.'\n\n\u003C!--more-->\n### Not preferred\n```python\ndetails = {\"first_name\": \"Alfred\", \"last_name\":\"Hitchcock\"}\nfor key in details.keys():\n    print(key, d[key])\n```\n### Preferred\n```python\ndetails = {\"first_name\": \"Alfred\", \"last_name\":\"Hitchcock\"}\nfor key, value in details.items():\n    print(key, value)\n```",[],{"shortcode":2218,"title":2219,"description":2220,"category":15,"severity":1294,"tags":2221,"isRecommended":825},"PTC-W0015","Unnecessary generator","It is unnecessary to use `list`, `set`, `dict` around a generator expression to get an object of that type since there are comprehensions for these types.\n\n\u003C!--more-->\n### Bad practice\n```python\nsquares = list(x**2 for x in range(1, 10))\nlarge_numbers = set(n for n in numbers if n > 1000)\ntree_counts = dict((tree, counts[tree]) for tree in trees)\n```\n### Recommended\n```python\nsquares = [x**2 for x in range(1, 10)]\nlarge_numbers = {n for n in numbers if n > 1000}\ntree_counts = {tree: counts[tree] for tree in trees}\n```",[],{"shortcode":2223,"title":2224,"description":2225,"category":19,"severity":1294,"tags":2226,"isRecommended":825},"PYL-W1641","Defining equality for a class without also defining hashability","In order to conform to the object model, classes that define their own equality method should also define their own hash method, or be unhashable. If the hash method is not defined then the hash of the super class is used. This is unlikely to result in the expected behavior.\n\nA class can be made unhashable by setting its `__hash__` attribute to None.\n\nIn Python 3, if you define a class-level equality method and omit a `__hash__` method then the class is automatically marked as unhashable.\n\nIt is recommended to implement a `__hash__` method or set `__hash__ = None`, whenever you define an `__eq__` method for a class.",[],{"shortcode":2228,"title":2229,"description":2230,"category":19,"severity":1294,"tags":2231,"isRecommended":825},"PYL-W0406","Module imports itself","The module is importing itself. This is not recommended.\n\u003C!--more-->\nConsider a module `foo.py`\n```python\nimport foo\nimport bar\n\n...\n```\nHere, module `foo` is trying to import a module named `foo`.",[],{"shortcode":2233,"title":2234,"description":2235,"category":41,"severity":2236,"tags":2237,"isRecommended":825},"FLK-E714","Test for object identity should be 'is not'","Tests for object identity should use the form `x is not None` rather than `not x is None`. The former example is more readable.\n\n\u003C!--more-->\n### Not preferred:\n```python\nvalue = get_result()\nif not value is None:\n    print(value)\n```\n\n### Preferred:\n```python\nvalue = get_result()\nif value is not None:\n    print(value)\n```","MINOR",[],{"shortcode":2239,"title":2240,"description":2241,"category":19,"severity":2236,"tags":2242,"isRecommended":825},"FLK-F812","List comprehension redefines name","A list comprehension uses the same name as another variable defined in the module, which can lead to confusion. Either change the variable name in the list comprehension or change it in the module.\n\n\u003C!--more-->\n### Bad practice\n```python\nitem = 12\nvalues = [item*2 for item in range(10)]  # name `item` re-used\n```\n### Recommended\n```python\nitem = 12\nvalues = [num*2 for num in range(10)]  # Using `num` to avoid name clashes.\n```",[],{"shortcode":2244,"title":2245,"description":2246,"category":19,"severity":2236,"tags":2247,"isRecommended":825},"PYL-W1662","Used a variable that was bound inside a comprehension","Accessed a variable, that was bound in a comprehension handler, outside of the comprehension itself. On Python 3 these variables will be deleted outside of the comprehension, and will give an error on being used.",[],{"shortcode":2249,"title":2250,"description":2251,"category":37,"severity":2236,"tags":2252,"isRecommended":825},"BAN-B611","Audit required: Potential SQL injection on `RawSQL` function","Use of `extra` in Django querysets should be audited, since unsanitized strings can open up security vulnerabilities.",[1503,1204],{"shortcode":2254,"title":2255,"description":2256,"category":37,"severity":2236,"tags":2257,"isRecommended":825},"BAN-B303","Audit required: Use of `md5`","Use of insecure MD2, MD4, MD5, or SHA1 hash functions should be avoided. Using more secure algorithms like SHA256 or SHA512.",[],{"shortcode":2259,"title":2260,"description":2261,"category":41,"severity":2236,"tags":2262,"isRecommended":825},"FLK-W292","No newline at end of file","It is recommended to put a newline at the end of the file.",[],{"shortcode":2264,"title":2265,"description":2266,"category":15,"severity":2236,"tags":2267,"isRecommended":825},"PYL-R1719","`if` expression used can be simplified","The `if` expression used here can be simplified to increase the code readability.\nExample:\n```python\nvalue = True if arg else False\n```\n\nThis can be simplified into:\n\n```python\nvalue = bool(arg)\n```",[],{"shortcode":2269,"title":2270,"description":2271,"category":41,"severity":2236,"tags":2272,"isRecommended":825},"FLK-W293","Blank line contains whitespace","Blank lines should not contain any tabs or spaces.",[],{"shortcode":2274,"title":2275,"description":2276,"category":19,"severity":2236,"tags":2277,"isRecommended":825},"PYL-R1706","Consider using an `if` expression","An instance of the pre-Python 2.5 ternary syntax is being used. It is recommended to use an `if` expression such as: `foo if condition else bar`.\nUsing `[condition] and [on_true] or [on_false]` may also give wrong results when `on_true` has a false boolean value.\n\n\u003C!--more-->\n*The inconsistency:*\nConsider the following example:\n```python\ndef get_val(condition, fallback, on_truth=None):\n    if on_truth is None:\n        on_truth = []\n\n    return condition and on_truth or fallback\n```\nHere, if `condition` is `True`, the function is supposed to return the value `on_truth` otherwise it will return the value `fallback`.\nThis would work fine for calls where the `on_truth` is not a `falsey` value.\nSo, for a call: `get_val(2>1, [1, 2, 3], [10, 20, 30])`, the output is as expected -> `[10, 20, 30]`\n\nBut, it would give the wrong result when `on_truth` is `falsey` value.\nFor the call: `get_val(2>1, [1, 2, 3])` expected result is `[]`, but the function will return the fallback value `[1, 2, 3]`.\n\nThis can be avoided by using `if expression`.\n\nPreferred:\n```python\ndef get_val(condition, fallback, on_truth=None):\n    if on_truth is None:\n        on_truth = []\n\n    return on_truth if condition else fallback\n```\n\nThe if expression is also more readable and straight forward.",[],{"shortcode":2279,"title":2280,"description":2281,"category":31,"severity":2236,"tags":2282,"isRecommended":825},"PTC-W0019","Consider using literal syntax to create the data structure","Using the literal syntax can give minor performance bumps compared to using function calls to create `dict`, `list` and `tuple`.\n\u003C!--more-->\n```python\nIn [1]: timeit.timeit(stmt=\"dict()\", number=100000000)\nOut[1]: 9.560388602000103\n\nIn [2]: timeit.timeit(stmt=\"{}\", number=100000000)\nOut[2]: 1.685333584000091\n\nIn [3]: timeit.timeit(stmt=\"tuple()\", number=100000000)\nOut[3]: 4.509182139000131\n\nIn [4]: timeit.timeit(stmt=\"()\", number=100000000)\nOut[4]: 0.5455615430000762\n\nIn [5]: timeit.timeit(stmt=\"list()\", number=100000000)\nOut[5]: 7.356000728000254\n\nIn [6]: timeit.timeit(stmt=\"[]\", number=100000000)\nOut[6]: 1.573771306999788\n```\nThis is because here, the name `dict` must be looked up in the global scope in case it has been rebound.\nSame goes for the other two types `list()` and `tuple()`.",[],{"shortcode":2284,"title":2285,"description":2286,"category":37,"severity":2236,"tags":2287,"isRecommended":825},"BAN-B410","Insecure `lxml` import detected","Using various methods to parse untrusted XML data is known to be vulnerable to XML attacks. Replace vulnerable imports with the equivalent [defusedxml](https://pypi.org/project/defusedxml) package.",[1503,1362,1204],{"shortcode":2289,"title":2290,"description":2291,"category":41,"severity":2236,"tags":2292,"isRecommended":825},"PTC-W0024","Bad `type` operand placement","The `type()` call shall be placed on the left side of the comparison when checking the type of one object against another type.\nThis affects readability.\n\n\u003C!--more-->\n### Not preferred\n```python\nx = 42\nif int is type(x):\n    print('This is an integer')\n```\n### Preferred\n```python\nx = 42\nif type(x) is int:\n    print('This is an integer')\n```\nOr even better, use `isinstance`:\n```python\nx = 42\nif isinstance(x, int):\n    print('This is an integer')\n```",[],{"shortcode":2294,"title":2295,"description":2296,"category":15,"severity":2236,"tags":2297,"isRecommended":825},"PYL-R1711","Useless `return` detected","A single `return` or `return None` statement is found at the end of the function or method definition. This statement can safely be removed to improve the readability because Python will implicitly return `None`.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef log_data(data):\n    '''Sends the data to our logging API.'''\n    api = get_api()\n    api.send(data)\n    return       # Unnecessary return\n\ndef print_pattern():\n    print('*')\n    print('**')\n    print('***')\n    return None  # Unnecessary return\n```\n### Recommended\n```python\ndef log_data(data):\n    '''Sends the data to our logging API.'''\n    api = get_api()\n    api.send(data)\n\ndef print_pattern():\n    print('*')\n    print('**')\n    print('***')\n```",[],{"shortcode":2299,"title":2300,"description":2301,"category":41,"severity":2236,"tags":2302,"isRecommended":825},"PYL-R1720","Unnecessary `else`/`elif` used after `raise`","`raise` causes control flow to be disrupted, as it will exit the block.\nIt is recommended to check other conditions using another `if` statement, and get rid of `else` statements as they are unnecessary.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef check_magic_generator(attribute):\n\n    magic = get_magic_number(attribute)\n\n    if magic \u003C 0:\n        raise ValueError(f\"{attribute} looks invalid\")\n    elif magic > 100\n        raise ValueError(f\"{attribute} is very magical\")\n    else:\n        return magic\n```\n\n### Recommended\n```python\ndef check_magic_generator(attribute):\n\n    magic = get_magic_number(attribute)\n\n    if magic \u003C 0:\n        raise ValueError(f\"{attribute} looks invalid\")\n    if magic > 100\n        raise ValueError(f\"{attribute} is very magical\")\n\n    return magic\n```",[],{"shortcode":2304,"title":2305,"description":2306,"category":19,"severity":2236,"tags":2307,"isRecommended":825},"PYL-W0212","Protected member accessed from outside the class","Accessing a protected member (a member prefixed with `_`) of a class from outside that class is not recommended, since the creator of that class did not intend this member to be exposed. If accesing this attribute outside of the class is absolutely needed, refactor it such that it becomes part of the public interface of the class.\n\n\u003C!--more-->\n### Bad practice\n```python\nclass Rectangle(object):\n    def __init__(self, height, width):\n        self._height = height\n        self._width = width\n\nr = Rectangle(4, 8)\narea = r._height * r._width\n```\n### Preferred:\n```python\nclass Rectangle(object):\n    def __init__(self, height, width):\n        self._height = height\n        self._width = width\n\n    def area():\n        return self._height * self._width\n\nr = Rectangle(4, 8)\narea = r.area()\n```",[],{"shortcode":2309,"title":2310,"description":2311,"category":19,"severity":2236,"tags":2312,"isRecommended":825},"PYL-W0221","Mismatched parameters in overridden method","The parameters in the overridden method don't match the method defined in the parent class.\nThere are three possible scenarios for this:\n\n- The number of parameters are different in both methods\n- One or more names of the parameters are different in both methods\n- The order of parameters is different in both methods\n\nPython will allow this, but if the overridden method is intended to be executed from external code, you may want to reconsider this.\nOverriding a method without ensuring that both methods accept the same name, number, and order of parameters has the potential to cause an error when the overriding method is called with parameters that is illegal for the overridden method. This violates the [Liskov substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle).\n\n\u003C!--more-->\n### Bad practice\n```python\nclass Base:\n    def summation(cycle, x, y, z):\n        log(cycle)\n        return x + y + z\n\n\nclass UneqalArgLen(Base):\n    def summation(cycle, x, y):\n        log(cycle)\n        return x + y\n\n\nclass RenamedArg(Base):\n    def summation(cycle, x, y, zee=None):\n        log(cycle)\n        return x + y\n\n\nclass unorderdArgs(Base):\n    def summation(x, cycle, y, z):\n        log(cycle)\n        return x + y + z\n```\n\n### Recommended\nThere can be multiple approaches to address this inconsistency.\nThe first approach is to re-think the method signature in the parent class itself if the child classes are expected to implement a variable number of arguments in their own implementation.\nIf the exploitation here is a special case, this can be dealt with making it compatible with the parent's class method signature, like this:\n```python\nclass Base:\n    def summation(cycle, x, y, z):\n        log(cycle)\n        return x + y + z\n\n\nclass FixedUneqalArgLen(Base):\n    def summation(cycle, x, y, z=None):\n        log(cycle)\n        return x + y\n\n\nclass NoRenamedArg(Base):\n    def summation(cycle, x, y, _):  # using `_` won't trigger the issue.\n        log(cycle)\n        return x + y\n\n\nclass NounorderdArgs(Base):\n    def summation(cycle, x, y, z):  # No surprises here\n        log(cycle)\n        return x + y + z\n\n```\n## References\n- [Liskov subsitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)",[],{"shortcode":2314,"title":2315,"description":2316,"category":15,"severity":2236,"tags":2317,"isRecommended":825},"PTC-W0023","Bad comparison test","It is recommended to use `identity test` ( `is` ) instead of equality test ( `==` ) when you need to compare types of two objects.\n\n\u003C!--more-->\n### Bad practice\n```python\nif type(x) == str:\n    print(x)\n```\n\n### Recommended\n```python\nif type(x) is str:\n    print(x)\n# Alternatively,\nif isinstance(x, str):\n    print(x)\n```",[],{"shortcode":2319,"title":2320,"description":2321,"category":19,"severity":946,"tags":2322,"isRecommended":2323},"PYL-E1201","Logging format string terminated in between conversion specifier","Logging statement format string shall not terminate before the end of a conversion specifier.",[],false,{"shortcode":2325,"title":2326,"description":2327,"category":19,"severity":946,"tags":2328,"isRecommended":2323},"PYL-E1004","Missing argument in `super()` call","In Python 2.x, the `super()` function must be called with the current class as the first argument, and the current instance as the second argument.",[],{"shortcode":2330,"title":2331,"description":2332,"category":19,"severity":946,"tags":2333,"isRecommended":2323},"PYL-E1126","Invalid sequence index found","A sequence type is indexed with an invalid type. Valid types are `int`s, slices, and objects with an `__index__` method.",[],{"shortcode":2335,"title":2336,"description":2337,"category":19,"severity":946,"tags":2338,"isRecommended":2323},"FLK-F823","Local variable name referenced before assignment","Local variables should be defined before they are referenced.",[],{"shortcode":2340,"title":2341,"description":2342,"category":19,"severity":946,"tags":2343,"isRecommended":2323},"PYL-E1138","Deletion attempted with unsupported object","Deletion is supported only for items which implement `__delitem__`.",[],{"shortcode":2345,"title":2346,"description":2347,"category":19,"severity":946,"tags":2348,"isRecommended":2323},"PYL-E0710","New-style class raised which doesn't inherit from `BaseException`","New-style classes raised must inherit from `BaseException`.",[],{"shortcode":2350,"title":2351,"description":2352,"category":19,"severity":946,"tags":2353,"isRecommended":2323},"PYL-E1003","Bad first argument given in `super()` call","The first argument to the `super()` function must be the current class.",[],{"shortcode":2355,"title":2356,"description":2357,"category":19,"severity":946,"tags":2358,"isRecommended":2323},"PYL-E1102","A non-callable object is being called","An object being called has been inferred to a non callable object. This is an error.",[],{"shortcode":2360,"title":2361,"description":2362,"category":19,"severity":946,"tags":2363,"isRecommended":2323},"PYL-E1200","Unsupported format character used in the logging format string","Logging format string must not contain any unsupported format character.",[],{"shortcode":2365,"title":2366,"description":2367,"category":19,"severity":946,"tags":2368,"isRecommended":2323},"PYL-E1127","Invalid slice index found","A slice is indexed with an invalid type. Valid types are `int`s, slices, and objects with an `__index__` method.",[],{"shortcode":2370,"title":2371,"description":2372,"category":37,"severity":946,"tags":2373,"isRecommended":2323},"BAN-B701","Use of jinja2 templates with `autoescape=False` detected","Using Jinja2 templates without autoescaping enabled leaves application vulnerable to [XSS attacks](https://owasp.org/www-project-top-ten/2017/A7_2017-Cross-Site_Scripting_(XSS).\n\n\u003C!--more-->\n[Autoescaping](https://flask.palletsprojects.com/en/1.1.x/templating/#controlling-autoescaping) is the concept of automatically escaping special characters. Special characters for HTML, XML and XHTMl are &, >, \u003C, \" as well as '. These characters carry specific meanings so need to be replaced by so called `entities` if you want to use them for text. Not doing so makes application susceptible to Cross Site Scripting (XSS) attacks.\n\nWhen configuring the Jinja2 environment, the option to use autoescaping on input can be specified. By default, autoescaping is disabled. When enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables.\n\n### Bad practice\n```python\nfrom jinja2 import Environment\n\ntemplate_env1 = Environment() # Insecure. Autoescape set to False by default\ntemplate_env2 = Environment(autoescape=False) # Insecure\n```\n\n### Recommended\n```python\nfrom jinja2 import Environment\n\ntemplate_env = Environment(autoescape=True) # Secure\n```\n\n## References:\n- [Autoescaping in Jinja](https://jinja.palletsprojects.com/en/2.11.x/api/#autoescaping)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE 79](https://cwe.mitre.org/data/definitions/79.html) - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')",[1647,1503,1362,2374,1704,1204],"cwe-79",{"shortcode":2376,"title":2377,"description":2378,"category":15,"severity":946,"tags":2379,"isRecommended":2323},"PTC-W0058","`list` object used during set creation","`list` type objects are unhashable and thus cannot be used for set initialization. Use `tuple` instead.\n\n### Not preferred:\n```python\nmyset = {[1, 2, 3]}\nset_b = set([[1, 2], [\"a\", \"b\"]])\nset_c = frozenset([(1, 2), [\"a\", \"b\"]])\n```\n\n### Preferred:\n```python\nset_a = {(1, 2, 3)}\nset_b = set([(1, 2), (\"a\", \"b\")])\nset_c = frozenset([(1, 2), (\"a\", \"b\")])\n```",[],{"shortcode":2381,"title":2382,"description":2383,"category":19,"severity":946,"tags":2384,"isRecommended":2323},"PTC-W0056","Dictionary size changed during iteration","Dictionaries are represented by a hash table and adding or removing items while iterating over it will alter the iteration order.\nThis will cause a `RuntimeError`.\n\n\u003C!--more-->\nIf you need to add items to the dictionary during iteration, it is recommended to iterate over a [shallow copy](https://docs.python.org/3/library/copy.html of the dictionary. A shallow copy creates a new object which stores the reference of the original elements.\n\n### Bad practice\n```python\nbasket = {\"oranges\": 2, \"apples\": 4, \"mangoes\": 10}\n\nfor fruit in basket:\n    if fruit == \"apples\":\n        del basket[fruit] # Runtime Error\n```\n\n### Recommended\n```python\nbasket = {\"oranges\": 2, \"apples\": 4, \"mangoes\": 10}\n\nfor fruit in basket.copy():\n    if fruit == \"apples\":\n        del basket[fruit] # No Runtime Error\n```\n\n## References:\n- [Shallow copy in Python](https://docs.python.org/3/library/copy.html)",[],{"shortcode":2386,"title":2387,"description":2388,"category":19,"severity":946,"tags":2389,"isRecommended":2323},"PTC-W0059","`yield` would not work as expected in the magic method","Not all magic method can used as generator function as Python's [datamodel](https://docs.python.org/3/reference/datamodel.html) is strict.\n\n\u003C!--more-->\nA function or method which uses the yield statement is called a generator function. Magic methods in Python are the special methods that start and end with the double underscores.\n\nUse of yield inside following magic methods in forbidden:\n\n- `__ixor__`\n- `__rrshift__`\n- `__lt__`\n- `__round__`\n- `__init__`\n- `__invert__`\n- `__pos__`\n- `__rdivmod__`\n- `__ceil__`\n- `__rsub__`\n- `__mul__`\n- `__eq__`\n- `__iadd__`\n- `__enter__`\n- `__index__`\n- `__aiter__`\n- `__radd__`\n- `__init_subclass__`\n- `__imul__`\n- `__matmul__`\n- `__ilshift__`\n- `__del__`\n- `__set__`\n- `__ne__`\n- `__truediv__`\n- `__sub__`\n- `__rmatmul__`\n- `__floordiv__`\n- `__rfloordiv__`\n- `__rxor__`\n- `__rpow__`\n- `__complex__`\n- `__iand__`\n- `__rmul__`\n- `__le__`\n- `__gt__`\n- `__contains__`\n- `__itruediv__`\n- `__missing__`\n- `__rtruediv__`\n- `__floor__`\n- `__get__`\n- `__int__`\n- `__imod__`\n- `__getattribute__`\n- `__new__`\n- `__len__`\n- `__getattr__`\n- `__imatmul__`\n- `__rlshift__`\n- `__instancecheck__`\n- `__divmod__`\n- `__isub__`\n- `__or__`\n- `__neg__`\n- `__bytes__`\n- `__ior__`\n- `__aexit__`\n- `__setattr__`\n- `__length_hint__`\n- `__rand__`\n- `__rshift__`\n- `__exit__`\n- `__lshift__`\n- `__delattr__`\n- `__subclasscheck__`\n- `__delete__`\n- `__pow__`\n- `__set_name__`\n- `__irshift__`\n- `__format__`\n- `__repr__`\n- `__anext__`\n- `__float__`\n- `__aenter__`\n- `__rmod__`\n- `__class_getitem__`\n- `__setitem__`\n- `__await__`\n- `__str__`\n- `__and__`\n- `__getitem__`\n- `__ifloordiv__`\n- `__delitem__`\n- `__ipow__`\n- `__hash__`\n- `__ge__`\n- `__trunc__`\n- `__dir__`\n- `__mod__`\n- `__ror__`\n- `__reversed__`\n- `__xor__`\n- `__abs__`\n- `__add__`\n- `__bool__`\n\nYou can remove `yield` from the magic method or rename it to be a custom method.\n\n### Bad practice\n```python\nclass MyClass:\n    def __init__(self):\n        yield 1\n```\n\n### Recommended\n```python\nclass MyClass:\n    def __init__(self):\n        pass\n```",[],{"shortcode":2391,"title":2392,"description":2393,"category":19,"severity":946,"tags":2394,"isRecommended":2323},"PTC-W0063","Unguarded next inside generator","Calls to `next()` should be inside `try-except` block.\n\n\u003C!--more-->\nWhen the iterator is exhausted, `StopIteration` exception is raised. When used inside a generator, this can cause unexpected behavior. If not handled, it will propagate out of the generator causing termination. [PEP-479](https://www.python.org/dev/peps/pep-0479/) has been accepted to fix this problem. It will modify the behavior of `StopIteration` in generators.\n\nEach call to `next()` should be wrapped in a `try-except` block to explicitly handle `StopIteration` exceptions.\n\n### Bad practice\n```python\ndef get_team_structure(team):\n    for team in class:\n        students = iter(team)\n        # StopIteration exception will be raised if team doesn't have members.\n        leader = next(students)\n        members = [m for m in students]\n        yield leader, members\n\ndef print_teams(teams):\n    for leader, members in get_team_structure(teams):\n        print(\"Leader: \"leader)\n        for member in members:\n            print(member)\n```\n\n## Recommended:\n```python\ndef get_team_structure(team):\n    for team in class:\n        # StopIteration exception will be raised if team has no members.\n        students = iter(team)\n        # Added `try` block, to guard against the exception\n        try:\n            leader = next(students)\n        except StopIteration:\n            # team has no members, skip it\n            continue\n\n        members = [m for m in students]\n        yield leader, members\n\ndef print_teams(teams):\n    for leader, members in get_team_structure(teams):\n        print(\"Leader: \"leader)\n        for member in members:\n            print(member)\n    ...\n```",[],{"shortcode":2396,"title":2397,"description":2398,"category":37,"severity":946,"tags":2399,"isRecommended":2323},"PY-S0900","Django app detected with DEBUG mode enabled","Running a Django application with debug mode enabled may allow an attacker to gain access to sensitive information. Ensure that Django applications that are run in a production environment have `DEBUG` set to `False`.\n\n \u003C!--more-->\nDebug mode helps developers to find bugs by providing information about the system and the users. The information may be security-sensitive. If enabled in a production environment, this information can help attackers know about the underlying tools, application settings, and so on.\nIt is recommended to configure another file (say, `development_settings.py`) in order to configure development-specific settings. Another recommended way is to read these values from environment variables.\n\n### Not Preferred:\n```python\nimport django\nfrom django.conf import settings\n\nsettings.configure(DEBUG=True)  # Sensitive\nsettings.configure(DEBUG_PROPAGATE_EXCEPTIONS=True)  # Sensitive\n\ndef some_config(config):\n    settings.configure(default_settings=config, DEBUG=True)  # Sensitive\n```\n\nDjango's \"settings.py\" or \"global_settings.py\" configuration file\n```python\nDEBUG = True  # Sensitive\nDEBUG_PROPAGATE_EXCEPTIONS = True  # Sensitive\n```\nIssue is raised for this case only if the file is named \"settings.py\" or \"global_settings.py\", the default names for Django configuration file.",[1203,1204],{"shortcode":2401,"title":2402,"description":2403,"category":37,"severity":946,"tags":2404,"isRecommended":2323},"PTC-W1002","Use of insecure `input` method detected","The `input` method in Python 2 will read from standard input, evaluate and run the resulting string as python source code.\nThis is similar, though in many ways worse, than using `eval`. On Python 2, use `raw_input` instead, `input` is safe in Python 3.",[1503,1204],{"shortcode":2406,"title":2407,"description":2408,"category":19,"severity":1294,"tags":2409,"isRecommended":2323},"PYL-E1139","Invalid metaclass","The class is using, as a metaclass, something which might be invalid for using as a metaclass.",[],{"shortcode":2411,"title":2412,"description":2413,"category":45,"severity":1294,"tags":2414,"isRecommended":2323},"TYP-042","Missing parameter in `Literal[...]` type hint","No parameter is given to `Literal[...]` type-hint. It must have at least one parameter.",[],{"shortcode":2416,"title":2417,"description":2418,"category":45,"severity":1294,"tags":2419,"isRecommended":2323},"TYP-044","Unsupported generic type annotation","Generic type annotation provided has no support. Please see the issue message for more context.",[],{"shortcode":2421,"title":2422,"description":2423,"category":41,"severity":1294,"tags":2424,"isRecommended":2323},"FLK-E743","Do not define functions named 'l', 'O', or 'I'","Functions named `I`, `O`, and `l` can be very hard to read. This is because the letter `I` and the letter `l` are easily confused, and the letter `O` and the number `0` can be easily confused.\n\nChange the names of these functions to something more descriptive.",[],{"shortcode":2426,"title":2427,"description":2428,"category":37,"severity":1294,"tags":2429,"isRecommended":2323},"BAN-B321","Detected calls to FTP-related functions","FTP-related functions are being called. FTP is considered insecure. Use SSH/SFTP/SCP or some other encrypted protocol.",[1362,1204],{"shortcode":2431,"title":2432,"description":2433,"category":45,"severity":1294,"tags":2434,"isRecommended":2323},"TYP-038","Deprecated type hint used","The special form `Any(...)` has been deprecated. Use `cast(Any, ...)` instead.",[],{"shortcode":2436,"title":2437,"description":2438,"category":19,"severity":1294,"tags":2439,"isRecommended":2323},"PYL-E1301","Format string truncated","The format string was terminated before the end of a conversion specifier. It is recommended to look again and verify if the conversion specifier is given.",[],{"shortcode":2441,"title":2442,"description":2443,"category":45,"severity":1294,"tags":2444,"isRecommended":2323},"TYP-050","Incompatible type detected","Type given is not compatible. See the issue message for more details.",[],{"shortcode":2446,"title":2447,"description":2448,"category":15,"severity":1294,"tags":2449,"isRecommended":2323},"PYL-R0205","Useless inheritance from `object`","The class is inheriting from `object`, which is implicit under Python 3 , hence can be safely removed from bases.\n\nNot preferred:\n```python\nclass Foo(object):\n    \"\"\"Foo bar baz\"\"\"\n```\n\nPreferred:\n```python\nclass Foo:\n    \"\"\"Foo bar baz\"\"\"\n```",[],{"shortcode":2451,"title":2452,"description":2453,"category":19,"severity":1294,"tags":2454,"isRecommended":2323},"PYL-W0402","Use of a deprecated module detected","The module imported has been deprecated for the current version of Python.\n\nDeprecated modules no longer get new feature or security updates, and are\nusually removed from the Python standard library 3-5 years after deprecation. It\nis highly recommended to stop depending on deprecated built-in modules.",[],{"shortcode":2456,"title":2457,"description":2458,"category":19,"severity":1294,"tags":2459,"isRecommended":2323},"PYL-W0632","Unbalanced tuple unpacking","Possible unbalanced tuple unpacking detected: either left or right side of the statement has more labels. This can raise `ValueError` while unpacking.",[],{"shortcode":2461,"title":2462,"description":2463,"category":45,"severity":1294,"tags":2464,"isRecommended":2323},"TYP-062","Type is not indexble","Type is not indexable. Please see the issue message for more details.",[],{"shortcode":2466,"title":2467,"description":2468,"category":19,"severity":1294,"tags":2469,"isRecommended":2323},"FLK-E101","Indentation contains mixed spaces and tabs","Indentation has has both tabs and spaces in it. You should use either tabs or spaces, but not both.",[],{"shortcode":2471,"title":2472,"description":2473,"category":41,"severity":1294,"tags":2474,"isRecommended":2323},"FLK-E704","Multiple statements on one line (def)","Multiple statements of a function definition should be on their own separate lines.",[],{"shortcode":2476,"title":2477,"description":2478,"category":45,"severity":1294,"tags":2479,"isRecommended":2323},"TYP-064","Can not assign to name without explicit type anotation","Explicit type annotation is needed to assign to name. Please see the occurrence message for more details.",[],{"shortcode":2481,"title":2482,"description":2483,"category":15,"severity":1294,"tags":2484,"isRecommended":2323},"PYL-R0123","Comparing to literal","Comparing an object to a literal is usually something you do not want to do, since you can compare to a different literal than what was expected altogether.",[],{"shortcode":2486,"title":2487,"description":2488,"category":45,"severity":1294,"tags":2489,"isRecommended":2323},"TYP-011","Invalid type hint parameter","In Python 2, type hint for return type must be `None` for generator.",[],{"shortcode":2491,"title":2492,"description":2493,"category":45,"severity":1294,"tags":2494,"isRecommended":2323},"TYP-046","Inconsistent number or arguments detected for type hint","Inconsistent number of argument given to a type hint.\nFor example, `Optional[...]`, and `Type[...]` must have exactly one type argument.\nPlease see the error message for more details.",[],{"shortcode":2496,"title":2497,"description":1324,"category":19,"severity":1294,"tags":2498,"isRecommended":2323},"PYL-W1603","Use of `buffer` built-in detected",[],{"shortcode":2500,"title":2501,"description":2502,"category":45,"severity":1294,"tags":2503,"isRecommended":2323},"TYP-037","Invalid type detected for type cast","The target of type cast is not a valid type.",[],{"shortcode":2505,"title":2506,"description":2507,"category":45,"severity":1294,"tags":2508,"isRecommended":2323},"TYP-031","Explicitly declared types are required for all `Protocol` members","All members of a protocol are required to have explicitly declared types. You can read more about it in this [PEP](https://www.python.org/dev/peps/pep-0544/)",[],{"shortcode":2510,"title":2511,"description":2512,"category":45,"severity":1294,"tags":2513,"isRecommended":2323},"TYP-009","Invalid return `type hint` for generator function","The return type of a generator function should be `Generator` or one of its supertypes.",[],{"shortcode":2515,"title":2516,"description":2517,"category":19,"severity":1294,"tags":2518,"isRecommended":2323},"PYL-W0231","`__init__` method from the base class not called","The ancestor class method has an init method which is not called by the derived class. This can cause unintended consequences.",[],{"shortcode":2520,"title":2521,"description":2522,"category":45,"severity":1294,"tags":2523,"isRecommended":2323},"TYP-014","Type error while assignment","Encountered a `TypeError` while assignment. Please see the message occurrence.",[],{"shortcode":2525,"title":2526,"description":2527,"category":45,"severity":1294,"tags":2528,"isRecommended":2323},"TYP-063","Missing free `type variable`","Free type variable is expected. Please see the occurrence message for details.",[],{"shortcode":2530,"title":2531,"description":2532,"category":15,"severity":1294,"tags":2533,"isRecommended":2323},"PTC-W0057","Sequence value overwritten unconditionally","You are assigning values at the same sequence index continuously without performing any other operations between them.\nThis might be something that was not intended and we suggest you retake a look at it.\nIf you want the value of the later assignment to be stored, it is recommended to remove this assignment, since it is anyways going to be overwritten.\n### Not preferred:\n```python\nsome_numbers = [1, 2, 3, 4, 5]\nsome_numbers[0] = 3\nsome_numbers[0] = 4  # unconditionally overwritting the existing value\n\nmymap = {'one': 1, 'two': 2}\nmymap['one'] = 4\nmymap['one'] = 3 # unconditionally overwritting value mapped to `one`\n```\n\n### Preferred:\n```python\nsome_numbers = [1, 2, 3, 4, 5]\nsome_numbers[0] = 3\ncheck_some_numbers()\nsome_numbers[0] = 4\n\nmymap = {'one': 1, 'two': 2}\nmymap['one'] = 4\nif condition:\n    mymap['one'] = 3\n```",[],{"shortcode":2535,"title":2536,"description":2537,"category":37,"severity":1294,"tags":2538,"isRecommended":2323},"PY-S0909","Security middleware not activated","`MIDDLEWARE` list in `settings.py` is missing `django.middleware.security.SecurityMiddleware`. Django's security middleware provides several security enhancements to the request/response cycle.\n\u003C!--more-->\n\nIf provided, it enables the following security features:\n- [HTTP Strict Transport Security](https://docs.djangoproject.com/en/3.1/ref/middleware/#http-strict-transport-security): Instruct browsers to always use HTTPS to connect to the application.\n- [Referrer Policy](https://docs.djangoproject.com/en/3.1/ref/middleware/#referrer-policy)\n- [X-Content-Type-Options](https://docs.djangoproject.com/en/3.1/ref/middleware/#x-content-type-options-nosniff):  Prevents the browser from guessing the content type and force it to always use the type provided in the `Content-Type` header.\n- [X-XSS-Protection](https://docs.djangoproject.com/en/3.1/ref/middleware/#x-xss-protection-1-mode-block): Enables the browser's built-in XSS protection.\n- [SSL Redirect](https://docs.djangoproject.com/en/3.1/ref/middleware/#ssl-redirect): If the `SECURE_SSL_REDIRECT` is set to `True`, `SecurityMiddleware` will permanently redirect all HTTP connections to HTTPS.\n\n### Bad practice\nIn `settings.py`\n```python\nfrom pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n\nINSTALLED_APPS = [\n    ...\n]\n\nMIDDLEWARE = [\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    ...\n]\n```\n\n### Recommended\nIn `settings.py`\n```python\nfrom pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n\nINSTALLED_APPS = [\n    ...\n]\n\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware', # Security middleware activated\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    ...\n]\n```\n\n## References:\n- [Django Security middleware Documentation](https://docs.djangoproject.com/en/3.1/ref/middleware/#module-django.middleware.security)\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)",[1203,2539,1204],"django",{"shortcode":2541,"title":2542,"description":2543,"category":19,"severity":1294,"tags":2544,"isRecommended":2323},"PYL-E1606","Use of long suffix","`l` or `L` is used to mark a long integer. This will not work in Python 3, since `int` and `long` types have merged.\n\n\u003C!--more-->\n### Bad practice\nIn Python 2\n```python\nmy_var = 1234l\n```\n### Recommended\n```python\nmy_var = 1234\n```",[],{"shortcode":2546,"title":2547,"description":2548,"category":19,"severity":1294,"tags":2549,"isRecommended":2323},"PYL-E1607","Old inequality operator used","Do not use the `\u003C>` operator. This is removed in Python 3 and will raise a `SyntaxError`. Use `!=` instead.\n\n\u003C!--more-->\n### Bad practice\nIn Python 2\n```python\nif a \u003C> b:\n    doSomething()\n```\n### Recommended\n```python\nif a != b:\n    doSomething()\n```",[],{"shortcode":2551,"title":2552,"description":2553,"category":19,"severity":1294,"tags":2554,"isRecommended":2323},"PYL-E1610","Non ascii bytes literals detected","Non-ascii byte literals are being used in this file. They are no longer supported in Python 3.\n\n\u003C!--more-->\n### Bad practice\n```python\nsome_var = b\"國華\"\n```\n### Recommended\n```python\nsome_var = b\"Guohua\"\n```",[],{"shortcode":2556,"title":2557,"description":2558,"category":31,"severity":1294,"tags":2559,"isRecommended":2323},"PYL-W1201","Logging is not lazy","The logging statement has the call of the form `logging.(format_string % (format_args...))`. For such calls, it is recommended to leave string interpolation to the logging method itself and be written as `logging.(format_string, format_args...)` so that the program may avoid incurring the cost of the interpolation in those cases in which no message will be logged.\nFor more details, see [PEP 282](http://www.python.org/dev/peps/pep-0282).\n\nNot Preferred:\n```python\nlogger.info(\"This is a log message %s %d %d\" % (msg, foo, bar))\n```\n\nPreferred:\n```python\nlogger.info(\"This is a log message %s %d %d\", msg, foo, bar)\n```",[],{"shortcode":2561,"title":2562,"description":1324,"category":19,"severity":1294,"tags":2563,"isRecommended":2323},"PYL-W1602","Use of `basestring` built-in detected",[],{"shortcode":2565,"title":2566,"description":2567,"category":45,"severity":1294,"tags":2568,"isRecommended":2323},"TYP-056","Invalid type for  `__all__`","Type of `__all__` must be sequence string. See the issue message for more details",[],{"shortcode":2570,"title":2571,"description":2572,"category":45,"severity":1294,"tags":2573,"isRecommended":2323},"TYP-041","Invalid `Literal[...]` type hint","Arbitrary arguments are given to `Literal[...]`, which makes it an invalid type. It is recommended to remove the arbitrary arguments.",[],{"shortcode":2575,"title":2576,"description":2577,"category":15,"severity":1294,"tags":2578,"isRecommended":2323},"PYL-W1304","Unused format string argument","The format string that uses named field(s), is used with an argument that is not required by the format string.\nIt is recommended to remove unused keyword-arguments for a better readability.\n\n#### Not preferred:\n```python\ndef greet_user(user):\n    print(\n        \"Hi {name}!. Welcome to {location}.\".format(\n            name=user.first_name, location=user.updated_loc, age=user.age\n        )\n    )\n```\nHere, the argument `age` is nowhere used in the format string and should be removed.\n\n### Preferred:\n```python\ndef greet_user(user):\n    print(\n        \"Hi {name}!. Welcome to {location}.\".format(\n            name=user.first_name, location=user.updated_loc\n        )\n    )\n```",[],{"shortcode":2580,"title":2581,"description":2582,"category":45,"severity":1294,"tags":2583,"isRecommended":2323},"TYP-073","Invalid definition of generic alias","You can not use a bound type variabe to define generic alias. Please see occurrence message for more details.",[],{"shortcode":2585,"title":2586,"description":2587,"category":19,"severity":1294,"tags":2588,"isRecommended":2323},"PYL-W1661","Used an exception object that was bound by an except handler","An exception, that was bound in an except handler, shall not be used outside of the except handler. On Python 3 these exceptions will be deleted once they get out of the except handler, and will give an error on being used.",[],{"shortcode":2590,"title":2591,"description":1324,"category":19,"severity":1294,"tags":2592,"isRecommended":2323},"PYL-W1609","Use of `raw_input` built-in detected",[],{"shortcode":2594,"title":2595,"description":2596,"category":19,"severity":1294,"tags":2597,"isRecommended":2323},"FLK-E113","Unexpected indentation","A line is indented when it shouldn’t be. Usually this will mean that multiple lines need to be indented at the same level.",[],{"shortcode":2599,"title":2600,"description":2601,"category":45,"severity":1294,"tags":2602,"isRecommended":2323},"TYP-071","Redundant `cast` detected","`cast` to the variable is useless and can be removed. Please see the occurrence message for details.",[],{"shortcode":2604,"title":2605,"description":2606,"category":45,"severity":1294,"tags":2607,"isRecommended":2323},"TYP-057","`TypeVar` value is not compatible","Incompatible `TypeVar` value. Please see the issue message for details.",[],{"shortcode":2609,"title":2610,"description":2611,"category":45,"severity":1294,"tags":2612,"isRecommended":2323},"TYP-047","Invalid type hint for `ClassVar`","The `type annotation` or `type comment` is not valid. Please see the issue message for more details.",[],{"shortcode":2614,"title":2615,"description":2616,"category":19,"severity":1294,"tags":2617,"isRecommended":2323},"PYL-E0117","`nonlocal` name found without binding","The `nonlocal` statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope **excluding globals**.\nHere, `nonlocal` has been provided with a name without any binding i.e., it couldn't be found in the enclosing scopes.\n\nBad syntax:\n```python\nx = \"something\"\ndef foo():\n    def bar():\n        def baz():\n            nonlocal x\n            ...\n```\nOn execution, python will throw a `SyntaxError` saying: `no binding for nonlocal 'x' found`\n\nThis is fine:\n```python\ndef foo():\n    x = \"something\"\n    def bar():\n        def baz():\n            nonlocal x\n            ...\n```",[],{"shortcode":2619,"title":2620,"description":1501,"category":37,"severity":1294,"tags":2621,"isRecommended":2323},"BAN-B319","Use of an insecure method from `xml.dom.pulldom` detected",[1503,1362,1204],{"shortcode":2623,"title":2624,"description":1501,"category":37,"severity":1294,"tags":2625,"isRecommended":2323},"BAN-B318","Use of an insecure method from `xml.dom.minidom` detected",[1503,1362,1204],{"shortcode":2627,"title":2628,"description":2629,"category":45,"severity":1294,"tags":2630,"isRecommended":2323},"TYP-019","Unsupported type application","The type application is not supported in this context. See the occurrence message for more details.",[],{"shortcode":2632,"title":2633,"description":2634,"category":37,"severity":1294,"tags":2635,"isRecommended":2323},"BAN-B413","Insecure library imported","Libraries like `crypto` and `pycrypto` are no longer actively maintained and has been deprecated in favor of pyca/cryptography library.\n\n`pycrypto` library is also known to have publicly disclosed [buffer overflow vulnerability](https://github.com/dlitz/pycrypto/issues/176).",[1627,1362,1204],{"shortcode":2637,"title":2638,"description":2639,"category":45,"severity":1294,"tags":2640,"isRecommended":2323},"TYP-054","Invalid type used for tuple index","Invalid types used for tuple index. Please see the issue message for details.",[],{"shortcode":2642,"title":2643,"description":2644,"category":45,"severity":1294,"tags":2645,"isRecommended":2323},"TYP-058","Invalid use of `TypeVar` found","The `TypeVar` being used can not be used as an expression here.",[],{"shortcode":2647,"title":2648,"description":2649,"category":45,"severity":1294,"tags":2650,"isRecommended":2323},"TYP-008","Invalid `type hint`","The type hint for exception must derived from BaseException.",[],{"shortcode":2652,"title":2653,"description":2654,"category":19,"severity":1294,"tags":2655,"isRecommended":2323},"PYL-E0114","Invalid star expression","During tuple unpacking, a star expression can only be used in an assignment target.\nUsing it in the value will raise a `SyntaxError`.\n\nNot preferred:\n```python\nvars = *[1, 2]\n```\n\nPreferred:\n```python\n# star expression is valid in assignment target\n*vars = [1, 2]\n\n# It's also valid inside another sequence\nmore_vars =  [1, 2, *(3, 4)]\n```",[],{"shortcode":2657,"title":2658,"description":1501,"category":37,"severity":1294,"tags":2659,"isRecommended":2323},"BAN-B316","Use of an insecure `expatbuilder` method",[1503,1362,1204],{"shortcode":2661,"title":2662,"description":2663,"category":31,"severity":1294,"tags":2664,"isRecommended":2323},"PYL-W0106","Expression not assigned","An expression that is not a function call is assigned to nothing. Probably something else was intended here. We recommend to review this.",[],{"shortcode":2666,"title":2667,"description":2668,"category":19,"severity":1294,"tags":2669,"isRecommended":2323},"FLK-F406","`from module import *` is only allowed at module level","Importing `*` is generally discouraged, but if there's a need regardless, such imports should only be done on module level.",[],{"shortcode":2671,"title":2672,"description":2673,"category":45,"severity":1294,"tags":2674,"isRecommended":2323},"TYP-032","Unsupported `Type` declaration","Declaring `Type` during an assignment to a non-self attribute is not supported.",[],{"shortcode":2676,"title":2677,"description":2678,"category":15,"severity":1294,"tags":2679,"isRecommended":2323},"PYL-W0715","Exception arguments suggest string formatting might be intended","Found multiple arguments to an exception constructor, the first of them a string literal containing what appears to be placeholders intended for formatting. In this case, it is recommended to format the message properly.",[],{"shortcode":2681,"title":2682,"description":1501,"category":37,"severity":1294,"tags":2683,"isRecommended":2323},"BAN-B317","Use of an insecure method from `xml.sax` detected",[1503,1362,1204],{"shortcode":2685,"title":2686,"description":2687,"category":15,"severity":1294,"tags":2688,"isRecommended":2323},"PYL-W0614","Unused import from wildcard import found","In a wildcard import, all public names defined in the module are imported. It is advised to explicitly import the values needed or modify the module being imported from and define __all__ to restrict the names to be imported.",[],{"shortcode":2690,"title":2691,"description":2692,"category":19,"severity":1294,"tags":2693,"isRecommended":2323},"PYL-E0107","Use of a non-existent operator detected","Detected the use of one of the C-style pre/post increment or decrement operators, `--` and `++`, which don't exist in Python.\nUse the `+=` or `-=` operators instead.\n\u003C!--more-->\nThis will cause an error:\n```python\nx = 50\nx++\n```\n\nBut, doing this is okay:\n```python\nx = 50\nx += 1\n```",[],{"shortcode":2695,"title":2696,"description":2697,"category":31,"severity":1294,"tags":2698,"isRecommended":2323},"PYL-R0201","Consider decorating method with `@staticmethod`","The method doesn't use its bound instance. Decorate this method with `@staticmethod` decorator, so that Python does not have to instantiate a bound method for every instance of this class thereby saving memory and computation. Read more about staticmethods [here](https://docs.python.org/3/library/functions.html#staticmethod).",[],{"shortcode":2700,"title":2701,"description":2702,"category":45,"severity":1294,"tags":2703,"isRecommended":2323},"TYP-034","Trying to declare type of a type variable","The type of a `Type` variable can not be declared. It is recommended to remove it.",[],{"shortcode":2705,"title":2706,"description":2707,"category":45,"severity":1294,"tags":2708,"isRecommended":2323},"TYP-040","Uexpected type hint","A type hint is expected within`[...]`. It is recommended to abide by this convention.",[],{"shortcode":2710,"title":2711,"description":2712,"category":37,"severity":1294,"tags":2713,"isRecommended":2323},"PYL-W0123","Audit required: Use of `eval`","Use of possibly insecure function - consider using safer `ast.literal_eval`. Read more on why should `eval` be avoided [here](https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided).",[1503,1204],{"shortcode":2715,"title":2716,"description":2717,"category":41,"severity":1294,"tags":2718,"isRecommended":2323},"FLK-E742","Do not define classes named 'l', 'O', or 'I'","Classes named `I`, `O`, and `l` can be very hard to read. This is because the letter `I` and the letter `l` are easily confused, and the letter `O` and the number `0` can be easily confused.\n\nChange the names of these classes to something more descriptive.",[],{"shortcode":2720,"title":2721,"description":2722,"category":19,"severity":1294,"tags":2723,"isRecommended":2323},"PYL-E0302","Special method defined with an invalid signature","Special methods are a set of predefined methods you can use to enrich your classes.\nHere, one or more special methods has been defined with an invalid number of parameters.\nIf the special method has too few or too many arguments, it might not work at all.\nIt is therefore recommended to take another look at the method definition.\n\u003C!--more-->\n### Bad practice\n```python\nclass Example:\n\n    def __enter__(self, other):  # special method `__enter__` provided with an extra arg\n        ...\n```\n\n### Recommended\n```python\nclass Example:\n\n    def __enter__(self):\n        ...\n```\n\n## References:\n- Python Docs for [special method names](https://docs.python.org/3/reference/datamodel.html#special-method-names).",[],{"shortcode":2725,"title":2726,"description":2727,"category":19,"severity":1294,"tags":2728,"isRecommended":2323},"PYL-W1646","Invalid string codec detected","`str.encode` or `str.decode` is being used with a non-text encoding.\nIt is recommended to use the [codecs](https://docs.python.org/3/library/codecs.html) module to handle arbitrary codecs.",[],{"shortcode":2730,"title":2731,"description":2732,"category":37,"severity":1294,"tags":2733,"isRecommended":2323},"BAN-B605","Starting a process with a shell detected","Spawning of a subprocess using a command shell is dangerous as it is vulnerable to various [shell injection attacks](https://owasp.org/www-community/attacks/Command_Injection). Great care should be taken to sanitize all input in order to mitigate this risk. Calls of this type are identified by the use of certain commands which are known to use shells.\n\n\u003C!--more-->\nIt is possible for an attacker to craft inputs to issue different commands than the ones you intended such as removing a file.\n\nIt is recommended to use functions that don't spawn a shell. If you must use them, use [`shlex.quote`](https://docs.python.org/3/library/shlex.html#shlex.quote) to sanitize the input by changing it to the shell-escaped version.\n\n### Bad practice\n```python\nimport os\n\n# Malicious input\nfilename = \"file.py; echo foo\"\n\n# Executing command in a shell without escaping. This will also run `echo foo`.\nos.system(\"git add \" + filename)\n```\n\n### Recommended\n```python\nimport os, shlex\n\n# Malicious input\nfilename = \"file.py; echo foo\"\n\n# This ensures someone can't inject other commands into the given command.\nos.system(\"git add \" + shlex.quote(filename))\n```\n\n## References:\n- [Command Injection](https://owasp.org/www-community/attacks/Command_Injection)\n- [shlex](https://docs.python.org/3/library/shlex.html)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-78](https://cwe.mitre.org/data/definitions/78.html)",[1647,2734,1503,1704,1204],"cwe-78",{"shortcode":2736,"title":2737,"description":2738,"category":41,"severity":1294,"tags":2739,"isRecommended":2323},"PYL-C0204","Bad metaclass-classmethod argument","Use of `cls` as the first named argument in a metaclass class method is recommended so it's easy to differentiate them from regular instance methods.\n\nNot preferred:\n```python\nclass MyMeta(type):\n    @classmethod\n    def some_method(self):\n       ...\n```\n\nPreferred:\n```python\nclass MyMeta(type):\n    @classmethod\n    def some_methon(cls):\n        ...\n```",[],{"shortcode":2741,"title":2742,"description":2743,"category":41,"severity":1294,"tags":2744,"isRecommended":2323},"PYL-R1707","Trailing comma tuple detected","In Python, a tuple can be created by the comma symbol. It is possible that one can actually create a tuple by misplacing a trailing comma, which can lead to potential weird bugs in your code.\nIt is recommended to always use parentheses explicitly for creating a tuple. This also improves readability.\n\n#### Not preferred:\n```python\nfruits = apple,\n```\n\n#### Preferred:\n```python\nfruits = (apple,)\n```",[],{"shortcode":2746,"title":2747,"description":2748,"category":41,"severity":1294,"tags":2749,"isRecommended":2323},"FLK-E111","Indentation is not a multiple of four","PEP8 recommends that Python code indentation be a multiple of four.",[],{"shortcode":2751,"title":2752,"description":2753,"category":15,"severity":1294,"tags":2754,"isRecommended":2323},"PYL-E1310","Bad string strip call","The argument to a `str.{l,r,}strip` call contains a duplicate character. Although this will not cause an error, but it is recommended to remove duplicates.\nThis may affect readability.",[],{"shortcode":2756,"title":2757,"description":2758,"category":19,"severity":1294,"tags":2759,"isRecommended":2323},"PYL-E1603","Unpacking in `except`","Implicit unpacking of exceptions in `except` clauses were supported in Python 2. \nThis has been removed from Python 3. Using this will give a `SyntaxError`. Read more about this [here](http://www.python.org/dev/peps/pep-3110/)",[],{"shortcode":2761,"title":2762,"description":2763,"category":15,"severity":1294,"tags":2764,"isRecommended":2323},"PYL-E5101","Model's `__unicode__` is not callable","Django models require a `__unicode__` method which must be callable.",[],{"shortcode":2766,"title":2767,"description":2768,"category":37,"severity":1294,"tags":2769,"isRecommended":2323},"BAN-B104","Audit: Binding to all interfaces detected with hardcoded values","Binding to all network interfaces can potentially open up a service to traffic on unintended interfaces, that may not be properly documented or secured. This can be prevented by changing the code so it explicitly only allows access from localhost.\n\n\u003C!--more-->\nWhen binding to `0.0.0.0`, you accept incoming connections from anywhere. During development, an application may have security vulnerabilities making it susceptible to SQL injections and other attacks. Therefore when the application is not ready for production, accepting connections from anywhere can be dangerous.\n\nIt is recommended to use `127.0.0.1` or local host during development phase. This prevents others from targeting your application and executing SQL injections against your project.\n### Bad practice\n```python\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('0.0.0.0, 31137)) # Binding to all interfaces\n```\n\n### Recommended\n```python\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('127.0.0.1', 31137)) # Binding to local host\n```\n```\n# References:\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)",[1203,1204],{"shortcode":2771,"title":2772,"description":2773,"category":41,"severity":1294,"tags":2774,"isRecommended":2323},"FLK-E701","Multiple statements detected on one line","Multiple statements should be on their own separate lines. This improves readability.",[],{"shortcode":2776,"title":2777,"description":2778,"category":37,"severity":1294,"tags":2779,"isRecommended":2323},"BAN-B414","Insecure `pycryptodome` library imported","pycryptodome is a direct fork of pycrypto that has not fully addressed the issues inherent in PyCrypto. It seems to exist, mainly, as an API compatible continuation of pycrypto and should be deprecated in favor of pyca/cryptography which has more support among the Python community.",[1627,1362,1204],{"shortcode":2781,"title":2782,"description":1324,"category":19,"severity":1294,"tags":2783,"isRecommended":2323},"PYL-W1613","Use of `xrange` built-in detected",[],{"shortcode":2785,"title":2786,"description":2787,"category":15,"severity":1294,"tags":2788,"isRecommended":2323},"PYL-W5102","Model has `__unicode__` method","Django models should not implement a `__unicode__` method for string representation when using Python 3. Use `__str__` instead.",[],{"shortcode":2790,"title":2791,"description":1501,"category":37,"severity":1294,"tags":2792,"isRecommended":2323},"BAN-B320","Use of an insecure method from `lxml.etree`",[1503,1362,1204],{"shortcode":2794,"title":2795,"description":2796,"category":37,"severity":1294,"tags":2797,"isRecommended":2323},"PYL-W0122","Audit required: Use of `exec`","Usage of `exec` function is strongly discouraged, since it opens up possibilities of unauthorized code execution if the statements are not escaped properly. Read more on why should `exec` be avoided [here](https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided).",[1503,1204],{"shortcode":2799,"title":2800,"description":2801,"category":37,"severity":1294,"tags":2802,"isRecommended":2323},"BAN-B301","Audit required: Use of `pickle` module","The [pickle](https://docs.python.org/3/library/pickle.html) module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.\n\n\u003C!--more-->\nPython's `pickle` module is used for serializing and de-serializing a Python object structure. Data serialization is the process of converting structured data to a format that allows sharing or storage of the data in a form that allows recovery of its original structure.\n\nInsecure deserialization is when an application deserializes the data that it gets without any kind of validation, or even the authenticity of the data. It is easy to execute arbitrary code when unpickling data. Unpickling can be exploited to execute arbitrary commands on your machine.\n\nIf `pickle` is not absolutely necessary for the use-case, consider using a safer serialization, like [PyYaml](https://pyyaml.org/wiki/PyYAMLDocumentation).PyYAML is a YAML parser and emitter for Python. YAML is language-agnostic and human-readable serialization format. But `pickle` has its advantages too. Pickle format is specific to Python and can represent a wide variety of data structures and objects where as YAML represents simple data types & structures in a language-portable manner.\n\nRecommended practices when using `pickle` module:\n\n- It should not be used between unknown parties. Unpickling data from malicious client can cause remote execution attack. Only unpickle data you trust.\n- Communicating parties should have an encrypted network connection. Otherwise, data to be unserialized can be modified and thus unsafe to pickle.\n- Consider signing data with [hmac](https://docs.python.org/3/library/hmac.html#module-hmac) if you need to ensure that it has not been tampered with. Pickle can be signed before storage or transmission, and its signature can be verified before loading it on the receiver side.\n\nRefer to [this blog post](https://www.synopsys.com/blogs/software-security/python-pickling/) to know more about dangers of using `pickle` module.\n\n### Bad practice\n```python\nfrom flask import request\n\nimport picke\n\n@app.route('/pickle')\ndef load():\n    data = request.GET.get(\"data\")\n    conf = pickle.load(data) # Insecure. Avoid using pickle\n```\n\n### Recommended\n```python\nfrom flask import request\n\nimport yaml\n\n@app.route('/yaml')\ndef load():\n    data = request.GET.get(\"data\")\n    conf = yaml.load(data) # Secure\n```\n\n## References:\n- OWASP Top 10 2021 Category A08 - [Software and Data Integrity Failures](https://owasp.org/Top10/A08_2021-Software_and_Data_Integrity_Failures/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE 502](https://cwe.mitre.org/data/definitions/502.html) - Deserialization of Untrusted Data\n- [pickle module](https://docs.python.org/3/library/pickle.html)\n- [yaml module](https://pyyaml.org/wiki/PyYAMLDocumentation)",[1647,2803,2804,1704,1204],"a08","cwe-502",{"shortcode":2806,"title":2807,"description":2808,"category":37,"severity":1294,"tags":2809,"isRecommended":2323},"BAN-B308","Audit required: Use of `mark_safe` detected","Use of `mark_safe()` may expose [cross-site scripting (XSS)](https://owasp.org/www-project-top-ten/2017/A7_2017-Cross-Site_Scripting_(XSS)) vulnerabilities and should be reviewed.\n`mark_safe` explicitly marks a string as safe for (HTML) output purposes.\n\n\u003C!--more-->\nDjango auto-escapes all output from template variable tags unless explicitly told not to. Use of `mark_safe()` function implies that the parameter is safe for client-side output without Django's automatic string escaping. It's a legitimate way of defining strings that are intended to be interpreted as HTML.\n\nUsing `mark_safe()` on an internally generated string is okay but becomes a security risk if used on unchecked user input.\n\nSince this is an audit issue, some occurrences may be harmless here. The goal is to bring the issue to attention. Please make sure that the input string is trusted. If the occurrences don't seem to be valid, please feel free to ignore them.\n\nWhen possible, use [format_html](https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html).\nIt is safe as all arguments are passed through [conditional_escape()](https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.conditional_escape)\n\n### Bad practice\n```\nmark_safe(\"\u003Cb>%s\u003C/b> %s\" % (user_input))\n```\n\n### Recommended\n```python\nformat_html(\"\u003Cb>%s\u003C/b>, user_input)\n```\n## References:\n- [mark_safe](https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.safestring.mark_safe)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [CWE 79](https://cwe.mitre.org/data/definitions/79.html) - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')",[1647,1503,2374,1704,1204],{"shortcode":2811,"title":2812,"description":2813,"category":37,"severity":1294,"tags":2814,"isRecommended":2323},"BAN-B310","Audit required: Use of an insecure method method from `urllib` detected","`urllib` not only opens `http://` or `https://` URLs, but also `ftp://` and `file://`.\nWith this, it might be possible to open local files on the executing machine which might be a security risk if the URL to open can be manipulated by an external user.\n\n \u003C!--more-->\nThe `urllib.request` module defines functions and classes which help in opening URLs. `urllib.request.open` can open `ftp://` and `file://` URLs. This is usually not intended and makes the application vulnerable to [Server Side Request Forgery](https://owasp.org/www-community/attacks/Server_Side_Request_Forgery) attack.\nPerforming requests from user-provided data could allow attackers to make requests on the internal network or change, retrieve or delete sensitive information. You are yourself responsible for validating the URL before opening it with `urllib`.\n\nIt is recommended to validate the user-provided data, such as the URL and headers used to construct the request.\n\nSince this is an audit issue, some occurrences may be harmless here. The goal is to bring the issue in attention.\nPlease make sure that the url is trusted. If the occurrences doesn't seem to be valid, please feel free to ignore them.\n\n### Bad practice\n```\nreq = urllib.Request.request(url)\nresp = urllib.request.urlopen(req)\n```\n\n### Recommended\n```python\n# Validate URL before opening it\nif url.lower().startswith('http'):\n  req = urllib.Request.request(url)\nelse:\n  raise ValueError from None\n\nwith urllib.request.urlopen(req) as resp:\n  [...]\n\n## References:\n- OWASP Top 10 2021 Category A10 - [Server Side Request Forgery](https://owasp.org/Top10/A10_2021-Server-Side_Request_Forgery_%28SSRF%29/)\n- [CWE-918](https://cwe.mitre.org/data/definitions/918.html) - Server-Side Request Forgery (SSRF)\n```",[1647,2815,2816,1204],"a10","cwe-918",{"shortcode":2818,"title":2819,"description":2820,"category":37,"severity":1294,"tags":2821,"isRecommended":2323},"BAN-B312","Audit required: Use of telnet detected","Telnet-related functions are being called. Telnet is considered insecure. Use SSH or some other encrypted protocol.\n\n\u003C!--more-->\nConsider the following points when using Telnet protocol:\n\n- Telnet is a plain-text protocol; anyone watching your Telnet packets on the wire will see your username, password, and everything you do on the remote system.\n- There are no authentication policies used in telnet, causing a massive security threat. Communication is carried out between the two desired hosts can be intercepted in the middle.\n\nUse [`ssh`](https://www.ssh.com/academy/ssh/protocol) as an alternative to `telnet`. It protects user identities, passwords, and data from network snooping attacks and allows secure logins and file transfers. The use of `telnet` has been replaced by `ssh` in almost all cases.\n\n### Bad practice\n```python\nimport telnetlib\n\nurl = \"telnet://a@somedomain.com\"\nconnection = telnetlib.Telnet(\"somehost\") # Sensitive, Using telnet protocol\n```\n\n### Recommended\n```python\nimport os\nfrom paramiko import SSHClient\n\nclient = SSHClient()\nurl = \"telnet://a@somedomain.com\"\npassword = os.environ.get('password')\nclient.connect(url, username='user', password=password)\n```\n\n## References:\n- [telnetlib module in Python](https://docs.python.org/3/library/telnetlib.html)\n- [Telnet security problems](https://www.ssh.com/academy/ssh/telnet)\n- [Paramiko module](http://www.paramiko.org/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-200](https://cwe.mitre.org/data/definitions/200.html) - Exposure of Sensitive Information to an Unauthorized Actor",[1647,1722,1362,1704,1204],{"shortcode":2823,"title":1292,"description":2824,"category":37,"severity":1294,"tags":2825,"isRecommended":2323},"PTC-W1004","Cipher used is not secure. It is recommended to replace it with a known secure cipher such as `AES`.\n\n\u003C!--more-->\nFollowing ciphers are considered weak for a variety of reasons:\n\n- [Single DES](https://pycryptodome.readthedocs.io/en/latest/src/cipher/des.html): DES was never cryptographically broken, but its key length is too short by nowadays standards and it could be brute forced with some effort.\n- [BlowFish](https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#cryptography.hazmat.primitives.ciphers.algorithms.Blowfish): Susceptible to attacks when using weak keys.\n- [ARC4](https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#cryptography.hazmat.primitives.ciphers.algorithms.ARC4): Weaknesses in its initial stream output.\n- [IDEA](https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#cryptography.hazmat.primitives.ciphers.algorithms.IDEA): Susceptible to attacks when using weak keys.\n\nNew applications should avoid their use and existing applications should strongly consider migrating away.\n\nIt is recommended to use [AES](https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#cryptography.hazmat.primitives.ciphers.algorithms.AES). AES is both fast and cryptographically strong. It is a good default choice for encryption.\n\n### Bad practice\n[pycryptodome library](https://pycryptodome.readthedocs.io/en/latest/index.html):\n```python\nfrom Crypto.Cipher import ARC4, DES\n\ncipher1 = ARC4.new(key)\ncipher2 = DES.new(key, DES.MODE_OFB)\n```\n[pyca/cryptography library](https://cryptography.io/en/latest/):\n```python\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\ncipher = Cipher(algorithms.Blowfish(key), modes.CBC(iv))\n```\n\n### Recommended\npycryptodome library:\n```python\nfrom Crypto.Cipher import AES\n\ncipher1 = AES.new(key, AES.MODE_EAX)\ncipher2 = AES.new(key, AES.MODE_OFB)\n```\npyca/cryptography library:\n```python\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n\ncipher = Cipher(algorithms.AES(key), modes.CBC(iv))\n```\n## References:\n- OWASP Top 10 2021 Category A02 - [Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [CWE 327](hhttps://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm",[1647,1627,1648,1362,1204],{"shortcode":2827,"title":2828,"description":2829,"category":37,"severity":1294,"tags":2830,"isRecommended":2323},"BAN-B108","Hardcoded temporary directory detected","Using hardcoded temp directory is unsafe. The program can be tricked into performing file actions against the wrong file or using a malicious file instead of the expected temporary file. Prefer using [tempfile](https://docs.python.org/3/library/tempfile.html)\n\n\u003C!--more-->\nMalicious users can predict the file name and write to the directory containing the temporary file. They effectively hijack the temporary file by creating a symlink with the name of the temporary file before the program creates the file itself. This allows a malicious user to supply malicious data or cause actions by the program to affect the attacker chosen files.\n\n[`tempfile.TemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile) function should be used to safely create temporary files. Besides creating temporary files safely, it creates random filenames, which can not be predicted, and cleans up the file automatically.\n\n### Bad practice\n```python\nwith open('/tmp/abc', 'w') as f: # Insecure, Hard coded temporary directory used\n    f.write('stuff')\n```\n\n### Recommended\n```python\nimport tempfile\n\n# Secure, temporary file is created using tempfile.TemporaryFile\n# File will be deleted on close\nwith tempfile.TemporaryFile() as tmp:\n    tmp.write('stuff')\n```\n\n## References:\n- OWASP Top 10 2021 Category A04 - [Insecure Design](https://owasp.org/Top10/A04_2021-Insecure_Design/)\n- [CWE 377](https://cwe.mitre.org/data/definitions/377) - Insecure Temporary File\n- [Python tempfile](https://docs.python.org/3/library/tempfile.html)",[1361,1710,1647,1204],{"shortcode":2832,"title":2833,"description":2834,"category":37,"severity":1294,"tags":2835,"isRecommended":2323},"BAN-B309","Use of `HTTPSConnection` may not be secure in Python versions \u003C 2.7.9","Use of `HTTPSConnection` on older versions of Python prior to 2.7.9 and 3.4.3 does not provide many of the assurances one would expect when using SSL and leaves connections open to potential man-in-the-middle attacks.\n\n\u003C!--more-->\nA secure SSL session relies on validation of a `X.509 certificate`. Basic checks include:\n\n- Certificate Authority trust verification\n- Certificate revocation status\n- Certificate expiration\n- Certificate subject name matching\n\nThe `HTTPSConnection` class is used in a large number of locations and fails to check that certificates are signed by a valid authority. Without that check in place, the subsequent checks (some highlighted above) are largely invalid.\n\nThe result is that an attacker who has access to the network traffic between two endpoints relying on `HTTPSConnection` can trivially create a certificate that will be accepted by `HTTPSConnection` as valid - allowing the attacker to intercept, read and modify the traffic that should be encrypted by `SSL`.\n\nIt is recommended to update the Python version.\n\n### Bad practice\n```python\nconn = httplib.HTTPSConnection(proxy_host, proxy_port)\n```\n\n## References:\n- OWASP Top 10 2021 Category A02 - [Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- Please see [this report](https://wiki.openstack.org/wiki/OSSN/OSSN-0033) for details.",[1627,1362,1204],{"shortcode":2837,"title":2838,"description":2839,"category":37,"severity":1294,"tags":2840,"isRecommended":2323},"BAN-B313","Use of an insecure method from `xml.etree.cElementTree` detected","Using various XML methods to parse untrusted XML data is known to be vulnerable to XML attacks. Using the [defusedxml](https://pypi.org/project/defusedxml) module is recommended. Methods should be replaced with their `defusedxml` equivalents.\n\n\u003C!--more-->\n`xml.etree.cElementTree` is the C implementation of the `xml.etree.cElementTree` API.\nIt has been deprecated since version 3.3. Use of `xml.etree.cElementTree` in itself is insecure.\n\nThe `xml.etree.ElementTree` module implements a simple and efficient API for parsing and creating XML data. But it makes the application vulnerable to:\n\n- [Billion Laughs attack](https://en.wikipedia.org/wiki/Billion_laughs_attack): It is a type of denial-of-service attack aimed at XML parsers. It uses multiple levels of nested entities. If one large entity is repeated with a couple of thousand chars repeatedly, the parser gets overwhelmed.\n- [Quadratic blowup attack](https://www.acunetix.com/vulnerabilities/web/xml-quadratic-blowup-denial-of-service-attack/): It is similar to a Billion Laughs attack. It abuses entity expansion, too. Instead of nested entities, it repeats one large entity with a couple of thousand chars repeatedly.\n\nReplace vulnerable imports with the equivalent [defusedxml](https://pypi.org/project/defusedxml) package, or make sure `defusedxml.defuse_stdlib()` is called.\n\n### Bad practice\n```python\nimport xml.etree.cElementTree as ET\ntree = ET.parse('some_fie.xml') # Use of method from etree.cElementTree\n```\n### Recommended\n```python\nfrom defusedxml.ElementTree import parse\ntree = parse('some_fie.xml')\n```\n\n## References:\n- [xml.etree](https://docs.python.org/3/library/xml.etree.elementtree.html)\n- [defusedxml](https://pypi.org/project/defusedxml/)\n- [XML vulnerabilities](https://docs.python.org/3/library/xml.html#xml-vulnerabilities)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [CWE-611](https://cwe.mitre.org/data/definitions/611.html)",[1647,1503,1716,1362,1704,1204],{"shortcode":2842,"title":2843,"description":2844,"category":37,"severity":1294,"tags":2845,"isRecommended":2323},"BAN-B402","File Transfer Protocol (FTP) related module imported","A FTP-related module is being imported. FTP is considered insecure. Use SSH/SFTP/SCP or some other encrypted protocol.\n\u003C!--more-->\nConsider the following points when using Telnet protocol:\n\n- FTP is a plain-text protocol, anyone watching your ftp packets on the wire will see your username, password, and everything you do on the remote system. Data sent via FTP is vulnerable to sniffing, spoofing, and brute force attacks, among other basic attack methods.\n- There are no authentication policies used in FTP causing huge security threat. Communication is carried out between the two desired hosts can be intercepted in the middle.\n\nThere are several common approaches to addressing these challenges and securing FTP usage. FTPS is an extension of FTP that can encrypt connections at the client’s request. Transport Layer Security (TLS), Secure Socket Layer (SSL), and SSH File Transfer Protocol (also known as Secure File Transfer Protocol or SFTP) are often used as more secure alternatives to FTP because they use encrypted connections.\n\n[`pysftp`](https://pysftp.readthedocs.io/en/release_0.2.9/) is an easy to use sftp module that utilizes paramiko and pycrypto. It provides a simple interface to sftp. It is recommended to use `pysftp` over `ftblib`.\n\n### Bad practice\n```python\nimport ftplib\n\nurl = \"ftp://a@somedomain.com\"\nconnection = ftplib.FTP(url) # Sensitive, Using FTP protocol\n```\n\n### Recommended\n```python\nimport pysftp\n\nurl = \"ftp://a@somedomain.com\"\nconnection = pysftp.Connection(host=url, username=username, password=password)\n```\n\n## References:\n- [ftplib module](https://docs.python.org/3/library/ftplib.html)\n- [ftplib security problems](https://digitalguardian.com/blog/what-ftp-security-securing-ftp-usage)\n- [pysftp module](https://pysftp.readthedocs.io/en/release_0.2.9/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-200](https://cwe.mitre.org/data/definitions/200.html)",[1647,1722,1362,1704,1204],{"shortcode":2847,"title":2848,"description":2849,"category":37,"severity":1294,"tags":2850,"isRecommended":2323},"BAN-B502","Detected use of a bad version of `SSL`","Several highly publicized exploitable flaws have been discovered in all versions of SSL and early versions of TLS. It is strongly recommended that use of the following known broken protocol versions be avoided:\n\n- SSL v2\n- SSL v3\n- TLS v1\n- TLS v1.1\n\n \u003C!--more-->\nEnsure that a modern, strong protocol is used. All versions listed above are known to be vulnerable to attacks. Using [TLS v1.2](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_TLSv1_2) is strongly recommended.\n### Bad practice\n```python\nimport ssl\nimport socket\n\nssl.wrap_socket(socket.socket(), ssl_version=ssl.PROTOCOL_SSLv2) # Insecure. SSL v2 used\n```\n\n### Recommended\n```python\nimport ssl\nimport socket\n\nssl.wrap_socket(socket.socket(), ssl_version= ssl.PROTOCOL_TLSv1_2) # Secure, TLS v1.2 used\n```\n\n## References:\n- [ssl module in python](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_SSLv2)\n- [TLS v1.2](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_TLSv1_2)\n- OWASP Top 10 2021 Category A02 - [Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- [CWE 327](https://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm",[1647,1203,1627,2851,1204],"cwe-326",{"shortcode":2853,"title":2854,"description":2855,"category":37,"severity":1294,"tags":2856,"isRecommended":2323},"BAN-B505","Detected use of a weak cryptographic key","Key length, should provide enough entropy against brute-force attacks. Due to increase in computational power, cryptographic algorithms when used with smaller length keys have become susceptible.\n\n\u003C!--more-->\nRecommended key lengths for different algorithms:\n\n- RSA and DSA algorithms is 2048 and higher. Keys with 1024 bits and below are now considered breakable.\n- EC key length sizes are recommended to be 224 and higher with 160 and below considered breakable.\n- For RSA public key exponent should be at least 65537.\n\n### Bad practice\n```python\nfrom cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa\n\ndsa.generate_private_key(key_size=1024, backend=backend) # Insecure. Key size is less than 2048\n# Insecure. Key size is less than 2048, public exponent less than 65537\nrsa.generate_private_key(public_exponent=888, key_size=1024, backend=backend)\nec.generate_private_key(curve=ec.SECT163R2, backend=backend) # Insecure. Key size is less than 224\n``\n\n### Recommended\n```python\nfrom cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa\n\ndsa.generate_private_key(key_size=2048)\nrsa.generate_private_key(public_exponent=65537, key_size=65537)\nec.generate_private_key(curve=ec.SECT163R2)\n```\n\n## References:\n- [cryptography module](https://cryptography.io/en/latest/)\n- OWASP Top 10 2021 Category A02 - [Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- [CWE 327](https://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm",[1647,1203,1627,1648,1204],{"shortcode":2858,"title":2859,"description":2860,"category":37,"severity":1294,"tags":2861,"isRecommended":2323},"BAN-B506","Unsafe usage of `yaml.load` function detected","It is not safe to call [yaml.load](https://pyyaml.org/wiki/PyYAMLDocumentation) with any data received from an untrusted source.\nThe `yaml.load` function provides the ability to construct an arbitrary Python object, which may be dangerous if you receive a YAML document from an untrusted source.\n\n\u003C!--more-->\nDeserialization of untrusted data exposes application to:\n\n- [Parameter tampering attacks](https://owasp.org/www-community/attacks/Web_Parameter_Tampering): Manipulation of parameters exchanged between client and server in order to modify application data, such as user credentials and permissions, price and quantity of products, etc.\n- [Remote code execution attacks](https://owasp.org/www-community/attacks/Command_Injection): Structure of unserialized data is changed to modify the behavior of object being unserialized.\n\nIt is recommended to use `yaml.safe_load`. The function `yaml.safe_load` limits this ability to simple Python objects like integers or lists.\n\n### Bad practice\n```python\nfrom flask import request\n\nimport yaml\n\n@app.route('/yaml')\ndef load():\n    data = request.GET.get(\"data\")\n    conf = yaml.load(data) # Insecure. Avoid using yaml.load\n```\n\n### Recommended\n```python\nfrom flask import request\n\nimport yaml\n\n@app.route('/yaml')\ndef load():\n    data = request.GET.get(\"data\")\n    conf = yaml.safe_load(data) # Secure\n```\n\n## References:\n- [pyyaml](https://pyyaml.org/wiki/PyYAMLDocumentation)\n- [Web parameter tampering](https://owasp.org/www-community/attacks/Web_Parameter_Tampering)\n- [Code injection](https://owasp.org/www-community/attacks/Command_Injection)\n- OWASP Top 10 2021 Category A08 - [Software and Data Integrity Failures](https://owasp.org/Top10/A08_2021-Software_and_Data_Integrity_Failures/)\n- [SAN Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE 502](https://cwe.mitre.org/data/definitions/502.html) - Deserialization of untrusted data",[1647,2804,2803,1704,1204],{"shortcode":2863,"title":2864,"description":2865,"category":37,"severity":1294,"tags":2866,"isRecommended":2323},"BAN-B602","Detected subprocess `popen` call with shell equals `True`","Using `shell=True` can expose you to security risks if someone crafts input to issue different commands than the ones you intended.\n\n\u003C!--more-->\nPython possesses many mechanisms to invoke an external executable. However, doing so may present a security issue if appropriate care is not taken to sanitize any user-provided or variable input. Subprocess invocation using a command shell is dangerous as it is vulnerable to various [shell injection attacks](https://owasp.org/www-community/attacks/Command_Injection). It is possible for an attacker to craft inputs to issue different commands than the ones you intended, for example: removing a file.\n\nGreat care should be taken to sanitize all input in order to mitigate this risk. Calls of this type are identified by a parameter of `shell=True` being given.\n\nIt is recommended to use functions that don't spawn a shell. If you must use them, use [`shlex.quote`](https://pypi.org/project/shellescape/) to sanitize the input.\n\n### Bad practice\n```python\nimport subprocess\n\nsubprocess.Popen(cmd, shell=True)  # Sensitive, shell spawned\n```\n\n### Recommended\n```python\nimport subprocess\n\nsubprocess.Popen(cmd)\n```\n\n## References:\n- [subprocess.popen](https://docs.python.org/3/library/subprocess.html#popen-constructor)\n- [Subprocess security considerations](https://docs.python.org/3/library/subprocess.html#security-considerations)\n- [shlex](https://docs.python.org/3/library/shlex.html)\n- [Command Injection](https://owasp.org/www-community/attacks/Command_Injection)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-78](https://cwe.mitre.org/data/definitions/78.html)",[1647,2734,1503,1704,1204],{"shortcode":2868,"title":2869,"description":2870,"category":37,"severity":1294,"tags":2871,"isRecommended":2323},"BAN-B604","Function call with `shell=True` parameter identified","Method calls for the presence of a keyword parameter `shell` equalling true can be vulnerable to [shell injection attacks](https://owasp.org/www-community/attacks/Command_Injection).\nThis issue is intended to catch custom wrappers to vulnerable methods that may have been created.\n\n\u003C!--more-->\nIt is possible for an attacker to craft inputs to issue different commands than the ones you intended such as removing a file.\n\nIt is recommended to use functions that don't spawn a shell. If you must use them, use [`shlex.quote`](https://pypi.org/project/shellescape/) to sanitize the input.\n\n### Bad practice\n```python\ncmd = '/bin/gcc --{}' % version\npop(cmd, shell=True)\n```\n\n### Recommended\n```python\ncmd = '/bin/gcc --{}' % version\npop(cmd)\n```\n\n## References:\n- [Command Injection](https://owasp.org/www-community/attacks/Command_Injection)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-78](https://cwe.mitre.org/data/definitions/78.html)",[1647,2734,1503,1704,1204],{"shortcode":2873,"title":2874,"description":2875,"category":37,"severity":1294,"tags":2876,"isRecommended":2323},"BAN-B702","Use of insecure `mako` templates detected","Mako has no environment wide variable escaping mechanism which leaves application vulnerable to [XSS attacks](https://owasp.org/www-project-top-ten/2017/A7_2017-Cross-Site_Scripting_(XSS).\n\n\u003C!--more-->\nUnlike [Jinja2](https://jinja.palletsprojects.com/en/3.0.x/) (an alternative templating), Mako has no environment wide variable escaping mechanism. Because of this, all input variables must be carefully escaped before use to prevent possible vulnerabilities to Cross Site Scripting (XSS) attacks.\n\n[Autoescaping](https://flask.palletsprojects.com/en/1.1.x/templating/#controlling-autoescaping) is the concept of automatically escaping special characters. Special characters for HTML, XML and XHTMl are &, >, \u003C, \" as well as '. These characters carry specific meanings so need to be replaced by so called `entities` if you want to use them for text. Not doing so makes application susceptible to Cross Site Scripting (XSS) attacks.\n\nIt is recommended to use Jinja2 instead of Mako. When configuring the Jinja2 environment, the option to use autoescaping on input can be specified. When enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables.\n\n### Bad practice\n```python\nfrom mako.template import Template\n\ntemplate = Template(filename=\"mytemplate.html\") # Insecure. Using mako template\n```\n\n### Recommended\n```python\nfrom jinja2 import Environment, PackageLoader, select_autoescape\nenv = Environment(autoescape=True)\n\ntemplate = env.get_template(\"mytemplate.html\")\n```\n\n## References:\n- [Jinja2](https://jinja.palletsprojects.com/en/3.0.x/)\n- [Autoescaping in Jinja](https://jinja.palletsprojects.com/en/2.11.x/api/#autoescaping)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE 79](https://cwe.mitre.org/data/definitions/79.html) - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')",[1647,1503,1362,2374,1704,1204],{"shortcode":2878,"title":2879,"description":2880,"category":37,"severity":1294,"tags":2881,"isRecommended":2323},"PTC-W1005","Use of insecure cipher mode","Use of insecure cipher mode such as `ECB` is not recommended for use in cryptographic protocols because it is [semantically insecure](https://en.wikipedia.org/wiki/Semantic_security).\n\n\u003C!--more-->\nA block cipher uses a symmetric key to encrypt data in groups (blocks) of a pre-determined size (128 bits, 256 bits, etc).\nWhen dealing with data of arbitrary length, the cipher must be combined with a mode of operation.\n\nWhen `ECB` mode is used, a message is divided into blocks. Each block of plaintext is encrypted independently of any other block.\n`ECB` encrypts identical plaintext blocks into identical ciphertext blocks. This is a problem because it will reveal if the same messages blocks are encrypted multiple times.\n\nUsing `ECB` allows an attacker to:\n\n- Detect if two encrypted messages are identical.\n- Detect if a block contains repetitive data.\n- Detect if encrypted messages share a common prefix.\n\nIt is recommended to use any other mode besides `ECB`.\n### Bad practice\n```python\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\ncipher = Cipher(algorithms.AES(key), modes.ECB())\n```\n\n### Recommended\n```python\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\ncipher = Cipher(algorithms.AES(key), modes.CBC(iv))\n```\n\n## References:\n- [ECB mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#ECB)\n- Read more about different cipher modes here -- [https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#module-cryptography.hazmat.primitives.ciphers.modes](https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#module-cryptography.hazmat.primitives.ciphers.modes)\n- Stack overflow - [Why not to use ECB](https://crypto.stackexchange.com/a/20946)\n- OWASP Top 10 2021 Category A02 - [Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [CWE 327](hhttps://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm",[1627,1647,1648,1362,1204],{"shortcode":2883,"title":2884,"description":2885,"category":19,"severity":1294,"tags":2886,"isRecommended":2323},"PYL-W0512","Invalid encoded data","The source line cannot be decoded using the specified source file encoding.\n\nEnsure that the file's encoding is the same as its declared encoding.\n\u003C!--more-->\n### Bad practice\nConsider the code snippet:\n```python\nsome_string = \"Today's temperature is 20°.\"\n```\nIf the file doesn't have an encoding which supports the unicode character °, python will raise an error.\n### Recommended\n```python\n# -*- coding: utf-8 -*-\n\nsome_string = \"Today's temperature is 20 Celsius.\"\n```",[],{"shortcode":2888,"title":2889,"description":2890,"category":19,"severity":1294,"tags":2891,"isRecommended":2323},"PYL-W1508","Invalid `envvar` default","Env manipulation functions return `None` or `str` values. Supplying anything different\nas a default may cause bugs. See https://docs.python.org/3/library/os.html#os.getenv.\n\n\u003C!--more-->\n\n### Bad practice\n\n```python\nimport os\n\nindent = os.getenv(\"INDENT_LEVEL\", default=4)  # 4 is an int, but getenv gives strings\n```\n\n### Recommended\n\n```python\nimport os\n\nindent_str = os.getenv(\"INDENT_LEVEL\", default=\"4\")  # Now it's a string\nindent = int(indent_str)\n```",[],{"shortcode":2893,"title":2894,"description":2895,"category":15,"severity":1294,"tags":2896,"isRecommended":2323},"PTC-W0028","Pythagorean calculation detected with sub-optimal numerics","Calculating the length of the hypotenuse using the standard formula `c = sqrt(a**2 + b**2)` may lead to overflow if the two other sides are both very large.\nEven though `c` will not be much bigger than `max(a, b)`, either `a**2` or `b**2` (or both) could be. Thus, the calculation could overflow, even though the result is well within representable range.\nIt is recommended to use the built-in function `hypot(a,b)` from the `math` library.\n\nExample:\n\n```python\nfrom math import sqrt, hypot\n\na = 3e154 # a^2 > 1e308\nb = 4e154 # b^2 > 1e308\n# with these, c = a^2 + b^2 = 5e154 which is less than 1e308\n\ndef hypotenuseDirect():\n    return sqrt(a**2 + b**2)  # This will give an `OverflowError`\n\ndef hypotenuseBuiltin():\n    return hypot(a, b)  # This will give the expected result, without overflowing\n```",[],{"shortcode":2898,"title":2899,"description":2900,"category":45,"severity":1294,"tags":2901,"isRecommended":2323},"TYP-061","Untyped function called in typed context","Calling an untyped function in a typed context. Please see the issue message for more details.",[],{"shortcode":2903,"title":2904,"description":2905,"category":45,"severity":1294,"tags":2906,"isRecommended":2323},"TYP-052","Unsupported type provided to operand","Type provided to the operand is not supported. See the issue message for more details.",[],{"shortcode":2908,"title":2909,"description":2910,"category":45,"severity":1294,"tags":2911,"isRecommended":2323},"TYP-060","Incompatible types detected","Incompatible types detected. Please see the issue message for details.",[],{"shortcode":2913,"title":2914,"description":2915,"category":45,"severity":1294,"tags":2916,"isRecommended":2323},"TYP-069","Inconsistent number of argument for type alias","Fewer or more number or arguments have been given for a type alias, which makes it invalid.\nPlease see the occurrence message for more details",[],{"shortcode":2918,"title":2919,"description":2920,"category":45,"severity":1294,"tags":2921,"isRecommended":2323},"TYP-059","Use of invalid type detected","Invalid type used. Please see the issue message for details.",[],{"shortcode":2923,"title":2924,"description":2925,"category":45,"severity":1294,"tags":2926,"isRecommended":2323},"TYP-066","Invalid parameter given to `Literal`","Parameter given to `Literal[...]` is not valid. Please see the occurrence message for details.",[],{"shortcode":2928,"title":2929,"description":2930,"category":15,"severity":1294,"tags":2931,"isRecommended":2323},"PTC-W0030","Empty module found","Do not pollute your project with empty files.\nIt is recommended to either delete this file or drop some documentation in it explaining why it is there.",[],{"shortcode":2933,"title":2934,"description":2935,"category":45,"severity":1294,"tags":2936,"isRecommended":2323},"TYP-055","Invalid return detected in callable","The callable shall not return anything and its return type should be `None`.",[],{"shortcode":2938,"title":2939,"description":2940,"category":45,"severity":1294,"tags":2941,"isRecommended":2323},"TYP-043","Invalid type comment or type annotation detected","The type comment or the type annotation is not valid. You can read more about valid type comments [here](//https://www.python.org/dev/peps/pep-0484/#type-comments).",[],{"shortcode":2943,"title":2944,"description":2945,"category":45,"severity":1294,"tags":2946,"isRecommended":2323},"TYP-074","Invalid target for type alias","The type variable used as the target for tupe alias is not valid. Please see the occurrence message for more details.",[],{"shortcode":2948,"title":2949,"description":2950,"category":45,"severity":1294,"tags":2951,"isRecommended":2323},"TYP-070","Type variable is bound by an outer class","The type variable is bound by an outer class. Please see the occurrence message for details.",[],{"shortcode":2953,"title":2954,"description":2955,"category":45,"severity":1294,"tags":2956,"isRecommended":2323},"TYP-018","Invalid use of type variable","Wrong use of `covariant` type variable. See the occurrence message for more context.",[],{"shortcode":2958,"title":2959,"description":2960,"category":45,"severity":1294,"tags":2961,"isRecommended":2323},"TYP-021","Inconsistent use of `type annotation` and `type comment`","[PEP 484](https://www.python.org/dev/peps/pep-0484/) disallows both type annotations and type comments. Please use type annotation for python 3 and type comments for python 2.",[],{"shortcode":2963,"title":2964,"description":2965,"category":45,"severity":1294,"tags":2966,"isRecommended":2323},"TYP-033","Unexpected type definition detected","Type definition is not expected where it is being used. It is recommended to see the issue occurrence to get more details.",[],{"shortcode":2968,"title":2969,"description":2970,"category":45,"severity":1294,"tags":2971,"isRecommended":2323},"TYP-020","Invalid type hint","Invalid type hint was given to keyword argument. See the occurrence message for more details.",[],{"shortcode":2973,"title":2974,"description":2975,"category":45,"severity":1294,"tags":2976,"isRecommended":2323},"TYP-045","Wrong use of `Final` type","Wrong use of `Final[...]`. Final can be only used as an outermost qualifier in a variable annotation. You can read more about using `Final` [here](https://mypy.readthedocs.io/en/latest/final_attrs.html#details-of-using-final).",[],{"shortcode":2978,"title":2979,"description":2980,"category":45,"severity":1294,"tags":2981,"isRecommended":2323},"TYP-065","Type variable is not used in type context","A type variable is only valid in a type context. The way you're using this type variable is not valid.\nPlease see the message occurrence for details.",[],{"shortcode":2983,"title":2984,"description":2985,"category":45,"severity":1294,"tags":2986,"isRecommended":2323},"TYP-067","Invalid number of type parameters detected","Fewer or more number of type parameters are given to a `Type` than what it expects. Please see the occurrence message for details.",[],{"shortcode":2988,"title":2989,"description":2990,"category":45,"severity":1294,"tags":2991,"isRecommended":2323},"TYP-072","Unexpected argument given to type variable","The type variable has been used with unexpected arguments. It is advised to remove them.\nPlease see the occurrence message for details.",[],{"shortcode":2993,"title":2994,"description":2995,"category":15,"severity":1294,"tags":2996,"isRecommended":2323},"PTC-W0027","`f-string` used without any expression","It is wasteful to use `f-string` mechanism if there are no expressions to be extrapolated. It is recommended to use regular strings instead.",[],{"shortcode":2998,"title":2999,"description":3000,"category":45,"severity":1294,"tags":3001,"isRecommended":2323},"TYP-039","`_promote` expects type as first argument","First argument of `_promote` is not a type.",[],{"shortcode":3003,"title":3004,"description":3005,"category":45,"severity":1294,"tags":3006,"isRecommended":2323},"TYP-028","Can not subclass value of type `Any`","Invalid subclass of `Any`. See the occurrence message for more details.",[],{"shortcode":3008,"title":3009,"description":3010,"category":15,"severity":1294,"tags":3011,"isRecommended":2323},"PTC-W0034","Unnecessary use of `getattr`","`getattr` is being used to check if an attribute exists, without specifying a default value.\nMissing a default to `getattr` will cause an `AttributeError` to be raised for non-existent properties, which is the same as when a non-existent property is accessed directly.\nIt is recommended to either provide a default value to be returned by `getattr` if the attribute is not found, or access the attribute directly as there is no additional safety in using `getattr` if the attribute name is known ahead of time.",[],{"shortcode":3013,"title":3014,"description":3015,"category":45,"severity":1294,"tags":3016,"isRecommended":2323},"TYP-022","Missing type parameter","Type parameter is missing in the generic type hint.",[],{"shortcode":3018,"title":3019,"description":3020,"category":45,"severity":1294,"tags":3021,"isRecommended":2323},"TYP-026","Duplicate type variables detected","Duplicate type variables provided. Please see the occurrence messages for more details.",[],{"shortcode":3023,"title":3024,"description":3025,"category":45,"severity":1294,"tags":3026,"isRecommended":2323},"TYP-030","Can not omit type hint in `Final[...]`","Type hint can not be omitted here. See the occurrence message to get more details.\nRead all about `Final` [here](https://mypy.readthedocs.io/en/latest/final_attrs.html).",[],{"shortcode":3028,"title":3029,"description":3030,"category":19,"severity":1294,"tags":3031,"isRecommended":2323},"PTC-W0035","`hasattr` used to check if the object is callable","It is unreliable to use `hasattr(object, '__call__')` to check if an object is callabe as it can give wrong results if `object` implements custom `__getattr__` or its `__call__ ` is itself not callabe. It is recommended to use the `callable` built-in instead.\n\n\u003C!--more-->\nHere's an example:\n\n```bash\nIn [1]: class FooBar:\n    ...:     def __init__(self):\n    ...:         self.foo = \"Foo\"\n    ...:         self.bar = \"Bar\"\n    ...:\n    ...:     def __getattr__(self, key):\n    ...:         return key\n    ...:\n\nIn [2]: instance = FooBar()\n```\n\nWhen `hasattr` is used to check if `instance` is callable, it return `True`\n\n```bash\nIn [3]: hasattr(instance, '__call__')\nOut[3]: True\n```\n\nBut when checked using the `callable` built-in, it returns `False`\n\n```bash\nIn [4]: callable(instance)\nOut[4]: False\n```\n\nWhen `instance` is called, here's the traceback:\n\n```bash\nIn [5]: instance()\n---------------------------------------------------------------------------\nTypeError                                 Traceback (most recent call last)\n\u003Cipython-input-23-5dd8ea036ab8> in \u003Cmodule>\n----> 1 instance()\n\nTypeError: 'FooBar' object is not callable\n```",[],{"shortcode":3033,"title":3034,"description":3035,"category":45,"severity":1294,"tags":3036,"isRecommended":2323},"TYP-027","All type variables should be listed here","If you include `Generic[...]` or `Protocol[...]` in bases, then it should list all type variables present in other bases (or more, if needed). Read more about this [here](https://mypy.readthedocs.io/en/latest/generics.html#defining-sub-classes-of-generic-classes).",[],{"shortcode":3038,"title":3039,"description":3040,"category":45,"severity":1294,"tags":3041,"isRecommended":2323},"TYP-013","Invalid type of decorator constructor","The type of decorated constructor is not valid.",[],{"shortcode":3043,"title":3044,"description":3045,"category":37,"severity":1294,"tags":3046,"isRecommended":2323},"PTC-W1006","Audit required: Sensitive data might be exposed","A potential sensitive data is being exposed in the source code. It can compromise the security of application/user. It is recommended to encrypt this data.\n\u003C!--more-->\nAnyone who has access to the source code can use sensitive data. The source code can be widely shared in an enterprise environment, and is certainly shared in open source. Also hardcoding data makes it difficult to change the password for the operational side.\n\nIt is recommended to put sensitive values either in a separate (uncommitted, gitignored) configuration file, or pull them in from environment variables. The first is easier if you're self-hosting; the latter is the norm if you use e.g. Heroku or similar platform that deploys from a repository.\n\n### Bad practice\n```python\nusername = \"james\"\ntoken = \"auenfejadldadjakf\"\n```\n\n### Recommended\n```python\nimport os\n\nusername = os.getenv(\"username\")\ntoken = os.environ.get(\"secret_key\", \"default_key\")  # getting value from env variable. No issue.\n```\n# References:\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-798](https://cwe.mitre.org/data/definitions/798.html) - Use of Hard-coded Credentials",[1647,1203,3047,1704,1204],"cwe-798",{"shortcode":3049,"title":3050,"description":3051,"category":19,"severity":1294,"tags":3052,"isRecommended":2323},"PTC-W0031","Use of a method on dictionary's `get` method detected","Use of a method on the return value of a dictionary's `get` method without checking if the value exists may give an `AttributeError` during runtime.\nBy default, the `get` method returns `None` if the key is not found in the dictionary.\n\nIt is recommended to either provide a `default` value to be returned by `get` when key doesn't exist, or check that the default value is not `None` before using any other method on it.\n\u003C!--more-->\n\n### Bad practice\n```python\ndef generate_username(name):\n    return student_record.get(name).lower()\n```\n\n### Recommended\n```python\ndef generate_username(name):\n    official_name = student_record.get(name)\n    return official_name.lower() if official_name else None\n```",[],{"shortcode":3054,"title":3055,"description":3056,"category":15,"severity":1294,"tags":3057,"isRecommended":2323},"PYL-R1709","Simplify boolean expression","The boolean expression with redundant pre-python 2.5 ternary syntax is used and can be simplified for better readability.\nPlease look at the issue text for suggestion.\n\n#### Not preferred:\n```python\nSOME_VALUE = condition and False or some_value\n```\n\n#### Preferred:\n```python\nSOME_VALUE = some_value\n```",[],{"shortcode":3059,"title":3060,"description":3061,"category":15,"severity":1294,"tags":3062,"isRecommended":2323},"PTC-W0042","Consider using `max` builtin","It is unnecessary to use an `if` statement to check the maximum of two values and then assign the value to a name.\nYou can use the `max` built-in do do this. It is straightforward and more readable.\n\nNot preferred:\n```python\nif value \u003C= 10:\n    value = 10\n```\n\nPreferred:\n```python\nvalue = max(value, 10)\n```",[],{"shortcode":3064,"title":3065,"description":3066,"category":15,"severity":1294,"tags":3067,"isRecommended":2323},"PTC-W0041","Consider using `min` builtin","It is unnecessary to use an `if` statement to check the minimum of two values and then assign the value to a name.\nYou can use the `min` built-in do do this. It is straightforward and more readable.\n\nNot preferred:\n```python\nif value >= 10:\n    value = 10\n```\n\nPreferred:\n```python\nvalue = min(value, 10)\n```",[],{"shortcode":3069,"title":3070,"description":3071,"category":15,"severity":1294,"tags":3072,"isRecommended":2323},"PYL-W1301","Format string contains unused key","Format string is using named conversion specifiers is being used with a dictionary that contains keys not required by the format string.\nIt is recommend to remove the unused keys.\n\n\u003C!--more-->\n#### Not preferred:\n```python\ndef greet_user(user):\n    print(\n        \"Hi %(name)s!. Welcome to %(location)s.\"\n        % {\"name\": user.first_name, \"location\": user.updated_loc, \"age\": user.age}\n    )\n```\nHere, the key `age` is nowhere used in the format string and should be removed.\n\n#### Preferred:\n```python\ndef greet_user(user):\n    print(\n        \"Hi %(name)s!. Welcome to %(location)s.\"\n        % {\"name\": user.first_name, \"location\": user.updated_loc}\n    )\n```",[],{"shortcode":3074,"title":3075,"description":3076,"category":19,"severity":1294,"tags":3077,"isRecommended":2323},"PTC-W0040","Using deprecated method `assertEquals`","`assertEquals` has been deprecated. Use the standardized ``assertEqual`` instead.\n\n\u003C!--more-->\n### Bad practice\n```python\nimport unittest\n\nclass Tests(unittest.TestCase):\n    def test_something(self, arg1, arg2):\n        self.assertEquals(arg1, arg2)\n```\n\n### Recommended\n```python\nimport unittest\n\nclass Tests(unittest.TestCase):\n    def test_something(self, arg1, arg2):\n        self.assertEqual(arg1, arg2)\n```\n\n## References\n- [Deprecated Aliases](https://docs.python.org/2/library/unittest.html#deprecated-aliases)\n- [Issue 9424 in Python](https://bugs.python.org/issue9424)",[],{"shortcode":3079,"title":3080,"description":3081,"category":15,"severity":1294,"tags":3082,"isRecommended":2323},"PYL-W1503","Constant passed to unittest `assert\u003CBool>`","The first argument of `assertTrue` and `assertFalse` should be a condition.\nIf a constant is passed as a parameter, the condition will be always `True`, making the test meaningless.\n\n\u003C!--more-->\n### Bad practice\n```python\nimport unittest\n\n\nclass Tests(unittest.TestCase):\n    def test_something(self):\n        ''' Some test '''\n        self.assertTrue('My String')\n```\n\n### Recommended\n```python\nimport unittest\n\n\nclass Tests(unittest.TestCase):\n    def test_something(self):\n        ''' Simple test '''\n        string = 'My String'\n        self.assertTrue('My String' == string)\n```\n\nYou also might accidentally use `assertTrue` instead of `assertEqual`, which also causes this issue to be raised.\n\n#### Incorrect:\n```python\nimport unittest\n\n\nclass Tests(unittest.TestCase):\n    def test_something(self):\n        ''' Simple test '''\n        some_var = 'It should be assertEqual'\n        self.assertTrue('I meant assertEqual not assertTrue', some_var)\n```\n\n#### Correct:\n```python\nimport unittest\n\n\nclass Tests(unittest.TestCase):\n    def test_something(self):\n        ''' Simple test '''\n        some_var = 'It should be assertEqual'\n        self.assertEqual('I meant assertEqual not assertTrue', some_var)\n```",[],{"shortcode":3084,"title":3085,"description":3086,"category":31,"severity":1294,"tags":3087,"isRecommended":2323},"PTC-W0044","Use of `len(seq) - 1` to get last element of an iterable","There’s no need to calculate length of an iterable in order to fetch the last element of the iterable.\nYou can provide a negative index `-1` to it directly in orger to get the last element.\nIn this way, you don't have to iterate over the sequence using `len` to get the last index when your purpose is only to get the last element.\n\nNot performant code:\n```python\nlast_element = some_sequence[len(some_sequence) - 1]\n```\n\nPerformant Code:\n```python\nlast_element = some_sequence[-1]\n```",[],{"shortcode":3089,"title":3090,"description":3091,"category":15,"severity":1294,"tags":3092,"isRecommended":2323},"PTC-W0043","Unnecessary `delete` statement in a local scope","Passing a local variable to a `del` statement results in that variable being removed from the local namespace.\nWhen exiting a function all local variables are deleted, so it is unnecessary to explicitly delete variables in such cases.\n\nIt is recommended to remove this `del` statement.\n\nNot preferred:\n```python\ndef my_func():\n    task = do_some_task()\n    evaluate_task(task)\n    del task  # This is unnecessary.\n```\n\nPreferred:\n```python\ndef my_func():\n    task = do_some_task()\n    evaluate_task(task)\n```",[],{"shortcode":3094,"title":3095,"description":3096,"category":19,"severity":1294,"tags":3097,"isRecommended":2323},"PTC-W0903","Admin class not in app's `admin.py`","Admin classes not in an app's `admin.py` can cause circular import problems throughout a project.\nThis is because registering an admin class implies a call to `models.get_apps()` which attempts to import *every* `models.py` in the project.\n\nWhilst your project should probably not have significant inter-app dependencies, importing every possible models.py does not help the situation and can cause `ImportError` when models are loaded in different scenarios.\n\nRegistering admin classes in `admin.py` is standard practice of django developers. It is recommended to have predictable project structure and follow common patterns. This simplifies maintenance of a codebase.",[2539],{"shortcode":3099,"title":3100,"description":3101,"category":15,"severity":1294,"tags":3102,"isRecommended":2323},"PTC-W0053","Abstract method does not raise `NotImplementedError`","Abstract methods should raise `NotImplementeError` when they require derived classes\nto override the method, or while the class is being developed to indicate that\nthe real implementation still needs to be added.\n\nRefer to the [docs](https://docs.python.org/3/library/exceptions.html#NotImplementedError)\nto read more about `NotImplementedError`.\n\n### Not preferred:\n```python\nimport abc\n\nclass Vehicle:\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def method_to_implement(self, input):\n        return\n```\n\n### Preferred:\n```python\nimport abc\n\nclass Vehicle:\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def method_to_implement(self, input):\n        raise NotImplementedError\n```",[],{"shortcode":3104,"title":3105,"description":3106,"category":15,"severity":1294,"tags":3107,"isRecommended":2323},"PTC-W0904","Consider using `TextField` instead of `CharField`","`CharField` highlighted in the issue has a `max_length` > 256.\nIt is recommended to use `TextField` for such long fields. `CharField` should only be used for smaller strings.\n\nReasons to fix this:\n\n- More readable and maintainable. Any developer reading the code in the future doesn't have to wonder about the specific `max_length`.\n- If for some reason, the current `max_length` needs to be increased, you'd need to create a new database migration to facilitate this change.\n\n#### Not Preferred:\n```python\nclass MyModel(models.Model):\n    my_field = models.CharField(max_length=1000)\n```\n\n#### Preffered:\n```python\nclass MyModel(models.Model):\n    my_field = models.TextField()\n```",[],{"shortcode":3109,"title":3110,"description":3111,"category":15,"severity":1294,"tags":3112,"isRecommended":2323},"PTC-W0046","Unit test class with no tests","Test methods should always start with the `test`. If there are no such methods,\nthe class overriding `unittest.TestCase` won't run any test.\n\nNot preferred:\n```python\nimport unittest\n\ndef Tests(unittest.TestCase):\n    def my_test(self, arg1, arg2):\n        self.assertEquals(arg1, arg2)\n```\n\nPreferred:\n```python\nimport unittest\n\ndef Tests(unittest.TestCase):\n    def test_something(self, arg1, arg2):\n        self.assertEquals(arg1, arg2)\n```",[],{"shortcode":3114,"title":3115,"description":3116,"category":15,"severity":1294,"tags":3117,"isRecommended":2323},"PTC-W0051","Branches of the `if` statement have similar implementation","For the highlighted `if` statements, all the `elif` / `else` branches have the same body as `if`.\nIt is recommended to refactor this snippet.\n\nIf the if-chain is performing the same action in every case, it shouldn't be used there at all.\n\n### Not preferred:\n```python\nif b == 0:\n    do_something()\nelif b == 1:\n    do_something()\nelse:\n    do_something()\n\nb = 4 if a > 12 else 4\n```\n\n### Preferred:\n```python\n# If this is was a copy-paste error, review and update the snippet\nif b == 0:\n    do_something()\nelif b == 1:\n    do_something_else()\nelse:\n    do_other_thing()\n\nb = -4 if a > 12 else 4\n\n# OR\n# Refactor the code to not use the if-chain at all.\ndo_something()\n\nb = 4\n```",[],{"shortcode":3119,"title":3120,"description":3121,"category":15,"severity":1294,"tags":3122,"isRecommended":2323},"PTC-W0901","String field is nullable","The `null` attribute specifies that the field can be `None`, or `null` at database level.\nThis makes the ORM queries and the Python code more complex because the values will sometime be `None` and other times, a `string`.\nHence, you'd need extra code to check on performing string operations on a `NoneType`.\n\nIt is recommended to provide a `default=''` option to the fields instead.\nThis way, you wonn't have to worry about null values and the database would also throw an exception if there is an attempt to explicitly save `None`.\n\n#### Not Preferred:\n```python\nclass Customer(models.Model):\n    remarks = models.CharField(null=True)\n\nquery = Q(remarks__isnull=True) | Q(remarks='')\nfor customer in Customer.objects.filter(query):\n    ...\n```\n\n#### Preferred:\n```python\nclass Customer(models.Model):\n    remarks = models.CharField(default='')\n\nfor customer in Customer.objects.filter(remarks=''):\n    # customer.remarks is always a str\n    ...\n```",[],{"shortcode":3124,"title":3125,"description":3126,"category":15,"severity":1294,"tags":3127,"isRecommended":2323},"PTC-W0050","Set declaration has duplicate elements","A set cannot have two identical values. When a value is repeated in a set literal,\nonly the last occurrence will remain. Thus duplicate values should be either modified or removed.\nIf duplicate elements are needed, that is, multiset, use `Counter` from `collections` module.\n\n### Not preferred:\n```python\nmy_set = {\"one\", \"two\", \"one\"}\n\ndef myfunc(a, b, c):\n    my_set = {a, b, a, c}\n```\n\n### Preferred:\n```python\nmy_set = {\"one\", \"two\", \"one\"}\n\ndef myfunc(a, b, c):\n    my_set = {a, b, c}\n```",[],{"shortcode":3129,"title":3130,"description":3131,"category":37,"severity":1294,"tags":3132,"isRecommended":2323},"PTC-W6002","Audit required: Server hostname may not be verified","It is recommended to validate server certificate's hostname specific data with the server hostname during SSL/TLS sessions to protect it from man-in-the-middle attacks.\n\nIn the highlighted code, the hostname validation is not enabled by default and it needs to be turned on.\nPlease see the occurrence message for details.\n\n### Not preferred:\n```python\nimport ssl\n\ncontext = ssl._create_stdlib_context()  # by default hostname verification is not done\n```\n\n### Preferred:\n```python\nimport ssl\n\ncontext = ssl._create_stdlib_context()\ncontext.check_hostname = True  # Explicitly set `check_hostname` to True\n```\n\n### References\n- [OWASP Top Ten 2021 Category A07:2021 - Identification and Authentication Failures](https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/)\n- [CWE-297](https://cwe.mitre.org/data/definitions/297.html)",[1204,3133,1647,1729],"cwe-297",{"shortcode":3135,"title":3136,"description":3137,"category":15,"severity":1294,"tags":3138,"isRecommended":2323},"PTC-W0049","Function/method with an empty body","The function/method has been left empty here, without any comment or docstring.\nThis can cause confusion later on why this was left empty.\n\n- If it is intentionally left blank, a nested comment should explain the reason why it is being done.\n- If this is not yet, or never will be, supported, an exception should be thrown rather than leaving it blank.\n\n### Not preferred:\n```python\ndef myfunc1(foo=\"Noncompliant\"):\n    pass\n\nclass MyClass:\n    def mymethod1(self, foo=\"Noncompliant\"):\n        pass\n```\n\n### Preferred:\n```python\ndef myfunc1():\n    pass  # comment explaining why this function is empty\n\ndef myfunc2():\n    raise NotImplementedError()\n\ndef myfunc3():\n    '''\n    Docstring explaining why this function is empty.\n    '''\n\nclass MyClass:\n    def mymethod1(self):\n        pass  # comment explaining why this function is empty\n\n    def mymethod2(self):\n        raise NotImplementedError()\n\n    def mymethod3(self):\n        '''\n        Docstring explaining why this method is empty. Note that this is not recommended for classes\n        which are meant to be subclassed.\n        '''\n```",[],{"shortcode":3140,"title":3141,"description":3142,"category":15,"severity":1294,"tags":3143,"isRecommended":2323},"PTC-W0906","Field allows null but not blank","If `null` is `True` and `blank` is `False` then Django and the database disagree on whether empty values are allowed.\n\nThe `null` attribute specifies that the database will accept it if no value is passed to the field. The `blank` attribute specifies Django should not check if the value is present when `Model.clean` is called.\n\nIf `Model.save` is called via the shell without first calling `Model.clean`: the bad data will be saved and there may be unwanted side effects, such as:\n\n- Complex ORM queries\n- Validation error if the records are validated the next time\n- Inconsistent datatypes\n\nThese unwanted side effects can cause more serious problems that are hard to debug long after the original error occurred.\n\n### Not preferred:\n```python\nclass Feedback(models.Model):\n    created = models.DateField(null=True)\n    updated = models.DateField(null=True, blank=False)\n```\n\n### Preferred:\n```python\nclass Feedback(models.Model):\n    created = models.DateField(null=True, blank=True)\n    updated = models.DateField(null=True, blank=True)\n```",[],{"shortcode":3145,"title":3146,"description":3147,"category":15,"severity":1294,"tags":3148,"isRecommended":2323},"PTC-W0054","Special method should return `NotImplemented`","Special methods corresponding to numeric operators, rich comparison operators, and the `__length_hint__` method should return `NotImplemented` when the operation is not supported.\nThese methods should not raise `NotImplementedError` as callers don't expect it and won't catch this exception.\n\nFor example, `A + B` is equivalent to calling `A.__add__(B)`.\nIf this binary operation is not supported by the class `A`, `A.__add__(B)` should return `NotImplemented`. \nThe interpreter will then try the reverse operation, i.e. `B.__radd__(A)`.\nThis enables adding new operations by changing only one class instead of two.\n\nFor further reading, check these:\n\n- Python documentation - [Built-in Constants - NotImplemented](https://docs.python.org/3/library/constants.html#NotImplemented)\n- Python documentation - [Implementing the arithmetic operations](https://docs.python.org/3/library/numbers.html#implementing-the-arithmetic-operations)\n\n### Not preferred:\n```python\nclass A:\n    def __init__(self, val): \n        self.val = val \n    \n    def __add__(self, other): \n        raise NotImplementedError\n         \nclass B: \n    def __init__(self, val): \n        self.val = val \n        \n    def __add__(self, other): \n        return self.val + other.val \n     \n    def __radd__(self, other): \n        return self.val + other.val\n                \nA(1) + B(1)  # This will raise `NotImplementedError`\n```\n\n### Preferred:\n```python\nclass A:\n    def __init__(self, val): \n        self.val = val \n    \n    def __add__(self, other): \n        return NotImplemented\n         \nclass B: \n    def __init__(self, val): \n        self.val = val \n        \n    def __add__(self, other): \n        return self.val + other.val \n     \n    def __radd__(self, other): \n        return self.val + other.val\n\nA(1) + B(1)  # This will return 2 \n```",[],{"shortcode":3150,"title":3151,"description":3152,"category":37,"severity":1294,"tags":3153,"isRecommended":2323},"PTC-W6001","Audit required: Server certificate may not be verified","It is recommended to validate server certificate during SSL/TLS sessions to protect it from man-in-the-middle attacks.\n\nThe certificate chain validation takes care of the following things:\n\n- The certificate is issued by its parent Certificate Authority or the root CA trusted by the system.\n- Each CA is allowed to issue certificates.\n- Each certificate in the chain is not expired.\n\n### Not preferred:\n```python\nimport ssl\n\ncontext = ssl.create_default_context()\nctx3.verify_mode = ssl.CERT_NONE  # Setting this won't verify the certificate\n```\n\n\n### Preferred:\n```python\nimport ssl\n\ncontext = ssl.create_default_context()\nctx3.verify_mode = ssl.CERT_REQUIRED\n```\n### References\n- [OWASP Top Ten 2021 Category A07:2021 - Identification and Authentication Failures](https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/)\n- [CWE-295](https://cwe.mitre.org/data/definitions/295.html)",[1204,1647,1740,1729],{"shortcode":3155,"title":3156,"description":3157,"category":15,"severity":1294,"tags":3158,"isRecommended":2323},"PTC-W0047","Empty block of code found","In most cases, an empty body of `for`, `while` or `if` implies some piece of code is missing.\nSuch empty block must be either filled or removed.\n\n\u003C!--more-->\n### Bad practice\n```python\nfor i in range(10):\n    pass\n```\n\n### Preferred:\n```python\nfor i in range(10):\n    print(i)\n```",[],{"shortcode":3160,"title":3161,"description":3162,"category":19,"severity":1294,"tags":3163,"isRecommended":2323},"PTC-W0045","Bad async magic method","Magic methods that are not supposed to be asynchronous would not work as expected if they are made `async`.\nIt is recommend to not make this magic method `async`.\n\n\u003C!--more-->\nFollwing magic methods should not asynchronous:\n\n- `__lshift__`\n- `__bytes__`\n- `__new__`\n- `__del__`\n- `__abs__`\n- `__eq__`\n- `__trunc__`\n- `__truediv__`\n- `__exit__`\n- `__getattr__`\n- `__repr__`\n- `__gt__`\n- `__and__`\n- `__dir__`\n- `__ifloordiv__`\n- `__rand__`\n- `__pow__`\n- `__set_name__`\n- `__format__`\n- `__rtruediv__`\n- `__complex__`\n- `__getitem__`\n- `__init_subclass__`\n- `__get__`\n- `__await__`\n- `__sub__`\n- `__ne__`\n- `__or__`\n- `__rmul__`\n- `__rxor__`\n- `__mod__`\n- `__rmod__`\n- `__subclasscheck__`\n- `__pos__`\n- `__int__`\n- `__round__`\n- `__add__`\n- `__ixor__`\n- `__mul__`\n- `__ipow__`\n- `__itruediv__`\n- `__missing__`\n- `__lt__`\n- `__hash__`\n- `__instancecheck__`\n- `__ror__`\n- `__aiter__`\n- `__xor__`\n- `__imul__`\n- `__delete__`\n- `__delitem__`\n- `__setitem__`\n- `__divmod__`\n- `__invert__`\n- `__contains__`\n- `__rpow__`\n- `__floor__`\n- `__len__`\n- `__iand__`\n- `__class_getitem__`\n- `__floordiv__`\n- `__setattr__`\n- `__enter__`\n- `__irshift__`\n- `__le__`\n- `__ilshift__`\n- `__init__`\n- `__rmatmul__`\n- `__rdivmod__`\n- `__radd__`\n- `__imod__`\n- `__iter__`\n- `__delattr__`\n- `__bool__`\n- `__length_hint__`\n- `__reversed__`\n- `__getattribute__`\n- `__isub__`\n- `__imatmul__`\n- `__rsub__`\n- `__rrshift__`\n- `__matmul__`\n- `__float__`\n- `__neg__`\n- `__str__`\n- `__rfloordiv__`\n- `__index__`\n- `__rlshift__`\n- `__ge__`\n- `__ior__`\n- `__iadd__`\n- `__rshift__`\n- `__set__`\n- `__ceil__`\n\n### Bad practice\n```python\nclass BadClass:\n    async def __lt__(self, other):\n        ...\n```\n\n### Recommended\n```python\nclass GoodClass:\n    def __lt__(self, other):\n        ...\n```",[],{"shortcode":3165,"title":3166,"description":3167,"category":15,"severity":1294,"tags":3168,"isRecommended":2323},"PTC-W0048","`if` statements can be merged","Nested `if` statements can be collapsed into a single `if` statement by separating their condition using `and` operator.\nMerging collapsible `if` statements increases the code's readability.\n\n\u003C!--more-->\n### Bad practice\n```python\nif condition1:\n    if condition2:\n        dosomething()\n```\n\n### Preferred\n```python\nif condition1 and condition2:\n    dosomething()\n```\n\n### Exception:\n\nDeepSource will not raise this issue when the nested `if` statements have comments in between them, as it could be explaining why the nested `if` is in place.",[],{"shortcode":3170,"title":3171,"description":3172,"category":15,"severity":1294,"tags":3173,"isRecommended":2323},"PTC-W0062","`with` statements can be merged","Nested `with` statements can be merged into a single compound `with` statement.\n\nThis issue is raised only when there are no other statements between the nested `with` statements.\nMerging collapsible `with` statements can decrease cognitive complexity, improving code readability.\n\n\u003C!--more-->\n### Bad practice\n```python\nwith open(\"file1\", \"w\") as file1:\n    with open(\"file2\", \"w\") as file2:\n        doSomething()\n```\n\n### Preferred\n```python\nwith open(\"file1\", \"w\") as file1, open(\"file2\", \"w\") as file2:\n    doSomething()\n```",[],{"shortcode":3175,"title":3176,"description":3177,"category":15,"severity":1294,"tags":3178,"isRecommended":2323},"PTC-W0065","Unused nested function or class detected","This issue concerns that one or more nested classes/functions have been declared but are nowhere used in the function.\n\n \u003C!--more-->\nA class or function defined inside a function is only accessible inside its parent function scope.\nIt is recommended either to remove the unused classes and functions as it is a dead code or refactor it to use them.\n\n**Note: DeepSource will remove all the unused nested definitions during Autofix.**\n\n### Bad practice\n```python\ndef run():\n    def total_time():\n        return Something\n\n    class Runner:\n        def __init__(time):\n            pass\n```\n\n### Preferred\n```python\ndef run():\n    def total_time():\n        return Something\n\n    class Runner:\n        def __init__(time):\n            ...\n\n    t = total_time()\n    bill = Runner(t)\n    ...\n```",[],{"shortcode":3180,"title":3181,"description":3182,"category":19,"severity":1294,"tags":3183,"isRecommended":2323},"PTC-W0900","Use of deprecated `NullBooleanField`","`NullBooleanField` is deprecated in favor of `BooleanField(null=True)` since Django 3.1 and has been removed in Django 3.2.\nIt is recommended to replace it with `BooleanField` with `null=True`\n\n\u003C!--more-->\n### Bad practice\n```python\nclass MyModel(models.Model):\n    my_field = models.NullBooleanField()\n```\n\n### Recommended\n```python\nclass MyModel(models.Model):\n    my_field = models.BooleanField(null=True)\n```",[2539],{"shortcode":3185,"title":3186,"description":3187,"category":19,"severity":1294,"tags":3188,"isRecommended":2323},"PTC-W0902","Primary key is not unique","Values in field which is used as primary key should be unique.\n\n\u003C!--more-->\nA primary key is used to uniquely identify each record in the Model's database table.\n\nA non-unique primary key allows the same value to be used for multiple records.\nTherefore, multiple objects can exist with the same primary key, which might not be something that was intended.\n\nThe kwarg `primary_key=True` denotes that the field is a primary key for the model.\nIt implicitly means `null=False` and `unique=True`.\n\nProviding `unique=False` is not recommended.\n\n### Bad practice\n```python\nclass MyModel(models.Model):\n    my_field = models.CharField(\n        primary_key=True,\n        unique=False\n    )\n```\n\n### Recommended\n```python\nclass MyModel(models.Model):\n    my_field = models.CharField(primary_key=True)\n```",[2539],{"shortcode":3190,"title":3191,"description":3192,"category":19,"severity":1294,"tags":3193,"isRecommended":2323},"PTC-W0905","Nullable `ManyToManyField` found","Having a nullable many-to-many field doesn't do anything. The declaration of a `ManyToManyField` causes the creation of an intermediate table to hold the relationship. Each relation between the two tables is an entry in this new table. By definition, having no relations between two tables would mean no entries in this table. There's no use of `null`.\n\nConsider removing `null=True` from this property.\n\n#### Not Preferred:\n```python\nclass User(models.Model):\n    chat_id = models.ManyToManyField(null=True)\n```\n\n#### Preffered:\n```python\nclass User(models.Model):\n    chat_id = models.ManyToManyField()\n```",[],{"shortcode":3195,"title":3196,"description":3197,"category":19,"severity":1294,"tags":3198,"isRecommended":2323},"PYL-E1605","Backticks are deprecated, use `repr()`","Backticks were deprecated and removed in Python 3. Use the built-in function `repr()` instead.\n\n\u003C!--more-->\nThe backtick(`) operator in Python 2 is used to convert the contained expression into a string.\nThe operator was removed in Python 3 as it is confusingly similar to a single quote, and hard to type on some keyboards.\nInstead of the backtick, use the equivalent built-in function `repr()`.\n`repr()` returns a string that holds a printable representation of an object.\n\nAnother alternative is to use `!r` inside an f-string: `repr(x)` is the same as `f'{x!r}'.\n\n### Bad practice\n```python\nobj = MyObj()\nprint(`obj`)\n```\n### Recommended\n```python\nobj = MyObj()\nprint(repr(obj))\nprint(f'{obj!r}')\n```",[],{"shortcode":3200,"title":3201,"description":3202,"category":19,"severity":1294,"tags":3203,"isRecommended":2323},"PTC-W0910","Missing backward migration","`RunPython` operation is missing `reverse_code` argument. If not provided, any attempt to undo the migration will raise `IrreversibleError`.\n\u003C!--more-->\nFailure to reverse migrations will prevent going back to a previous state of the database if needed. Therefore, it is recommended to always include a backward/reverse callable so that the migration is reversible.\n\nIt is highly recommended to provide a function to the `reverse_code` parameter that undoes the migration.\nIf it is safe to skip the migration to go to a previous state, you can specify `RunPython.noop` as a value. This will prevent Django from raising `IrreversibleError`.\n### Bad practice\n```python\nfrom django.db import migrations\n\n\ndef update_marks(apps, schema_editor):\n    pass\n\nclass Migration(migrations.Migration):\n    dependencies = [(\"0002_field_with_default_value\", \"0001_no_issue\")]\n    operations = [\n        migrations.RunPython(update_marks), # Issue\n    ]\n```\n\n### Preferred\n```python\nfrom django.db import migrations\n\n\ndef update_marks(apps, schema_editor):\n    pass\n\nclass Migration(migrations.Migration):\n    dependencies = [(\"0002_field_with_default_value\", \"0001_no_issue\")]\n    operations = [\n        migrations.RunPython(update_marks, reverse_code=migrations.RunPython.noop),\n    ]\n```\n# References\n- [RunPython](https://docs.djangoproject.com/en/3.2/ref/migration-operations/#runpython)\n- [Reversing Migrations](https://docs.djangoproject.com/en/3.2/topics/migrations/#reversing-migrations)",[],{"shortcode":3205,"title":3206,"description":3207,"category":37,"severity":1294,"tags":3208,"isRecommended":2323},"PY-S6007","Use of both safe and unsafe HTTP methods for a view","An HTTP method is safe if it doesn't alter the state of the server i.e it leads to a read-only operation.\nCommon safe HTTP methods: `GET`, `HEAD`, and `OPTIONS`.\nWhereas, `POST`, `PUT`, and `DELETE` are unsafe because they alter the server state.\n\nThe use of both safe and unsafe HTTP methods on a view makes the application vulnerable to Cross-Site Request Forgery (CSRF). CSRF protections are responsible for protecting operations performed by unsafe HTTP methods. They do not protect if safe HTTP methods used for a route that can change the state of an application.\n\nIt is recommended to use safe HTTP methods only when read-only operations need to be performed. Don't use safe and unsafe methods together. \n\n\u003C!--more-->\n### Bad practice\nFor Django:\n```python\nfrom django.views.decorators.http import require_http_methods\n\n@require_http_methods([\"GET\", \"POST\"]) # Sensitive\ndef register(request):\n    ...\n```\n\nFor Flask:\n```python\nimport flask\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/sensitive', methods=['GET', 'POST'])  # Sensitive\ndef register():\n    ...\n```\n\n### Recommended\nFor Django\n```python\nfrom django.views.decorators.http import require_POST, require_GET\n\n@require_POST\ndef register(request):\n    ...\n\n@require_GET\ndef post(request):\n    ...\n```\n\nFor Flask\n```python\nimport flask\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/sensitive', methods=['POST'])  # Sensitive\ndef register():\n    ...\n\n@app.route('/sensitive', methods=['GET'])  # Sensitive\ndef hello_world():\n    return \"Hello World\"\n```\n\n## References:\n- OWASP Top 10 2021 Category A04 - [Insecure Design](https://owasp.org/Top10/A04_2021-Insecure_Design/)\n- [SANS 25](https://www.sans.org/blog/top-25-series-rank-4-cross-site-request-forgery/)\n- [CWE-352](https://cwe.mitre.org/data/definitions/352.html)\n- [Cross Site Request Forgery](https://owasp.org/www-community/attacks/csrf)",[1361,1647,3209,1704,1204],"cwe-352",{"shortcode":3211,"title":3212,"description":3213,"category":37,"severity":1294,"tags":3214,"isRecommended":2323},"PY-S6008","Setting loose POSIX file permissions is security-sensitive","Every file in the POSIX file system has the following permissions:\n- Owner permissions - Determines what actions the owner of the file can perform on the file.\n- Group permissions - Determines what actions a user who is a member of the group that a file belongs to can perform on the file.\n- Other permissions − Determines what action all other users can perform on the file.\n\nGranting permissions to `others` can lead to unintended access and modification to files. It is recommended to assign most restrictive permissions to files and directories.\n\nOne should avoid using following modes for a file unless necessary:\n- [stat.S_IRWXO](https://docs.python.org/3/library/stat.html#stat.S_IRWXO) - Grants read and write permission to Other group.\n- [stat.S_IWOTH](https://docs.python.org/3/library/stat.html#stat.S_IWOTH) - Grants write permission to Other group.\n- [stat.S_IXOTH](https://docs.python.org/3/library/stat.html#stat.S_IXOTH) - Grants execute permission to Other group.\n\nRefer to the references to learn about other modes for files.\n\n\u003C!--more-->\n\n### Bad practice\n```python\nimport os, stat\n\nr = os.umask(0) # read, write permission granted to others\nos.umask(2)\n\nos.chmod(\"/home/some_fle\", stat.S_IRWXO)   # Others have read and write permission\nos.lchmod(\"/home/some_file\", stat.S_IRWXO)  # Others have read and write permission\nos.fchmod(f, stat.S_IWOTH) # Others have write permission\n```\n\n### Recommended\n```python\nimport os, stat\n\nr = os.umask(0o027) # Others do not have read or write permission\nos.umask(2)\n\nos.chmod(\"/home/some_fle\", stat.S_IRWXG)\nos.lchmod(\"/home/some_file\", stat.S_IRWXU)\nos.fchmod(f, stat.S_IRWXG)\n```\n\n## References:\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- [os.umask](https://docs.python.org/3/library/os.html#os.umask)\n- [Guide to set umask value](https://docs.oracle.com/cd/E19683-01/817-3814/userconcept-95347/index.html)\n- [Possible modes for files](https://docs.python.org/3/library/os.html#os.chmod)",[1203,1204],{"shortcode":3216,"title":3217,"description":3218,"category":37,"severity":1294,"tags":3219,"isRecommended":2323},"PY-S0901","Insecure use of `format_html` detected","Django's `format_html()` function can be used to safely insert untrusted user data into HTML.\n\nHowever, passing an already formatting string to `format_html()` has no effect on the inputted string, and may be a security issue. This may expose [cross-site scripting (XSS)](https://owasp.org/www-project-top-ten/2017/A7_2017-Cross-Site_Scripting_(XSS)) vulnerabilities.\n\n### Bad practice\n\n```python\nformat_html(f\"\u003Cb>{user_input}\u003C/b>\")  # `user_input` is not being sanitized!\n```\n\n### Recommended\n```python\nformat_html(\"\u003Cb>{}\u003C/b>\", user_input)  # This can safely be used.\n```\n\n## References:\n- [`format_html`](https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [CWE 79](https://cwe.mitre.org/data/definitions/79.html) - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')",[1647,2374,1503,1704,1204],{"shortcode":3221,"title":3222,"description":3223,"category":19,"severity":1294,"tags":3224,"isRecommended":2323},"PYL-E1608","Use of old octal literal","Old octal syntax is being used. This has been removed in Python 3, and will raise an error.\nTo use the new syntax, prepend `0o` to the number.\n\n\u003C!--more-->\n### Bad practice\nIn Python 2\n```python\nmy_var = 011 # This represents 8 in decimal\n```\n### Recommended\n```python\nmy_var = 0o11 # This represents 8 in decimal\n```",[],{"shortcode":3226,"title":3227,"description":3228,"category":19,"severity":1294,"tags":3229,"isRecommended":2323},"PYL-W1649","Use of deprecated `string` function detected","The `string` function you're trying to access has been deprecated in Python 3.\nPlease consult the documentation [here](https://docs.python.org/3/library/string.html).\n\u003C!--more-->\nThe issue is raised for the following functions from the `string` module, that have been removed in the latest version of Python.\n\n- `maketrans`\n- `atof`\n- `atoi`\n- `atol`\n- `capitalize`\n- `expandtabs`\n- `find`\n- `rfind`\n- `index`\n- `rindex`\n- `count`\n- `lower`\n- `letters`\n- `split`\n- `rsplit`\n- `splitfields`\n- `join`\n- `joinfields`\n- `lstrip`\n- `rstrip`\n- `strip`\n- `swapcase`\n- `translate`\n- `upper`\n- `ljust`\n- `rjust`\n- `center`\n- `zfill`\n- `replace`\n- `lowercase`\n- `letters`\n- `uppercase`\n- `atol_error`\n- `atof_error`\n- `atoi_error`\n- `index_error`",[],{"shortcode":3231,"title":3232,"description":3233,"category":37,"severity":1294,"tags":3234,"isRecommended":2323},"BAN-B302","Audit required: Use of `marshal` module","The [marshal](https://docs.python.org/3/library/marshal.html) module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source.\n\n\u003C!--more-->\nData serialization is the process of converting structured data to a format that allows sharing or storage of the data in a form that allows recovery of its original structure.\n\nThe marshal module exists mainly to support reading and writing the pseudo-compiled code for Python modules of .pyc files. Backward compatibility of the module is not guaranteed. `marshal` supports only elementary data types (e.g., dictionaries, lists, tuples, numbers, and strings).\n\nIt is recommended to avoid use of `marshal` module. Consider using [`PyYaml`](https://pyyaml.org/wiki/PyYAMLDocumentation) module with default safe loader. PyYAML is a YAML parser and emitter for Python. YAML is language-agnostic and human-readable serialization format and can represent simple data types & structures. But `marshal` module is much faster than YAML. If speed is a concern, use the [pickle](https://docs.python.org/3/library/pickle.html) module instead – the performance is comparable, version independence is guaranteed, and pickle supports a substantially wider range of objects than `marshal`.\n### Bad practice\n```python\nfrom flask import request\n\nimport marshal\n\n@app.route('/marshal')\ndef load():\n    data = request.GET.get(\"data\")\n    conf = marshal.loads(data) # Insecure. Avoid using marhsal module\n```\n\n### Recommended\n```python\nfrom flask import request\n\nimport yaml\n\n@app.route('/yaml')\ndef load():\n    data = request.GET.get(\"data\")\n    conf = yaml.load(data) # Secure\n```\n\n## References:\n- OWASP Top 10 2021 Category A08 - [Software and Data Integrity Failures](https://owasp.org/Top10/A08_2021-Software_and_Data_Integrity_Failures/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE 502](https://cwe.mitre.org/data/definitions/502.html) - Deserialization of Untrusted Data\n- [marshal module](https://docs.python.org/3/library/marshal.html)\n- [yaml module](https://pyyaml.org/wiki/PyYAMLDocumentation)\n- [pickle module](https://docs.python.org/3/library/pickle.html)",[1647,2803,2804,1704,1204],{"shortcode":3236,"title":3237,"description":3238,"category":37,"severity":1294,"tags":3239,"isRecommended":2323},"BAN-B608","Audit required: Risk of possible SQL injection vector through string-based query construction","Constructing SQL query using user provided data is insecure. It makes application vulnerable to [SQL injection]([SQL injection](https://owasp.org/www-community/attacks/SQL_Injection)) attacks.\n\u003C!--more-->\nAn SQL injection attack consists of the insertion or “injection” of an SQL query via the input data given to an application. It is a very common attack vector. Unless care is taken to sanitize and control the input data when building such SQL statement strings, an injection attack becomes possible. It is possible for an attacker to craft queries to read, modify, or delete sensitive information from the database and sometimes even shut it down or execute arbitrary operating system commands.\n\nIt is recommended to ensure that the user-provided data is properly escaped and validated. Modern database adapters come with built-in tools for preventing Python SQL injection by using query parameters.\n\nSince this is an audit issue, some occurrences may be harmless here. The goal is to bring the issue to attention. Please make sure that the input string is trusted. If the occurrences don't seem to be valid, please feel free to ignore them.\n### Bad practice\n```python\ncursor = connection.cursor()\ncursor.execute(\"SELECT id FROM userdata WHERE Name =%s;\" % name)  # Sensitve. Query constructed based on user's input\n```\n\n### Recommended\n```python\ncursor = connection.cursor()\n# # Username is passed as a named parameter.\n# Database will use the specified type and value of username when executing the query\ncursor.execute(\"SELECT * FROM userdata WHERE Name = %s;\", (name,))\n```\n## References:\n- [SQL injection](https://owasp.org/www-community/attacks/SQL_Injection)\n- [SQL injection attacks with Python](https://realpython.com/prevent-python-sql-injection/)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-20](https://cwe.mitre.org/data/definitions/20.html) - Improper input validation\n- [CWE 89](https://cwe.mitre.org/data/definitions/89.html) - Improper Neutralization of Special Elements used in an SQL Command",[1647,1503,3240,3241,1704,1204],"cwe-20","cwe-89",{"shortcode":3243,"title":3244,"description":3245,"category":37,"severity":1294,"tags":3246,"isRecommended":2323},"BAN-B609","Audit required: Possible wildcard injection in call: `subprocess.Popen`","The use of partially qualified paths may result in unintended consequences if an unexpected file or symlink is placed into the path location given. This becomes particularly dangerous when combined with commands used to manipulate file permissions or copy data off of a system.\n\n\u003C!--more-->\nPython provides a number of methods that emulate the behavior of standard Linux command line utilities. Like their Linux counterparts, these commands may take a wildcard “*” character in place of a file system path. This is interpreted to mean “any and all files or folders” and can be used to build partially qualified paths, such as “/home/user/*”.\n\n### Bad practice\n```python\nimport subprocess\n\nsubprocess.Popen(\"/bin/chown *\") # Sensitive, unexpected file may be placed in location\n```\n\n### Recommended\n```python\nimport subprocess\n\nsubprocess.Popen(\"/bin/chown /home/user/some_file\") # Fixed path provided\n```\n\n## References:\n- [Wildcard Injection attack](https://www.hackingarticles.in/exploiting-wildcard-for-privilege-escalation/)",[1503,1204],{"shortcode":3248,"title":3249,"description":3250,"category":27,"severity":2236,"tags":3251,"isRecommended":2323},"FLK-D208","Docstring is over-indented","It is recommended to properly indent docstrings for readability.",[],{"shortcode":3253,"title":3254,"description":3255,"category":41,"severity":2236,"tags":3256,"isRecommended":2323},"FLK-E242","Tab after comma detected","There should be only one space after the `,` character.",[],{"shortcode":3258,"title":3259,"description":3260,"category":41,"severity":2236,"tags":3261,"isRecommended":2323},"FLK-E126","Continuation line over-indented for hanging indent","A continuation line is indented farther than it should be for a hanging indent.",[],{"shortcode":3263,"title":3264,"description":3265,"category":41,"severity":2236,"tags":3266,"isRecommended":2323},"FLK-E116","Unexpected indentation in comments","Comments should be indented relative to the code in the block they are in.",[],{"shortcode":3268,"title":3269,"description":3270,"category":41,"severity":2236,"tags":3271,"isRecommended":2323},"FLK-E114","Indentation is not a multiple of four in comments","Comment indentation should be a multiple of four.",[],{"shortcode":3273,"title":3274,"description":3275,"category":41,"severity":2236,"tags":3276,"isRecommended":2323},"FLK-W505","Doc line too long","Docstring line lengths are recommended to be no greater than 79 characters.",[],{"shortcode":3278,"title":3279,"description":3250,"category":27,"severity":2236,"tags":3280,"isRecommended":2323},"FLK-D207","Docstring is under-indented",[],{"shortcode":3282,"title":3283,"description":3284,"category":41,"severity":2236,"tags":3285,"isRecommended":2323},"FLK-W191","Indentation contains tabs","Indentation has tabs when only spaces are expected. Change all tabs to spaces.",[],{"shortcode":3287,"title":3288,"description":3255,"category":41,"severity":2236,"tags":3289,"isRecommended":2323},"FLK-E241","Multiple spaces after ','",[],{"shortcode":3291,"title":3292,"description":3293,"category":41,"severity":2236,"tags":3294,"isRecommended":2323},"FLK-E266","Too many leading `#` for block comment","There should be only one leading `#` for a block comment.",[],{"shortcode":3296,"title":3297,"description":3298,"category":41,"severity":2236,"tags":3299,"isRecommended":2323},"FLK-E123","Closing bracket does not match indentation of opening bracket's line","Closing brackets should match the same indentation level of the line that their opening bracket started on.",[],{"shortcode":3301,"title":3302,"description":3303,"category":41,"severity":2236,"tags":3304,"isRecommended":2323},"FLK-E225","Missing whitespace around operator","There should be one space before and after all operators.",[],{"shortcode":3306,"title":3307,"description":3308,"category":15,"severity":2236,"tags":3309,"isRecommended":2323},"PYL-W5101","Model missing `__unicode__` method","Django models should implement a `__unicode__ ` method for string representation.",[],{"shortcode":3311,"title":3312,"description":3313,"category":41,"severity":2236,"tags":3314,"isRecommended":2323},"PYL-W0107","Unnecessary `pass` statement","The `pass` statement used here is not necessary. You can safely remove this.\n\n#### Not Preferred:\n```python\nclass Docstring:\n    '''This is a dummy class with docstring.'''\n    pass\n```\n\n#### Preferred:\n```python\nclass Docstring:\n    '''This is a dummy class with docstring.'''\n```",[],{"shortcode":3316,"title":3317,"description":3318,"category":41,"severity":2236,"tags":3319,"isRecommended":2323},"FLK-W291","Trailing whitespace detected","There should be no whitespace after the final character in a line.",[],{"shortcode":3321,"title":3322,"description":3323,"category":15,"severity":2236,"tags":3324,"isRecommended":2323},"FLK-E731","Named lambda expression detected","Lambdas should not be assigned to a variable. Instead, they should be defined as functions. The primary reason for this is debugging. Lambdas show as `\u003Clambda>` in tracebacks, where functions will display the function’s name.",[],{"shortcode":3326,"title":3327,"description":3328,"category":41,"severity":2236,"tags":3329,"isRecommended":2323},"FLK-E224","Tab found after operator","There should be only one space before or after operators.",[],{"shortcode":3331,"title":3332,"description":3333,"category":41,"severity":2236,"tags":3334,"isRecommended":2323},"FLK-E402","Module level import not at the top of the file","All module level imports should be at the top of the file. This means that there should be no statements in between module level imports.",[],{"shortcode":3336,"title":3337,"description":3338,"category":41,"severity":2236,"tags":3339,"isRecommended":2323},"FLK-E261","At least two spaces before inline comment","Inline comments should have two spaces before them.",[],{"shortcode":3341,"title":3342,"description":3343,"category":41,"severity":2236,"tags":3344,"isRecommended":2323},"FLK-E273","Tab after keyword detected","There should be only one space after a keyword.",[],{"shortcode":3346,"title":3347,"description":3348,"category":41,"severity":2236,"tags":3349,"isRecommended":2323},"PYL-C0328","Unexpected line ending format found","Unexpected line ending format.",[],{"shortcode":3351,"title":3352,"description":3353,"category":41,"severity":2236,"tags":3354,"isRecommended":2323},"FLK-E115","Expected an indented block in comments","An indented block comment was expected but a non-indented block comment was found instead.",[],{"shortcode":3356,"title":3357,"description":3328,"category":41,"severity":2236,"tags":3358,"isRecommended":2323},"FLK-E223","Tab found before operator",[],{"shortcode":3360,"title":3361,"description":3362,"category":41,"severity":2236,"tags":3363,"isRecommended":2323},"FLK-E121","Continuation line is under-indented for hanging indent","A line is less indented than it should be for hanging indents.",[],{"shortcode":3365,"title":2772,"description":3366,"category":41,"severity":2236,"tags":3367,"isRecommended":2323},"FLK-E702","Multiple statements should not be on the same line separated by a semicolon.\nIt is considered a good practice to have statements on their own separate lines. This makes the code more readable.",[],{"shortcode":3369,"title":3370,"description":3371,"category":41,"severity":2236,"tags":3372,"isRecommended":2323},"PYL-W0311","Bad indentation detected","Statements use indentations that are not standard four spaces. [PEP 8](https://python.org/dev/peps/pep-0008) recommends 4 spaces to be used as single indent.",[],{"shortcode":3374,"title":3375,"description":3376,"category":41,"severity":2236,"tags":3377,"isRecommended":2323},"FLK-E202","Whitespace before closing parenthesis","Closing parentheses should not have any before after them.",[],{"shortcode":3379,"title":3380,"description":3381,"category":41,"severity":2236,"tags":3382,"isRecommended":2323},"FLK-E222","Multiple spaces found after operator","There should be only one space after an operator.",[],{"shortcode":3384,"title":3385,"description":3386,"category":41,"severity":2236,"tags":3387,"isRecommended":2323},"FLK-E274","Tab before keyword detected","There should be only one space before a keyword.",[],{"shortcode":3389,"title":3390,"description":3391,"category":41,"severity":2236,"tags":3392,"isRecommended":2323},"FLK-E128","Continuation line under-indented for visual indent","A continuation line is under-indented for a visual indentation.",[],{"shortcode":3394,"title":3395,"description":3396,"category":41,"severity":2236,"tags":3397,"isRecommended":2323},"FLK-E251","Unexpected spaces around keyword / parameter equals","There should be no spaces before or after the `=` in a function definition.",[],{"shortcode":3399,"title":3400,"description":3401,"category":27,"severity":2236,"tags":3402,"isRecommended":2323},"FLK-D210","No whitespaces allowed surrounding docstring text","You should avoid spaces at the beginning and at the end of a docstring.",[],{"shortcode":3404,"title":3405,"description":3406,"category":27,"severity":2236,"tags":3407,"isRecommended":2323},"FLK-D202","No blank lines allowed after function docstring","There shouldn't be any blank lines after the function docstring.\nRemove the blank lines to fix this issue.\n\n \u003C!--more-->\n#### Not preferred:\n```python\ndef example():\n    '''Bad docstring.'''\n\n    pass\n```\n\n#### Preferred:\n```python\ndef example():\n    '''Good docstring.'''\n    pass\n```",[],{"shortcode":3409,"title":3410,"description":3411,"category":27,"severity":2236,"tags":3412,"isRecommended":2323},"FLK-D201","No blank lines allowed before function docstring","There shouldn't be any blank lines before the function docstring.\nRemove the blank lines to fix this issue.\n\n#### Not preferred:\n```python\ndef example():\n\n    '''Bad docstring.'''\n    ...\n```\n\n#### Preferred:\n```python\ndef example():\n    '''Good docstring.'''\n    ...\n```",[],{"shortcode":3414,"title":3415,"description":3416,"category":15,"severity":2236,"tags":3417,"isRecommended":2323},"PY-R1000","Function with cyclomatic complexity higher than threshold","A function with high cyclomatic complexity can be hard to understand and\nmaintain. Cyclomatic complexity is a software metric that measures the number of\nindependent paths through a function. A higher cyclomatic complexity indicates\nthat the function has more decision points and is more complex.\n\n\u003C!--more-->\n\nFunctions with high cyclomatic complexity are more likely to have bugs and be\nharder to test. They may lead to reduced code maintainability and increased\ndevelopment time.\n\nTo reduce the cyclomatic complexity of a function, you can:\n\n- Break the function into smaller, more manageable functions.\n- Refactor complex logic into separate functions or classes.\n- Avoid multiple return paths and deeply nested control expressions.\n\n## Bad practice\n\n```python\ndef number_to_name():\n    number = input()\n    if not number.isdigit():\n        print(\"Enter a valid number\")\n        return\n\n    number = int(number)\n    if number >= 10:\n        print(\"Number is too big\")\n        return\n\n    if number == 1:\n        print(\"one\")\n    elif number == 2:\n        print(\"two\")\n    elif number == 3:\n        print(\"three\")\n    elif number == 4:\n        print(\"four\")\n    elif number == 5:\n        print(\"five\")\n    elif number == 6:\n        print(\"six\")\n    elif number == 7:\n        print(\"seven\")\n    elif number == 8:\n        print(\"eight\")\n    elif number == 9:\n        print(\"nine\")\n```\n\n## Recommended\n\n```python\ndef number_to_name():\n    number = input()\n    if not number.isdigit():\n        print(\"Enter a valid number\")\n        return\n\n    number = int(number)\n    if number >= 10:\n        print(\"Number is too big\")\n        return\n\n    names = {\n      1: \"one\",\n      2: \"two\",\n      3: \"three\",\n      4: \"four\",\n      5: \"five\",\n      6: \"six\",\n      7: \"seven\",\n      8: \"eight\",\n      9: \"nine\",\n    }\n    print(names[number])\n```\n\n### Issue configuration\n\nCyclomatic complexity threshold can be configured using the\n`cyclomatic_complexity_threshold` [meta field](https://docs.deepsource.com/docs/analyzers-python#cyclomatic_complexity_threshold) in the\n`.deepsource.toml` config file.\nConfiguring this is optional. If you don't provide a value, the Analyzer will\nraise issues for functions with complexity higher than the default threshold,\nwhich is `medium` for the Python Analyzer.\n\nHere's the mapping of the risk category to the cyclomatic complexity score to\nhelp you configure this better:\n\n| Risk category | Cyclomatic complexity range | Recommended action                                                                                         |\n| :------------ | :-------------------------- | :--------------------------------------------------------------------------------------------------------- |\n| low           | 1-5                         | No action needed.                                                                                          |\n| medium        | 6-15                        | Review and monitor.                                                                                        |\n| high          | 16-25                       | Review and refactor. Recommended to add comments if the function is absolutely needed to be kept as it is. |\n| very-high     | 26-50                       | Refactor to reduce the complexity.                                                                         |\n| critical      | >50                         | Must refactor this. This can make the code untestable and very difficult to understand.                    |",[],{"shortcode":3419,"title":3420,"description":3421,"category":27,"severity":2236,"tags":3422,"isRecommended":2323},"FLK-D200","One-line docstring should fit on one line with quotes","If a docstring fits in a single line (72 characters according to PEP8), it is\nrecommended to have the quotes on the same line.\n\n\u003C!--more-->\n\n### Bad practice\n\n```python\ndef foo():\n  \"\"\"\n  Runs bar and returns baz.\n  \"\"\"\n  baz = bar()\n  return baz\n```\n\n### Recommended\n\n```python\ndef foo():\n  \"\"\"Runs bar and returns baz.\"\"\"\n  baz = bar()\n  return baz\n```",[],{"shortcode":3424,"title":3425,"description":3426,"category":41,"severity":2236,"tags":3427,"isRecommended":2323},"FLK-E275","Missing whitespace after keyword","There should be one space after keywords.",[],{"shortcode":3429,"title":3430,"description":3431,"category":15,"severity":2236,"tags":3432,"isRecommended":2323},"PYL-W5103","Model does not explicitly define `__unicode__`","Django models should implement a `__unicode__` method for string representation.  A parent class of this model does, but ideally all models should be explicit.",[],{"shortcode":3434,"title":3435,"description":3436,"category":45,"severity":2236,"tags":3437,"isRecommended":2323},"TYP-001","Unnecessary suppression of type checking issue","Useless suppression of a type checker issue with `type: ignore` comment. There is no issue being raised here, hence you can safely remove this comment.",[],{"shortcode":3439,"title":3440,"description":3441,"category":41,"severity":2236,"tags":3442,"isRecommended":2323},"FLK-E303","Too many blank lines found","Two blank lines are expected between functions and classes and one blank line is expected between methods of a class.",[],{"shortcode":3444,"title":3445,"description":3446,"category":41,"severity":2236,"tags":3447,"isRecommended":2323},"FLK-E226","Missing whitespace around arithmetic operator","There should be one space before and after an arithmetic operator (`+`, `-`, `/`, and `*`).",[],{"shortcode":3449,"title":3450,"description":3451,"category":41,"severity":2236,"tags":3452,"isRecommended":2323},"FLK-E122","Continuation line missing indentation or outdented","A continuation line is not indented as far as it should be or is indented too much.",[],{"shortcode":3454,"title":3455,"description":3456,"category":41,"severity":2236,"tags":3457,"isRecommended":2323},"FLK-E131","Continuation line unaligned for hanging indent","A continuation line is unaligned for hanging indent.",[],{"shortcode":3459,"title":3460,"description":3461,"category":41,"severity":2236,"tags":3462,"isRecommended":2323},"FLK-E502","The backslash is redundant between brackets","There is no need for backslashes between brackets.",[],{"shortcode":3464,"title":3465,"description":3466,"category":41,"severity":2236,"tags":3467,"isRecommended":2323},"FLK-E228","Missing whitespace around modulo operator","The modulo operator `%` should have whitespace on both the sides.",[],{"shortcode":3469,"title":3470,"description":3471,"category":41,"severity":2236,"tags":3472,"isRecommended":2323},"FLK-E401","Multiple imports on one line","Imports from different modules should be on different lines.\n\n```python\nimport os, sys  # multiple imports on same line\n\n# instead these imports should be on their own line\nimport os\nimport sys\n```",[],{"shortcode":3474,"title":3475,"description":3476,"category":41,"severity":2236,"tags":3477,"isRecommended":2323},"FLK-E304","Blank lines found after function decorator","There should be no blank lines between a function decorator and the function definition.",[],{"shortcode":3479,"title":3480,"description":3481,"category":15,"severity":2236,"tags":3482,"isRecommended":2323},"PTC-W0018","Unnecessary literal","It is unnecessary to use a `list` or `tuple` literal within a call to `tuple`, `list`, `set`, or `dict` since there is a literal syntax for these types.",[],{"shortcode":3484,"title":3485,"description":3486,"category":41,"severity":2236,"tags":3487,"isRecommended":2323},"PYL-C0327","Mixed line endings found","There are mixed (LF and CRLF) newline signs in a file.\nIt means, some of the lines terminate with `\n` (LF) sequence and some with `\r\n` (CRLF) sequence.\n\nWhen this file is edited locally, all the terminating sequence will be converted to a common sequence depending on the machine it is edited in.\nThis may cause confusion when viewing the diff of that file in git (or any other version control system).",[],{"shortcode":3489,"title":3490,"description":3491,"category":41,"severity":2236,"tags":3492,"isRecommended":2323},"FLK-E741","Do not use variables named 'l', 'O', or 'I'","Variables named `I`, `O`, and `l` can be very hard to read. This is because the letter `I` and the letter `l` are easily confused, and the letter `O` and the number `0` can be easily confused.\n\nChange the names of these variables to something more descriptive.",[],{"shortcode":3494,"title":3495,"description":3496,"category":41,"severity":2236,"tags":3497,"isRecommended":2323},"FLK-W391","Multiple blank lines detected at end of the file","There should be one, and only one, blank line at the end of each file. This warning will occur when there are two or more blank lines.",[],{"shortcode":3499,"title":3500,"description":3501,"category":41,"severity":2236,"tags":3502,"isRecommended":2323},"PYL-R1710","Inconsistent return statements","According to [PEP8](https://www.python.org/dev/peps/pep-0008/), 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).\n\nGood:\n```python\ndef foo(x):\n    if x >= 0:\n        return math.sqrt(x)\n    else:\n        return None\n\ndef bar(x):\n    if x \u003C 0:\n        return None\n    return math.sqrt(x)\n```\nBad:\n```python\ndef foo(x):\n    if x >= 0:\n        return math.sqrt(x)\n\ndef bar(x):\n    if x \u003C 0:\n        return\n    return math.sqrt(x)\n```",[],{"shortcode":3504,"title":3505,"description":3506,"category":15,"severity":2236,"tags":3507,"isRecommended":2323},"PYL-R1716","Chained comparison detected","Detected boolean operation like`a \u003C b and b \u003C c`.\nIt is recommended to refactor it to `a \u003C b \u003C c`. It improves readability,",[],{"shortcode":3509,"title":3510,"description":3511,"category":15,"severity":2236,"tags":3512,"isRecommended":2323},"PYL-W0201","Attribute defined outside `__init__`","Defining an instance attribute outside `__init__` affects the readability of code. It is expected to find all the attributes an instance may have by reading its `__init__` method. If there is a need to initialize attribute via sub-initialization methods, it is recommended to assign attributes to `None` in the __init__ then call the sub-initialization methods.",[],{"shortcode":3514,"title":3515,"description":3516,"category":41,"severity":2236,"tags":3517,"isRecommended":2323},"FLK-W503","Line break before binary operator","Line breaks should occur after the binary operator to keep all variable names aligned.",[],{"shortcode":3519,"title":3520,"description":3521,"category":41,"severity":2236,"tags":3522,"isRecommended":2323},"PYL-W0301","Unnecessary semicolon","Semicolons are not needed in Python unless using multiple statements in single line.\nUse of semi-colons add unnecessary clutter.\n\n\u003C!--more-->\n### Bad practice\n```python\nfor x in range(10):\n    if input[x]:\n        i = x - 2;\n        x = i * i;\n    print(i);\n```\n\n### Preferred\n```python\nfor x in range(10):\n    if input[x]:\n        i = x - 2\n        x = i * i\n    print(i)\n```",[],{"shortcode":3524,"title":3525,"description":3526,"category":41,"severity":2236,"tags":3527,"isRecommended":2323},"FLK-E129","Visually indented line with same indent as next logical line","A visual indented line has the same indentation as the next logical line. This can make it hard to read.",[],{"shortcode":3529,"title":3530,"description":3531,"category":27,"severity":2236,"tags":3532,"isRecommended":2323},"FLK-D206","Docstring should be indented with spaces, not tabs","It is recommended to use spaces in the docstrings, just as the code.",[],{"shortcode":3534,"title":3535,"description":3536,"category":27,"severity":2236,"tags":3537,"isRecommended":2323},"FLK-D301","Use r”“” if any backslashes in a docstring","If there are backslashes in a docstring, please use raw strings.",[],{"shortcode":3539,"title":3540,"description":3541,"category":41,"severity":2236,"tags":3542,"isRecommended":2323},"FLK-E125","Continuation line with same indent as next logical line","Continuation lines should not be indented at the same level as the next logical line. Instead, they should be indented to one more level so as to distinguish them from the next line.",[],{"shortcode":3544,"title":3545,"description":3386,"category":41,"severity":2236,"tags":3546,"isRecommended":2323},"FLK-E272","Multiple spaces before keyword",[],{"shortcode":3548,"title":3549,"description":3550,"category":45,"severity":2236,"tags":3551,"isRecommended":2323},"TYP-051","Missing type annotation for callable","The callable is missing type annotation. It is required to type annotate the functions for the type checker to check for issues accurately.",[],{"shortcode":3553,"title":3554,"description":3555,"category":41,"severity":2236,"tags":3556,"isRecommended":2323},"FLK-E262","Inline comment should start with `# `","Inline comments should have one space before the pound sign `#` and the comment itself.",[],{"shortcode":3558,"title":3559,"description":3560,"category":41,"severity":2236,"tags":3561,"isRecommended":2323},"FLK-E301","Expected 1 blank line","One blank line is expected between the methods of a class.",[],{"shortcode":3563,"title":3564,"description":3565,"category":41,"severity":2236,"tags":3566,"isRecommended":2323},"FLK-E302","Expected 2 blank lines","Two blank lines are expected between functions and classes.",[],{"shortcode":3568,"title":3569,"description":3570,"category":41,"severity":2236,"tags":3571,"isRecommended":2323},"FLK-E201","Whitespace after opening parenthesis detected","Open parentheses should not have any space before or after them.",[],{"shortcode":3573,"title":3574,"description":3575,"category":27,"severity":2236,"tags":3576,"isRecommended":2323},"FLK-D300","Use of single quote detected in docstring","Use of triple-quotes is recommended to specify docstrings.",[],{"shortcode":3578,"title":3579,"description":3580,"category":41,"severity":2236,"tags":3581,"isRecommended":2323},"FLK-E127","Continuation line over-indented for visual indent","A continuation line is indented farther than it should be for a visual indent.",[],{"shortcode":3583,"title":3584,"description":3585,"category":41,"severity":2236,"tags":3586,"isRecommended":2323},"FLK-E221","Multiple spaces found before operator","There should be only one space before an operator.",[],{"shortcode":3588,"title":3589,"description":3343,"category":41,"severity":2236,"tags":3590,"isRecommended":2323},"FLK-E271","Multiple spaces after keyword",[],{"shortcode":3592,"title":3593,"description":3594,"category":41,"severity":2236,"tags":3595,"isRecommended":2323},"FLK-E124","Closing bracket does not match visual indentation","Closing brackets should match the indentation of the opening bracket.",[],{"shortcode":3597,"title":3598,"description":3599,"category":41,"severity":2236,"tags":3600,"isRecommended":2323},"FLK-E306","Expected 1 blank line before a nested definition","Nested functions and classes should have one blank line before them.",[],{"shortcode":3602,"title":3603,"description":3604,"category":41,"severity":2236,"tags":3605,"isRecommended":2323},"FLK-E501","Line too long","Line length greater than configured `max_line_length` detected, defaults to 79 character. This limit can be configured [docs](https://deepsource.io/docs/analyzer/python/#meta)",[],{"shortcode":3607,"title":3608,"description":3609,"category":41,"severity":2236,"tags":3610,"isRecommended":2323},"FLK-E703","Statement ends with a semicolon","Unlike programming languages like Java and C#, statements in Python do not need to end with a semicolon. They can be safely removed.",[],{"shortcode":3612,"title":3613,"description":3570,"category":41,"severity":2236,"tags":3614,"isRecommended":2323},"FLK-E211","Whitespace before opening parenthesis",[],{"shortcode":3616,"title":3617,"description":3618,"category":41,"severity":2236,"tags":3619,"isRecommended":2323},"FLK-E305","Expected 2 blank lines after end of function or class","Functions and classes should have two blank lines after them, separating them from other functions and classes.",[],{"shortcode":3621,"title":3622,"description":3623,"category":15,"severity":2236,"tags":3624,"isRecommended":2323},"PTC-W0020","Unnecessary typecast","Object is being type casted to the same type. This is unnecessary.",[],{"shortcode":3626,"title":3627,"description":3628,"category":27,"severity":2236,"tags":3629,"isRecommended":2323},"PYL-W0511","Use of `FIXME`/`XXX`/`TODO` encountered","You have marked this block as `FIXME`/`XXX`/`TODO`. Please make sure this is addressed, or remove this comment as this could be misleading.",[],{"shortcode":3631,"title":3632,"description":3633,"category":15,"severity":2236,"tags":3634,"isRecommended":2323},"PYL-W0603","`global` statement detected","It is recommended not to use `global` statement unless it is really necessary. Global variables are dangerous because they can be simultaneously accessed from multiple sections of a program. This frequently results in bugs. This also make code difficult to read, because they force you to search through multiple functions or even modules just to understand all the different locations where the global variable is used and modified. Read more about why it should be avoided [here](http://wiki.c2.com/?GlobalVariablesAreBad).",[],{"shortcode":3636,"title":3637,"description":3638,"category":19,"severity":2236,"tags":3639,"isRecommended":2323},"FLK-E722","Do not use bare `except`, specify exception instead","Using `except` without a specific exception can be error prone.",[],{"shortcode":3641,"title":3642,"description":3643,"category":41,"severity":2236,"tags":3644,"isRecommended":2323},"FLK-E227","Missing whitespace around bitwise or shift operator","There should be one space before and after bitwise and shift operators (`\u003C\u003C`, `>>`, `&`, `|`, `^`).",[],{"shortcode":3646,"title":3647,"description":3648,"category":37,"severity":2236,"tags":3649,"isRecommended":2323},"BAN-B606","Audit required: Starting a subprocess","Spawning of a subprocess in a way that doesn't use a shell is generally safe, but it maybe useful for penetration testing workflows to track where external system calls are used.\n\n\u003C!--more-->\nPython possesses many mechanisms to invoke an external executable. However, doing so may present a security issue if appropriate care is not taken to sanitize any user provided or variable input.\n```python\nimport os\n\n# Creating subprocess:\n# The following calls can be sensitive if the command is not sanitized, since they are starting a subprocess.\nos.spawnl(mode, path, *cmd)\nos.spawnle(mode, path, *cmd, env)\nos.spawnlp(mode, file, *cmd)\nos.spawnlpe(mode, file, *cmd, env)\nos.spawnv(mode, path, cmd)\n```\n\n## References:\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE-78](https://cwe.mitre.org/data/definitions/78.html)",[1647,2734,1503,1704,1204],{"shortcode":3651,"title":3652,"description":3653,"category":41,"severity":2236,"tags":3654,"isRecommended":2323},"PYL-C0325","Unnecessary parentheses after keyword","Extra parentheses in code can be removed for improved readability.\n\nIn the examples below, the first example is more readable than the second one.\n\nPreferred:\n```python\nif len(some_variable) + 1 \u003C 1:\n    ...\n```\n\nNot preferred:\n```python\nif (len(some_variable) + 1) \u003C 1:\n    ...\n```",[],{"shortcode":3656,"title":3657,"description":3658,"category":37,"severity":2236,"tags":3659,"isRecommended":2323},"BAN-B607","Audit: Starting a process with a partial executable path","Python possesses many mechanisms to invoke an external executable. If the desired executable path is not fully qualified relative to the filesystem root then this may present a potential security risk.\n\n\u003C!--more-->\nIn POSIX environments, the PATH environment variable is used to specify a set of standard locations that will be searched for the first matching named executable. While convenient, this behavior may allow a malicious actor to exert control over a system. If they are able to adjust the contents of the PATH variable, or manipulate the file system, then a bogus executable may be discovered in place of the desired one. This executable will be invoked with the user privileges of the Python process that spawned it, potentially a highly privileged user.\n\nThis test will scan the parameters of all configured Python methods, looking for paths that do not start at the filesystem root, that is, do not have a leading ‘/’ character.\n\n### Bad practice\n```python\nimport subprocess\n\nsubprocess.run(['calculator', '-u', 'critical', msg], check=True) # Sensitive, Path not qualified from root\n```\n\n### Recommended\n```python\nimport subprocess\n\nsubprocess.run(['/usr/bin/calculator', '-u', 'critical', msg], check=True) # Path qualified from root\n```\n\n## References:\n- [Bandit B607](https://bandit.readthedocs.io/en/latest/plugins/b607_start_process_with_partial_path.html#b607-start-process-with-partial-path)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)",[1503,1204],{"shortcode":3661,"title":3662,"description":3663,"category":37,"severity":2236,"tags":3664,"isRecommended":2323},"BAN-B610","Audit required: Potential SQL injection on `extra` function","Use of `extra` in Django querysets should be audited, since unsanitized strings can open up security vulnerabilities. It makes application vulnerable to [SQL injection]([SQL injection](https://owasp.org/www-community/attacks/SQL_Injection)) attacks.\n\n\u003C!--more-->\nSometimes, the Django query syntax by itself can’t easily express a complex WHERE clause. For these edge cases, Django provides the [extra()](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.extra) QuerySet modifier — a hook for injecting specific clauses into the SQL generated by a QuerySet.\n\n An SQL injection attack consists of insertion or “injection” of a SQL query via the input data given to an application. It is a very common attack vector.\n\nOne should be very careful whenever you use `extra()`. Use it only if you cannot express your query using other queryset methods.\n### Bad practice\n```python\nqs.extra(\n...     select={'val': \"select col from sometable where othercol = %s\"},\n...     select_params=(someparam,),\n)\n```\nExecuting above code snippet is equivalent to the following raw SQL with unsatized input:\n```python\nqs.annotate(val=RawSQL(\"select col from sometable where othercol = %s\", (someparam,)))\n```\n\n## References:\n- [extra() QuerySet modifier in Django](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.extra)\n- [SQL injection protection in Django](https://docs.djangoproject.com/en/3.2/topics/security/#sql-injection-protection)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- [SANS Top 25](https://www.sans.org/top25-software-errors/)\n- [CWE 20](https://cwe.mitre.org/data/definitions/20.html) - Improper Input Validation",[1647,3240,1503,1704,1204],{"shortcode":3666,"title":3667,"description":3668,"category":37,"severity":2236,"tags":3669,"isRecommended":2323},"BAN-B405","Import of method(s) from `xml.etree` detected","Using various methods to parse untrusted XML data is known to be vulnerable to XML attacks.\n\u003C!--more-->\nThe xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. But it makes the application vulnerable to:\n\n- [Billion Laughs attack](https://en.wikipedia.org/wiki/Billion_laughs_attack) - It is a type of denial-of-service attack aimed at parsers of XML documents. It uses multiple levels of nested entities. If one large entity is repeated with a couple of thousand chars over and over again, parser gets overwhelmend.\n- [Quadratic blowup attack](https://www.acunetix.com/vulnerabilities/web/xml-quadratic-blowup-denial-of-service-attack/) - It is similar to a Billion Laughs attack. It abuses entity expansion, too. Instead of nested entities it repeats one large entity with a couple of thousand chars over and over again.\n\nReplace vulnerable imports with the equivalent [defusedxml](https://pypi.org/project/defusedxml) package, or make sure `defusedxml.defuse_stdlib()` is called.\n\n### Bad practice\n```python\nimport xml.etree.ElementTree as ET # Insecure, import from xml.etree\ntree = ET.parse('some_fie.xml')\n```\n### Recommended\n```python\nfrom defusedxml.ElementTree import parse\ntree = parse('some_fie.xml')\n```\n\n## References:\n- [xml.etree](https://docs.python.org/3/library/xml.etree.elementtree.html)\n- [defusedxml](https://pypi.org/project/defusedxml/)\n- [XML vulnerabilities](https://docs.python.org/3/library/xml.html#xml-vulnerabilities)\n- OWASP Top 10 2021 Category A03 - [Injection](https://owasp.org/Top10/A03_2021-Injection/)\n- OWASP Top 10 2021 Category A06 - [Vulnerable and Outdated Components](https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/)\n- [CWE-611](https://cwe.mitre.org/data/definitions/611.html)",[1647,1503,1716,1362,1704,1204],{"shortcode":3671,"title":3672,"description":3673,"category":37,"severity":2236,"tags":3674,"isRecommended":2323},"BAN-B503","SSL used with bad defaults","Python methods with default parameter values that specify the use of broken SSL/TLS protocol versions are insecure.\n\n \u003C!--more-->\nSeveral highly publicized exploitable flaws have been discovered in all versions of SSL and early versions of TLS. It is strongly recommended that the use of the following known broken protocol versions be avoided:\n\n- SSL v2\n- SSL v3\n- TLS v1\n- TLS v1.1\n\nEnsure that a modern, strong protocol is used. All versions listed above are known to be vulnerable to attacks. Using [TLS v1.2](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_TLSv1_2) is strongly recommended.\n### Bad practice\n```python\nimport ssl\n\ndef open_ssl_socket(version=SSL.SSLv2_METHOD): # Insecure. SSL v2 used\n    pass\n```\n\n### Recommended\n```python\nimport ssl\n\ndef open_ssl_socket(version=ssl.PROTOCOL_TLSv1_2): # Secure, TLS v1.2 used\n    pass\n```\n\n## References:\n- [ssl module in python](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_SSLv2)\n- [TLS v1.2](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_TLSv1_2)\n- OWASP Top 10 2021 Category A02 - [Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- [CWE 327](https://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm",[1647,1203,1627,1648,1204],{"shortcode":3676,"title":3677,"description":3678,"category":37,"severity":2236,"tags":3679,"isRecommended":2323},"BAN-B504","SSL used with no version specified","Specific methods in Python's native SSL/TLS support and the pyOpenSSL module may use default versions of SSL/TLS protocol which are insecure.\n\n \u003C!--more-->\nSeveral highly publicized exploitable flaws have been discovered in all versions of SSL and early versions of TLS. It is strongly recommended that use of the following known broken protocol versions be avoided:\n\n- SSL v2\n- SSL v3\n- TLS v1\n- TLS v1.1\n\nEnsure that a modern, strong protocol is used. All versions listed above are known to be vulnerable to attacks. Using [TLS v1.2](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_TLSv1_2) is strongly recommended.\n### Bad practice\n```python\nimport ssl\nimport socket\n\nssl.wrap_socket(socket.socket())\n```\n\n### Recommended\n```python\nimport ssl\nimport socket\n\nssl.wrap_socket(socket.socket(), ssl_version=ssl.PROTOCOL_TLSv1_2)\n``\n\n## References:\n- [ssl module in python](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_SSLv2)\n- [TLS v1.2](https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_TLSv1_2)\n- OWASP Top 10 2021 Category A02 - [Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- [CWE 327](https://cwe.mitre.org/data/definitions/327.html) - Use of a Broken or Risky Cryptographic Algorithm",[1647,1203,1627,1648,1204],{"shortcode":3681,"title":3682,"description":3683,"category":41,"severity":2236,"tags":3684,"isRecommended":2323},"FLK-E231","Missing whitespace after `,`, `;`, or `:`","There should be whitespace after the characters `,`, `;`, and `:`.",[],{"shortcode":3686,"title":3687,"description":3688,"category":41,"severity":2236,"tags":3689,"isRecommended":2323},"FLK-E265","Block comment should start with `# `","Block comments should have one space before the pound sign `#` and the comment itself.\n\n\u003C!--more-->\n\n### Bad practice\n\n```python\n#Save the data to DB, to ensure redundancy before responding\ndb.save(req.data)\napi.send(req)\n```\n\n### Recommended\n\n```python\n# Save the data to DB, to ensure redundancy before responding\ndb.save(req.data)\napi.send(req)\n```",[],{"shortcode":3691,"title":3692,"description":3693,"category":41,"severity":2236,"tags":3694,"isRecommended":2323},"PYL-C0412","Imports from same package are not grouped","Imports for the same package are scattered and not grouped together.\nIt is recommended to keep the imports from the same package together. It makes the code easier to read.\n\nNot preferred:\n```python\nimport os\nimport sys\nfrom os import listdir\nimport time\nfrom os.path import isfile, join\n```\n\nPreferred:\n```python\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\n\nimport sys\nimport time\n```",[],{"shortcode":3696,"title":3697,"description":3698,"category":45,"severity":2236,"tags":3699,"isRecommended":2323},"TYP-048","Invalid type alias detected","The type alias provided is not valid. Read more about `type aliases` [here](https://mypy.readthedocs.io/en/latest/kinds_of_types.html#type-aliases).",[],{"shortcode":3701,"title":3702,"description":3703,"category":45,"severity":2236,"tags":3704,"isRecommended":2323},"TYP-068","Missing type hint","Type annotation or type comment was not found. Please see the occurrence message for more details.",[],{"shortcode":3706,"title":3707,"description":3708,"category":45,"severity":2236,"tags":3709,"isRecommended":2323},"TYP-012","Uninferred `lambda expression` type","The type of lambda expression cannot be inferred here.",[],{"shortcode":3711,"title":3712,"description":3713,"category":27,"severity":2236,"tags":3714,"isRecommended":2323},"PY-D0002","Missing class docstring","Class docstring is missing.\nIf you want to ignore this, you can configure this in the `.deepsource.toml` file. Please refer to [docs](https://deepsource.io/docs/analyzer/python/#meta) for available options.",[],{"shortcode":3716,"title":3717,"description":3718,"category":15,"severity":2236,"tags":3719,"isRecommended":2323},"PYL-W0127","Variable assigned to itself","Variable is being assigned to itself.\n\u003C!--more-->\nIt is unnecessary to assign a variable to itself without any modification. You can safely remove this assignment operation.\n## Bad practice:\n```python\nif condition:\n    x = x\n    doSomething()\n```\n\n## Recommended\n```python\nif condition:\n    doSomething()\n```",[],{"shortcode":3721,"title":3722,"description":3723,"category":19,"severity":2236,"tags":3724,"isRecommended":2323},"PYL-W1510","Subprocess run with ignored non-zero exit","`subprocess.run` uses a default of `check=False`, which means that a nonzero exit code will be\nignored by default, instead of raising an exception.\n\nYou can ignore this issue if this behaviour is intended.\n\n\u003C!--more-->\n\n### Bad practice\n```python\n# Nonzero exit code will be ignored here\nsubprocess.run(['notify-send', '-u', 'critical', msg])\n```\n\n### Recommended\n```python\n# Exception will be raised for nonzero exit code\nsubprocess.run(['notify-send', '-u', 'critical', msg], check=True) # some comment\n```",[],{"shortcode":3726,"title":3727,"description":3728,"category":27,"severity":2236,"tags":3729,"isRecommended":2323},"PY-D0001","Missing module docstring","Module docstring is missing.\nIf you want to ignore this, you can configure this in the `.deepsource.toml` file. Please refer to [docs](https://deepsource.io/docs/analyzer/python/#meta) for available options.",[],{"shortcode":3731,"title":3732,"description":3733,"category":27,"severity":2236,"tags":3734,"isRecommended":2323},"FLK-D211","No blank lines allowed before class docstring","There shouldn't be any blank lines before the class docstring.\nRemove the blank lines to fix this issue.\n\n#### Not preferred:\n```python\nclass Example:\n\n    '''Bad docstring.'''\n```\n\n#### Preferred:\n```python\nclass Example:\n    '''Good docstring.'''\n```",[],{"shortcode":3736,"title":3737,"description":3738,"category":27,"severity":2236,"tags":3739,"isRecommended":2323},"FLK-D209","Multi-line docstring closing quotes should be on a separate line","#### Not Preferred:\n```python\ndef foo():\n    \"\"\"This is an example docstring.\n    To show how to write multi-line docstring.\"\"\"\n```\n\n#### Preferred:\n```python\ndef foo():\n    \"\"\"\n    This is an example docstring.\n    To show how to write multi-line docstring.\n    \"\"\"\n```",[],{"shortcode":3741,"title":3742,"description":3743,"category":27,"severity":2236,"tags":3744,"isRecommended":2323},"FLK-D204","1 blank line required after class docstring","There should be exactly one blank line after the class docstring.\n\n#### Not preferred:\n```python\nclass example:\n    \"\"\"Bad docstring.\"\"\"\n    ...\n```\n\n#### Preferred:\n```python\nclass  example:\n    \"\"\"Good docstring.\"\"\"\n\n    ...\n```",[],{"shortcode":3746,"title":3747,"description":3748,"category":15,"severity":2236,"tags":3749,"isRecommended":2323},"PTC-W0039","Unnecessary `None` provided as default","It is unnecessary to provide `None` as the default value when the key is not present in the dictionary as `get` implicitly returns `None`.\n\nNot preferred:\n```python\nvalue = some_dict.get(\"key\", None)\n```\n\nPreferred:\n```python\nvalue = some_dict.get(\"key\")\n```",[],{"shortcode":3751,"title":3752,"description":3753,"category":27,"severity":2236,"tags":3754,"isRecommended":2323},"PY-D0003","Missing module/function docstring","The module/function docstring is missing.\nIf you want to ignore this, you can configure this in the `.deepsource.toml` file. Please refer to [docs](https://deepsource.io/docs/analyzer/python/#meta) for available options.",[],{"shortcode":3756,"title":3757,"description":3758,"category":15,"severity":2236,"tags":3759,"isRecommended":2323},"PYL-W0105","Unassigned string statement","The string statement has not been assigned to anything. This is pointless and should be removed if not necessary.\nIn case this is supposed to describe what's happening in the code, it is recommended to use comments or docstrings instead.\n\n#### Not preferred:\n```python\n'Define a function to add 2 numbers here.'\ndef add(a, b):\n    return a + b\n```\n\n#### Preferred:\nUse Comments:\n\n```python\n# Define a function to add 2 numbers here.\ndef add(a, b):\n    return a + b\n```\n\nor, use docstrings:\n```python\ndef add(a, b):\n    '''Function to add 2 numbers here.'''\n    return a + b\n```",[],{"shortcode":3761,"title":3762,"description":3763,"category":27,"severity":2236,"tags":3764,"isRecommended":2323},"FLK-D402","First line should not be the function’s “signature”","The first line of the function docstring has the function's signature, which is not recommended.\nIt shouldn't be specified unless you're specifying or explaining something which might be confusing.\nIt is recommended to remove the redundant function signature from the docstring.\n\n\u003C!--more-->\n### Bad practice\n```python\ndef area(a, b):\n    '''area(a, b) -> a*b'''\n    ...\n```\n\n### Recommended\n```python\ndef area(a, b):\n    '''Calculates area of rectagnle with sides a and b'''\n    ...",[],{"shortcode":3766,"title":3767,"description":3768,"category":41,"severity":2236,"tags":3769,"isRecommended":2323},"PTC-W0907","Redundant `default=None` for a model field","If field is nullable (`null=True`), then it is unnecessary to provide `default=None` since this is implicit.\nIt is recommended to remove `default=None` kwarg.\n\n### Not Preferred:\n```python\nclass SomeModel(models.Model):\n    some_field = models.EmailField(null=True, default=None)\n```\n\n### Preferred:\n```python\nclass SomeModel(models.Model):\n    some_field = EmailField(null=True)\n```",[],{"shortcode":3771,"title":3772,"description":3773,"category":15,"severity":2236,"tags":3774,"isRecommended":2323},"PTC-W0066","Use of `=+` / `=-` looks ambiguous","Operator pair (`=+` / `=+`) used without space after `=` looks ambiguous. This looks like a typo for `+=` / `-=`.\n\n\u003C!--more-->\nOperator pair (`=+` or `=-`) don't produce the same result as the reverse operator (`+=` or `-=`).\n\nIf you wanted to make the operand negative, consider inserting a space after the assignment operator like this `x = -5`.\n\nThis may also be a typo, where you actually meant something like `x += 1`.\n\n### Not Preferred\n```python\ntotal = 10\ncount = 5\ntotal =+ count # total = 5, Addition assignment doesn't take place\nloss =- count # loss = -5, Not clear whether intent is to assign the inverse or perfrom Subtraction assignment\n```\n\n### Preferred\n```python\ntotal = 10\ncount = 5\nloss = 10\n\n# When + / -  is intentional after `=`\ntotal = count  # total = 10\nloss = -count  # loss = -5 : Expected result is clear\n\n# If the operator was a typo:\ntotal += count  # total = 15\nloss -= count  # loss = 5\n```\n\n*_NOTE: In this case, DeepSoure autofixes the issue by changing `=+` to `+=` and `=-` to `-=` respectively._*\n*_Please do not autofix this issue if `+`/`-`  after `=` is intentional._*",[],{"shortcode":3776,"title":3777,"description":3778,"category":15,"severity":2236,"tags":3779,"isRecommended":2323},"PTC-W0052","Field duplicates the name of its containing class","There is a class member with the same name (not considering the case difference) as its enclosing class.\n\n\u003C!--more-->\n\nThis can cause confusion while reading the code later on keeping a track of what the field represents.\nIt is strongly recommended to provide self-explanatory names so that someone who's reading the code doesn't have to spend time keeping a track of the variable/method names.\n\n### Not preferred:\n```python\nclass Orange:\n    '''We mean, the fruit.'''\n    orange = \"#FFA500\"\n    \n    # Other class implementations\n    \n    def get_orange(self):\n        return abc\n\nfruit = Orange()\nrender_to_frontend(fruit.orange)  # Rendering a color, but one can get confused with the fruit\nrender_bg(fruit.get_orange)  # Not clear that `get_orange` is returning a color\n```\n\n### Preferred:\n```python\nclass Orange:\n    '''We mean, the fruit.'''\n    color = \"#FFA500\"\n    \n    # Other class implementations\n    \n    def get_color(self):\n        return abc\n\nfruit = Orange()\nrender_to_frontend(fruit.color)  # Evident that we are working with color\nrender_bg(fruit.get_color)  # Evident that we are fetching the fruit's color\n```",[],{"shortcode":3781,"title":3782,"description":3783,"category":37,"severity":2236,"tags":3784,"isRecommended":2323},"PTC-W6003","Audit required: Sensitive cookie without `secure` attribute","Cookies set without the `secure` flag can be observed by an unauthorized person, leading to a man-in-the-middle attack.\n\n\u003C!--more-->\nGenerally, the production sites redirect any requests that are sent over HTTP to the same URL but on HTTPS.\nIn this case, make sure that these HTTP requests that are immediately redirected to HTTPS do not carry any cookie that contains sensitive information.\nThe `secure` flag limits cookies to HTTPS traffic only so, the browser will never send secure cookies with requests that are not encrypted.\n\n### Bad practice\n```python\n# The cookie is not secure here:\nsome_response.set_cookie('sensitive', 'some_value')\n```\n\n### Recommended\n```python\n# The cookie is secure here:\nsome_response.set_cookie('sensitive', 'some_value', secure=True)\n```\n\n## References:\n- [Secure Cookies](https://en.wikipedia.org/wiki/Secure_cookie)\n- Security considerations laid down in the [Flask Documentation](https://flask.palletsprojects.com/en/1.1.x/security/).\n- [OWASP Top 10:2021 > A02 - Cryptographic Failures](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/)\n- [CWE-314: Missing Encryption of Sensitive Data](https://cwe.mitre.org/data/definitions/311)\n- [CWE-315: Cleartext Storage of Sensitive Information in a Cookie](https://cwe.mitre.org/data/definitions/315)\n- [CWE-614: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute](https://cwe.mitre.org/data/definitions/614)\n\n## Exceptions:\nWhile this issue mostly makes sense if you're setting a sensitive cookie, DeepSource will flag all the cookies encountered without the `secure` flag.\nThis is to ensure that you are aware about all the cookies set, and avoid false negatives.",[1627,3785,3786,3787,3788,1204],"cwe-614","cwe-315","flask","cwe-314",{"shortcode":3790,"title":3791,"description":3792,"category":37,"severity":2236,"tags":3793,"isRecommended":2323},"PY-A6004","Audit required: Sensitive cookie without `httponly` attribute","Cookies set without the `httponly` flag can be read by a client-side script, leading to cookie theft from Cross-Site Scripting (XSS) attacks.\nWhen a cookie is created, the default value of `httponly` is `False`.\nIt is recommended to explicitly set `httponly` to `True` to prevent the risk.\n\n\u003C!--more-->\nCross-Site Scripting (XSS) attacks target the theft of session-cookies. If `httponly` attribute is set to `True`, it won't be possible to exploit the XSS vulnerability to steal session-cookies.\n\n### Bad practice\n```python\n# The cookie is not secure here:\nsome_response.set_cookie('sensitive', 'some_value')\n```\n\n### Recommended\n```python\n# The cookie is secure here:\nsome_response.set_cookie('sensitive', 'some_value', httponly=True)\n```\n\n## References:\n- Security considerations laid down in the [Flask Documentation](https://flask.palletsprojects.com/en/1.1.x/security/).\n- OWASP Top 10 2021 Category A05 - [Security Misconfiguration](https://owasp.org/Top10/A05_2021-Security_Misconfiguration/)\n- [Cross-Site Scripting (XSS) attacks are an OWASP top 10 security threat: Category A7](https://owasp.org/www-project-top-ten/2017/A7_2017-Cross-Site_Scripting_(XSS))\n- [OWASP HttpOnly](https://owasp.org/www-community/HttpOnly)\n- [CWE-1004](https://cwe.mitre.org/data/definitions/1004.html)\n\n## Exceptions:\nWhile this issue mostly makes sense if you're setting a sensitive cookie, DeepSource will flag all the cookies encountered without the `httponly` flag.\nThis is to ensure that you are aware of all the cookies being set and avoid false negatives.",[1647,1203,3794,3787,1704,1204],"cwe-1004",{"shortcode":3796,"title":3797,"description":3798,"category":19,"severity":2236,"tags":3799,"isRecommended":2323},"PTC-W0908","Use of `unique_for` constrant found","`unique_for_date/month/year` is very brittle and can be a source for unexpected behaviour.\n\n\u003C!--more-->\nThe unique_for_date/month/year constraint is enforced at the Django admin-form level but not at the database level. Checking will not occur if `Model.save()` is called without first calling `Model.validate_unique()`. Only the date portion of the field will be considered, even when validating a `DateTimeField`.\n\nRefer to the [docs](https://docs.djangoproject.com/en/3.1/ref/models/fields/#unique)\nto read more about `unique_for` constraint.\n\n### Bad practice\n```python\nfrom django.db import models\n\nclass MyModel(models.Model):\n    date = models.DateField()\n    somefield = models.CharField(unique_for_date='date')\n```\n\n### Recommended\n```python\nfrom django.db import models\n\nclass MyModel(models.Model):\n    date = models.DateField()\n    somefield = models.CharField()\n\n    def save(self, *args, **kwargs):\n        if self.objects.filter(date=self.date, somefield=self.somefield).exists():\n            raise ValidationError({'somefield': 'Value'})\n        return super().save(*args, **kwargs)\n```",[],{"shortcode":3801,"title":3802,"description":3803,"category":19,"severity":2236,"tags":3804,"isRecommended":2323},"PTC-W0061","Ambiguous augmented assignment","An augmented assign statement (such as `x += y`) is performed on the same assign variable, which looks ambiguous here.\nPlease verify if this was intended.\n\n\u003C!--more-->\nThe augmented assignment has the same operand on the left and right-hand sides.\nThis mostly looks like a bug due to an unnoticed typo.\nIf this is intentional, it can be refactored to use multiple self-assignment, to make the intention clear.\n\n### Bad practice\n```python\nmyvar += myvar + 1\n```\n\n### Recommended\n```python\n# If it was a typo:\nmyvar += 1\n\n# If this was intended:\n# if the data you're dealing with is a number,\n# consider using basic mathematical operation for better readability:\nmyvar = (2 * myvar) + 1\n```",[],{"shortcode":3806,"title":3807,"description":3808,"category":37,"severity":2236,"tags":3809,"isRecommended":2323},"PTC-W6004","Audit required: External control of file name or path","Python's `open()` function can take in a relative or absolute path and read its file contents.\nIf a user is provided direct access to the path that is opened, it can have serious security risks.\n\n### Bad practice\n\n```python\ndef read_file(path):\n    with open(os.path.join('some/path', path)) as f:\n        f.read()\n\n# Someone can exploit `read_file` and see your secrets this way:\nread_file('../../../secrets.txt')\n```\n\n### Recommended\n\nEither use a static path:\n\n```python\ndef read_file(path):\n    with open('some/path/to/file.txt') as f:\n        f.read()\n```\n\nOr, do some kind of validation to make sure you're not allowing arbitrary file access:\n\n```python\ndef read_file(filename):\n    if filename not in ('x.txt', 'y.txt'):\n        return 'Invalid filename'\n\n    with open(os.path.join('some/path', path)) as f:\n        f.read()\n```\n\n### References\n\n- OWASP Top 10 2021 Category A01 - [Broken Access Control](https://owasp.org/Top10/A01_2021-Broken_Access_Control/)\n- OWASP Top 10 2021 Category A04 - [Insecure Design](https://owasp.org/Top10/A04_2021-Insecure_Design/)\n- [CWE-73 External Control of File Name or Path](https://cwe.mitre.org/data/definitions/73.html)",[1647,3810,3811,1204,1361],"cwe-73","a01",{"shortcode":3813,"title":3814,"description":3815,"category":37,"severity":2236,"tags":3816,"isRecommended":2323},"PY-A6006","Audit required: Configuring loggers can be security-sensitive","This issue higlights code that initiates loggers configuration. This should be audited to make sure no sensitive information is being logged.\nSince this is an audit issue, some occurrences may be harmless here. The goal is to bring the issue in attention. Please take a look at the `Audit Checklist` mentioned later in the description.\nIf the occurrences doesn't seem to be valid, please feel free to ignore them.\n\u003C!--more-->\n\nThe configuration determines the type of information logged and how it is logged.\nLogs might contain sensitive information which can be used by malicious users. But they should contain sufficient information to understand the damage an attacker might have inflicted.\n\n**Audit Checklist**:\nMake sure these points are taken care of:\n\n- Logs doesn't contain sensitive information. This can happen when the logger is in the `debug` mode.\n- Logs aren't growing without limit. This happens when additional information is written into logs every time a user performs an action and the user can perform the action any number of times.\n- Logs contain enough information to understand the damage, in case there's a security incident.\n- Log format is easy to parse and process automatically. Processing logs rapidly is important in case of an attack.\n- Logs are stored in a secure location which is only accessible to system administrators.\n\n### Bad practice\n```python\nimport logging\nimport os\n\nfrom logging.config import fileConfig, dictConfig\n\nlogging.basicConfig(level=os.environ.get(\"LOGLEVEL\", \"INFO\"))\nfileConfig(fname='file.conf', disable_existing_loggers=False)  # Disabling the loggers.\ndictConfig(config)  # Configuring a logger shoud be audited.\n\nlogging.disable() # Disabling the logger.\n\nclass SomeLogger(logging.Logger):  # A custom logger implementation shoud be audited\n    ...\n\ndef set_logger_class(logger_class):\n    logging.setLoggerClass(logger_class)  # A custom logger implementation shoud be audited\n\ndef set_logging_last_resort(last_resort):\n    logging.lastResort = last_resort  # Hints the absence of any logging configuration. It is recommended to set up logging properly.\n```\n\n## References:\n- OWASP Top 10 2021 Category A09 - [Security Logging and Monitoring Failures](https://owasp.org/Top10/A09_2021-Security_Logging_and_Monitoring_Failures/)\n- [CWE 532](https://cwe.mitre.org/data/definitions/532.html) - Insertion of Sensitive Information into Log File\n- [CWE 778](https://cwe.mitre.org/data/definitions/778.html) - Insufficient logging",[1647,3817,3818,3819,1704,1204],"cwe-532","a09","cwe-778",{"shortcode":3821,"title":3822,"description":3823,"category":31,"severity":2236,"tags":3824,"isRecommended":2323},"PYL-R1728","Redundant list comprehension can be replaced using generator","Using a container in place of a generator for a calls that can accept both, slows down the performance. Consider using generators for all function calls which accept both containers and genertors.\n\n\u003C!-- more -->\n\n### Bad practice\n\n```python\n# List comprehension is unnecessary here\nset([student.name for student in student])\nsum([y**2 for y in list(range(10))])\n```\n\n### Recommended\n\n```python\nset(student.name for student in students)\nsum(y**2 for y in list(range(10)))\n```",[],{"shortcode":3826,"title":3827,"description":3828,"category":31,"severity":2236,"tags":3829,"isRecommended":2323},"PYL-C0209","Consider using f-strings","f-strings are the fastest way to format strings as compared to the following methods:\n\n* using format specifiers `%`\n* using `format()`\n* using `str.join`\n* using `+` operator to concatinate string\n* using `Template.substitute`\n\n\u003C!-- more -->\n\n### Bad practice\n\nSome less preferred ways to format strings are the following:\n\n```python\nfrom string import Template\n\nmenu = ('eggs', 'spam', 42.4)\n\nold_order = \"%s and %s: %.2f ¤\" % menu # [consider-using-f-string]\nbeginner_order = menu[0] + \" and \" + menu[1] + \": \" + str(menu[2]) + \" ¤\"\njoined_order = \" and \".join(menu[:2])\nformat_order = \"{} and {}: {:0.2f} ¤\".format(menu[0], menu[1], menu[2])\nnamed_format_order = \"{eggs} and {spam}: {price:0.2f} ¤\".format(eggs=menu[0], spam=menu[1], price=menu[2])\ntemplate_order = Template('$eggs and $spam: $price ¤').substitute(eggs=menu[0], spam=menu[1], price=menu[2])\n```\n\n### Recommended\n\nConsider using f-strings as shown below:\n\n```python\nmenu = ('eggs', 'spam', 42.4)\n\nf_string_order = f\"{menu[0]} and {menu[1]}: {menu[2]:0.2f} ¤\"\n```",[],{"shortcode":3831,"title":3832,"description":3833,"category":41,"severity":2236,"tags":3834,"isRecommended":2323},"PYL-W1114","Positional arguments are out of order","Positional arguments (with the same name as function parameters) appear to be out of order. Ensure that the order of arguments passed is correct.\n\n\u003C!-- more -->\n\n### Bad practice\n\n```python\ndef func_with_two_args(arg_one, arg_two):\n    ...\n\narg_one = 1\narg_two = 2\nfunc_with_two_args(arg_two, arg_one)\n```\n\n### Recommended\n\n```python\ndef func_with_two_args(arg_one, arg_two):\n    ...\n\narg_one = 1\narg_two = 2\nfunc_with_two_args(arg_one, arg_two)\n\n```",[],{"shortcode":3836,"title":3837,"description":3838,"category":31,"severity":2236,"tags":3839,"isRecommended":2323},"PYL-W1202","Lazy formatting of message string passed to logging module","Formatting the message manually before passing it to a `logging` call does unnecessary work if logging in disabled. Consider using the `logging` module's built-in formatting features to avoid that.\n\n\u003C!-- more -->\n\n### Bad practice\n\n```python\nimport logging, inspect\n\nlogging.basicConfig(level=logging.INFO)\nlogging.debug(\"Entered function {}\".format(inspect.stack[0][3]))\n```\n\n### Recommended\n\n```python\nimport logging, inspect\n\nlogging.basicConfig(level=logging.INFO)\nlogging.debug(\"Entered function %s\", inspect.stack[0][3])\n```",[],{"shortcode":3841,"title":3842,"description":3843,"category":31,"severity":2236,"tags":3844,"isRecommended":2323},"PYL-W1203","Formatted string passed to logging module","Formatting the message manually before passing it to a `logging` call does unnecessary work if logging is disabled. Consider using the `logging` module's built-in formatting features to avoid that.\n\n\u003C!-- more -->\n\nIf your logging level is set to `\"WARNING\"`, but the logging call is:\n\n```python\nlogging.debug(\"Data: %s\", data)\n```\n\nIn the above example, there will be no logging as the level `debug` is below `warning`. The conversion of the `data` object to a string will be skipped by the logging module resulting in _improved performance_.\n\n```python\nlogging.debug(f\"Data: {data}\")\n```\n\nIn the code shown above, the conversion of the `data` object to a string will happen regardless of whether the message is logged or not (which is based on the log level).\n\n### Bad practice\n\n```python\nimport logging\nimport inspect\nlogging.basicConfig(level=logging.INFO)\nlogging.debug(f\"Entered function {inspect.stack[0][3]}\"))\n```\n\n### Recommended\n\n```python\nimport logging\nimport inspect\nlogging.basicConfig(level=logging.INFO)\nlogging.debug(\"Entered function %s\", inspect.stack[0][3])\n```",[],1791870539174]