Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions hello1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import random
import pdb

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`pdb` import retains debugging code in production


The import statement import pdb brings in the Python debugger, which may lead to accidental invocation of interactive debugging sessions in production or shared code, disrupting execution and revealing internal states.
Remove the import pdb statement from committed code to ensure debuggers are only used temporarily during development.

import sys as sys

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`import sys as sys` uses unnecessary alias identical to original module


Using import sys as sys creates an alias identical to the original module name, which is redundant and unnecessary. It adds clutter without any benefit and may confuse maintainers about the intent.
Remove the alias and use a straightforward import sys statement instead, which is simpler and more readable.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused `sys` import increases code clutter


The sys module is imported as sys but is not used anywhere in the module, which adds unnecessary clutter and can confuse maintainers or static analysis tools. Unused imports slightly increase load time and reduce code clarity.

Remove the unused import statement import sys as sys to clean up the code and improve maintainability.

import os
import subprocess
import abc

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused `abc` import adds unnecessary code clutter


The abc import statement is redundant since the module does not use it, leading to unnecessary clutter and possibly confusing developers about its purpose. Removing such unused imports improves code clarity and reduces maintenance overhead.

Remove the unused abc import to clean up the module and improve readability without affecting functionality.


# from django.db.models.expressions import RawSQL

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commented out code blocks increase clutter


The commented out import statement for RawSQL is redundant and serves no functional purpose. Such commented code increases technical debt by cluttering the file, distracting developers and slowing code comprehension.
Remove the commented out code to clean and simplify the codebase, improving maintainability and clarity.


AWS_SECRET_KEY = "d6s$f9g!j8mg7hw?n&2"


class BaseNumberGenerator:
"""Declare a method -- `get_number`."""

def __init__(self):
self.limits = (1, 10)

def get_number(self, min_max):
raise NotImplemented

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`raise NotImplemented` triggers `TypeError` instead of intended signal


Using raise NotImplemented raises a different runtime error than intended. Callers receive a TypeError, obscuring that subclass implementation is required.

Replace with raise NotImplementedError() to communicate unsupported abstract behavior correctly


def smethod():
"""static method-to-be"""

smethod = staticmethod(smethod)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assigning `staticmethod` instead of using `@staticmethod` decorator


The line smethod = staticmethod(smethod) statically binds the method but lacks the clarity and conciseness of the @staticmethod decorator. This older style can decrease code readability and maintainability.
Use the @staticmethod decorator placed directly before the method definition to declare static methods in a clear and idiomatic way.


def cmethod(cls, something):
"""class method-to-be"""

cmethod = classmethod(cmethod)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using `classmethod()` assignment misses decorator benefits


Manually assigning cmethod = classmethod(cmethod) marks the method as a class method but lacks the clarity and built-in tooling benefits of the @classmethod decorator. This can confuse readers and prevent some linting features.
Use the @classmethod decorator directly above the method definition to clearly indicate its purpose and improve code readability and maintainability.



class RandomNumberGenerator:
"""Generate random numbers."""

def limits(self):
return self.limits

def get_number(self, min_max=[1, 10]):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mutable list `min_max` as default causes shared state


The min_max parameter defaults to a list [1, 10] which is mutable. If this list is modified inside the method, changes persist across function calls, resulting in shared state and potential hard-to-find bugs.

Replace the mutable default with None and initialize a new list inside the method to ensure each call uses a fresh object, preventing unintentional data sharing.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Method without `self` usage should be `@staticmethod`


The get_number method includes the self parameter but does not utilize it, causing Python to bind this method to each instance. This consumes additional memory and slows method calls.
Decorate the method with @staticmethod and remove the self parameter to prevent binding and improve performance.

"""Get a random number between min and max."""
assert all([isinstance(i, int) for i in min_max])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`assert` removed on optimization risks skipping checks


The assert statement on line 41 validates all elements in min_max as integers, but if Python runs with optimizations enabled (-O flag), this assert statement is removed, disabling the check and risking unchecked invalid data usage.
Replace the assert with an explicit if statement followed by raising an appropriate exception, such as TypeError or ValueError, to ensure the validation is always performed regardless of optimization settings.

return random.randint(*min_max)


def main(options: dict = {}) -> str:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using mutable `dict` as default causes shared state


The main function uses a mutable dictionary as a default argument, which is evaluated only once at function definition. This causes the same dictionary to be shared among all calls to main, leading to unexpected side effects and bugs.

Replace the mutable default with None and initialize options inside the function to a new dictionary if it is None. This prevents state leakage between calls.

pdb.set_trace()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`pdb.set_trace()` enables interactive runtime takeover


pdb.set_trace() stops execution and opens an interactive debugger. In deployed jobs or services, this can leak sensitive runtime data and allow unintended command execution paths.

Remove pdb.set_trace() or guard it behind an explicit development-only flag

if "run" in options:
value = options["run"]
else:
value = "default_value"

if type(value) != str:
raise Exception()
else:
value = iter(value)

sorted(value, key=lambda k: len(k))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lambda calling `len` without modification is redundant


The lambda expression lambda k: len(k) in the sorted call does nothing more than call the built-in len function directly. This redundancy clutters the code and makes debugging harder since lambdas show as <lambda> in tracebacks.
Replace the lambda with the direct function reference len in the sorted call to improve readability and debugging clarity.


f = open("/tmp/.deepsource.toml", "r")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using `open()` without `with` risks resource leaks


Opening a file using open() without a with statement means the file resource may not be released promptly, especially if exceptions occur, causing resource leaks or file locking issues. The variable f is assigned the file handle but may never be closed explicitly.
Use the with open() context manager to ensure the file is automatically closed after use, even if errors arise during file operations.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hardcoded `/tmp/.deepsource.toml` risks symlink hijacking


Hardcoding the filename /tmp/.deepsource.toml enables attackers to anticipate and pre-create symbolic links with that filename, potentially redirecting file operations to malicious targets. This can lead to data corruption or execution of attacker-controlled files.

Use the tempfile module's secure APIs like TemporaryFile for creating temporary files with unpredictable names that are safely cleaned up after use, avoiding predictable file paths in /tmp.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Local variable `f` shadows outer scope variable


The variable f is defined locally within a function or scope, but it shadows a variable named f from an outer scope. This makes the outer variable inaccessible within this local context and can cause confusion or bugs if the outer variable was intended to be used.

Rename the local variable f to a more specific name or restructure the code to avoid using the same variable name in nested scopes to maintain clarity and prevent shadowing issues.

f.write("config file.")
Comment on lines +59 to +60

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`open(..., "r")` with `write()` raises runtime exception


The handle is opened with read-only mode then written to immediately. This fails every run and prevents later logic in main from executing.

Open with write-capable mode and context management, e.g. with open(path, "w") as f:

f.close()


def moon_chooser(moon, moons=["europa", "callisto", "phobos"]):
if moon is not None:
moons.append(moon)
Comment on lines +64 to +66

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`moons=[...]` accumulates values between calls


The default list is shared globally for the function lifetime. Appending moon mutates future-call inputs and creates hidden state coupling.

Use None default and create a fresh list inside before appending


return random.choice(moons)


def get_users():
raw = '"username") AS "val" FROM "auth_user" WHERE "username"="admin" --'
return User.objects.annotate(val=RawSQL(raw, []))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`User` and `RawSQL` unresolved names crash execution


get_users references User and RawSQL without defining or importing them. The function fails immediately, so callers cannot retrieve users.

Add explicit imports for User and RawSQL, or replace with ORM-native query constructs already available



def tar_something():
os.tempnam("dir1")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`os.tempnam()` enables symlink attacks allowing file hijacking


The use of os.tempnam() generates a temporary filename that can be predicted or intercepted by attackers via symbolic links, enabling file hijacking or data manipulation. This exposes the application to potential security breaches through race conditions or file access vulnerabilities.

Replace os.tempnam() with safer alternatives like os.tmpfile() or use tempfile module functions which securely create temporary files and avoid race conditions.

subprocess.Popen("/bin/chown *", shell=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`subprocess.Popen(..., shell=True)` permits shell interpretation risks


subprocess.Popen with shell=True runs a shell parser, so metacharacters and wildcard expansion affect command semantics. In privileged contexts, crafted filenames can alter chown arguments unexpectedly.

Replace with argument-list execution and disable shell parsing

o.system("/bin/tar xvzf *")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`o.system` causes `NameError` at runtime


The call uses o.system even though only os is imported. This throws NameError and breaks tar_something every execution.

Replace o.system with os.system or preferably subprocess.run with argument lists



def bad_isinstance(initial_condition, object, other_obj, foo, bar, baz):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redefining builtin `object` disables its usage causing errors


The function defines a parameter named object, which shadows the Python builtin object. This prevents the use of the original object type or function inside the function, potentially causing unexpected behavior or errors.

Rename the parameter to a non-builtin name like obj or another descriptive identifier to restore access to the builtin object within the function.

if (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty `if` block implies missing code or logic


The if statement without a body means the program does nothing when the condition is met, leading to logical errors or missed operations. This could cause incorrect program flow or unhandled cases.

Add meaningful code inside the if block or remove the conditional check if not needed to ensure the intended logic is implemented properly.

initial_condition
and (
isinstance(object, int)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Separate `isinstance` calls reduce readability


Multiple consecutive isinstance calls checking the same object with different types should be merged. This improves code clarity by reducing redundancy and makes the intent clearer.

Replace multiple calls like isinstance(object, int) or isinstance(object, float) with a single call: isinstance(object, (int, float)).

or isinstance(object, float)
or isinstance(object, str)
)
and isinstance(other_obj, float)
and isinstance(foo, str)
or (isinstance(bar, float) or isinstance(bar, str))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multiple `isinstance` calls reduce clarity and readability


The code uses multiple isinstance calls combined with or to check if bar is a float or a str. This approach reduces readability and makes the condition unnecessarily verbose. Using isinstance(bar, (float, str)) achieves the same effect more clearly and succinctly.

Replace the multiple isinstance calls with a single isinstance call passing a tuple of the types float and str to improve code clarity and maintainability.

and (isinstance(baz, float) or isinstance(baz, int))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Separate `isinstance` calls reduce clarity and readability


The code uses two separate isinstance calls for float and int on variable baz joined by or, which is redundant and lowers readability. This pattern is less clear than a single call with a tuple of types, and it increases the potential for errors when extending type checks.

Replace the consecutive calls with a single isinstance(baz, (float, int)) call to improve readability and maintainability.

):
pass


def check(x):
if x == 1 or x == 2 or x == 3:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Repeated `or` equality checks slow performance and reduce clarity


The code uses multiple or conditions to check if x equals 1, 2, or 3, which leads to slower evaluation and less readable code as it requires separately evaluating each comparison. This pattern increases cognitive load when reading and executing.

Replace the chained equality checks with a single membership test like if x in (1, 2, 3): to improve performance and simplify code readability.

print("Yes")
elif x != 2 or x != 3:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`x != 2 or x != 3` makes later `elif` unreachable


The boolean expression is tautological, so control always enters this branch when previous if fails. Later elif blocks become dead code and intended behavior is lost.

Replace with x != 2 and x != 3 or invert using x not in (2, 3)

print("also true")

elif x in (2, 3) or x in (5, 4):
print("Here")

elif x == 10 or x == 20 or x == 30 and x == 40:
print("Sweet!")

elif x == 10 or x == 20 or x == 30:
print("Why even?")

def chained_comparison():
a = 1
b = 2
c = 3
return a < b and b < c

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chained comparison `a < b < c` improves readability


The code uses the boolean operation a < b and b < c, which is redundant for chaining comparisons. This form is less readable and more verbose than the chained comparison.

Refactor to use a < b < c to improve readability and simplify the expression without changing logic.


if __name__ == "__main__":
args = ["--disable", "all"]
f = open("/tmp/.deepsource.toml", "r")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hardcoded temp path risks file hijacking


Using a hardcoded temporary filename like /tmp/.deepsource.toml is unsafe because attackers can predict and pre-create this file or symlink, resulting in hijacking or corruption of program file actions.

Use the Python tempfile module to safely create temporary files with unpredictable names and automatic cleanup to avoid these vulnerabilities.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`open()` without `with` risks resource leaks


Opening a file with open() without a with block means the file remains open until explicitly closed, risking resource leaks and file handle exhaustion. The file handle f in the code remains open past its usage, potentially blocking other operations.

Use the with open() as f: syntax to automatically manage file closing and resource release after block execution, ensuring safer and cleaner resource management.

f.write("config file.")
Comment on lines +121 to +122

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`open(..., "r")` with `write()` raises runtime exception


Startup code opens the file in read-only mode and immediately writes, causing an exception before argument processing completes. This makes the script fail deterministically.

Replace with with open("/tmp/.deepsource.toml", "w") as f: before writing

f.close()
assert args is not None
for i in range(len(args)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`range(len(...))` usage is non-pythonic and verbose


Using range(len(args)) manually creates an index sequence for iteration, which is verbose and less readable. It can lead to off-by-one errors and is generally discouraged in Python. This pattern appears at line 125 in the loop over args.
Replace for i in range(len(args)): with for i, arg in enumerate(args): to iterate more pythonically and access both index and element directly.

has_truthy = True if args[i] else False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`if` expression can be simplified to `bool()` conversion


The assignment has_truthy = True if args[i] else False explicitly checks the condition and returns True or False, which is redundant since args[i] itself is truthy or falsy. This verbose pattern reduces code readability.
Simplify the expression by using has_truthy = bool(args[i]), which converts args[i] directly into a boolean value, making the code clearer and more concise.

assert has_truthy is not None
if has_truthy:
break
Loading