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 risks accidental debugger activation


The pdb module is imported, which is a debugger intended for development and testing only. Accidental use or breakpoints can halt application execution and disrupt production environments.
Remove the import pdb statement from production code or restrict its usage to development-only contexts by conditional imports or environment checks.

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` is redundant and unnecessary


The import statement import sys as sys uses an alias that is identical to the module name sys, which is redundant and does not simplify or clarify usage. This redundancy can confuse readers or maintainers by implying a different alias is intended.

Remove the alias and use import sys directly to keep the code clean and clear.

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 not used anywhere in the code, which unnecessarily increases code clutter and can confuse maintainers or static analysis tools. Unused imports can also slightly impact load times or analysis performance.
Remove the unused sys import statement to clean up and simplify the codebase.

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 increases code clutter


The abc module is imported but not used anywhere in the module, introducing unnecessary clutter and potential confusion for maintainers. Unused imports can also slightly degrade code readability and increase the cognitive load.

Remove the unused abc import statement to clean up the code and simplify maintenance.


# 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 clutter codebase


Commented out code like the commented import statement for RawSQL on line 8 adds clutter and reduces code clarity. It can confuse maintainers about whether the code is needed or obsolete.
Remove the commented import statement to keep the codebase clean and maintainable.


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


raise NotImplemented does not produce the expected abstract-method failure. Python raises TypeError, masking intent and confusing callers.

Replace with raise NotImplementedError() for correct behavior.


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.

`staticmethod` used without `@staticmethod` decorator


Assigning staticmethod to smethod directly (e.g., smethod = staticmethod(smethod)) works but is less readable and unconventional. It can confuse maintainers and reduces code clarity.

Use the @staticmethod decorator above the method definition instead of assignment to explicitly mark static methods, improving readability and adhering to modern Python style conventions.


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()` function instead of `@classmethod` decorator


The code uses the classmethod() function to convert cmethod into a class method rather than using the @classmethod decorator syntax. This pattern is less readable, less idiomatic, and can confuse maintainers accustomed to decorator usage.

Replace the assignment cmethod = classmethod(cmethod) with the @classmethod decorator above the method definition. This improves clarity and follows modern Python standards.



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.

Instance method `get_number` unused; wastes memory and computation


The method get_number is defined with self but does not use any instance variables or methods, meaning it behaves like a static method. Binding it to an instance causes unnecessary memory and computation overhead for every class instance.
Use the @staticmethod decorator to define the method as static, which removes the need for binding and improves performance and memory usage.

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 default argument like `list` risks shared state


The get_number method has a mutable default argument min_max initialized to [1, 10]. Because default arguments in Python are evaluated once at definition, modifications to min_max in one call affect all subsequent calls, causing shared state bugs. This can lead to unpredictable and incorrect function outputs when min_max is mutated.

Replace the default argument with None and set min_max to [1, 10] inside the method if it is None. This ensures a fresh list for each call, preventing state leakage between calls.

"""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.

Using `assert` in production removes checks when optimized


Using assert for runtime validation in application logic is unsafe because Python removes these statements when the -O or -OO flags are used during execution. This causes the check on min_max elements to be bypassed, potentially allowing invalid or malicious input to pass.

Replace assert with explicit conditional checks and raise exceptions like TypeError or ValueError to enforce validation consistently, regardless of optimization flags.

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.

Mutable `options` as default causes shared state


The default argument options is a mutable dictionary initialized once at function definition. Subsequent calls mutate the same dictionary, causing shared state and erratic results when main() is called multiple times.

Replace the default options={} with options=None and initialize an empty dictionary inside the function to avoid persistent shared state across 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 execution hijacking


pdb.set_trace() pauses execution and opens an interactive prompt. In deployed environments, this can leak sensitive runtime data and permit command execution by anyone with terminal access.

Remove pdb.set_trace() or gate it behind a strict debug-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 k: len(k)` duplicates built-in `len` function


The lambda expression lambda k: len(k) in the sorted call merely wraps the built-in len function without modification. This duplication adds unnecessary overhead and obscures the intent in diagnostics or debugging since tracebacks show <lambda> instead of a meaningful function name. Use len directly as the key in sorted to improve readability and debugging clarity.

Replace the lambda expression with the direct built-in function len when passing it to sorted as the key parameter.


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 `open('/tmp/.deepsource.toml')` risks file hijacking


The code opens a hardcoded temporary file path /tmp/.deepsource.toml, which is predictable and can be preemptively created or replaced by an attacker, resulting in unintended file manipulation or data leaks. This security risk exposes the program to tampering and exploitation by malicious users.
Replace open('/tmp/.deepsource.toml', 'r') with tempfile.TemporaryFile() or other tempfile module functions. These securely create unpredictable temporary files and clean them up automatically, preventing file hijacking.

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 local variable f defined by open("/tmp/.deepsource.toml", "r") shadows any variable named f from an outer scope, which may lead to unexpected behavior since the outer variable becomes inaccessible in this scope. This can cause bugs if the outer f was intended to be used later or elsewhere.

Rename the local variable to a more descriptive and unique name or limit variable scope by restructuring code to avoid such shadowing, like using different variable names or enclosing logic inside functions.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

File opened without `with` risks resource leaks


The file at /tmp/.deepsource.toml is opened using open() without the with context manager, which can cause the file descriptor to remain open if not manually closed. This risks exhausting system resources or causing file access issues during runtime.
Use the with statement to open the file, ensuring automatic closing of the file descriptor once the block is exited even if exceptions occur.

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")` then `write()` raises runtime exception


open("/tmp/.deepsource.toml", "r") creates a read-only stream, but code immediately calls f.write(...). This reliably throws and aborts execution.

Open with writable mode using a context manager, e.g. with open(..., "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=[...]` persists appended values between calls


The default moons list is reused for every call, and moons.append(moon) mutates it. Call results become order-dependent and leak prior inputs across invocations.

Use None default and create a fresh list per call.


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.

Undefined `raw` variable causes runtime error


The variable raw is used as an argument in the RawSQL function call but it is not defined or imported anywhere in the visible code, which will cause a NameError at runtime. This breaks the function or feature relying on this code.
Define or import the variable raw before its usage or replace it with the intended query string to fix the error.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Use of undefined `RawSQL` causes runtime NameError


The code attempts to use RawSQL in the annotation without importing or defining it, causing a NameError at runtime. This prevents the code from executing as intended and breaks functionality.

Ensure RawSQL is imported from the correct module (e.g., django.db.models.expressions) or defined before usage to fix the error.



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 risking file compromise


Using os.tempnam() exposes the system to symlink attacks since it generates filenames without atomic creation, allowing attackers to exploit race conditions. This can lead to unauthorized file access, tampering, or overwriting in sensitive operations.
Use os.tmpfile() or tempfile module functions that safely create temporary files atomically to avoid race conditions and improve security.

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)` enables shell metacharacter abuse


subprocess.Popen("/bin/chown *", shell=True) executes via shell parsing. Wildcard expansion and shell semantics let crafted filenames influence command arguments and can lead to command abuse.

Replace with argument-list invocation 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.

Undefined `o` causes runtime error


The snippet calls o.system without o being defined anywhere prior, causing a runtime NameError that halts execution. This indicates either a typo or a missing import such as import os as o.

Define or import o to a valid object like import os and use os.system instead of o.system to fix the error.



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 `object` disables builtin `object` usage


The function parameter named object shadows the Python builtin object function, making it inaccessible within the function. This can cause confusion and errors if the builtin object is needed.

Rename the parameter object to a non-builtin name such as obj or item to retain access to the builtin object and avoid naming conflicts.

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 indicates missing code or logic


The presence of an empty if block suggests that intended logic or code was never implemented, which can lead to unexpected behavior or logical errors in program flow. The code execution reaches this point but performs no action, which might cause functional issues.

Add meaningful code inside the if block or remove the condition block entirely if it is unnecessary to ensure correct and clear program behavior.

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 clarity and readability


Multiple isinstance calls on the same object for checking different types reduce code clarity and readability. For example, separate calls like isinstance(object, int) or isinstance(object, float) are less clear.

Merge all types into one call using a tuple, e.g., isinstance(object, (int, float)). This improves readability and makes the intent explicit without redundant checks.

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 on `bar` reduce readability


Multiple isinstance calls combined with or on the same variable bar create verbose and less readable code. This approach duplicates effort and can confuse readers about the intent.

Merge the types into a tuple and call isinstance(bar, (float, str)) once to improve 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.

Multiple `isinstance` calls reduce code clarity


The code uses two separate isinstance calls for float and int combined with or, which is redundant. This pattern makes the code longer and less clear.

Merge the isinstance checks into a single call using a tuple, such as isinstance(baz, (float, int)), to enhance clarity and conciseness.

):
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` comparisons reduce performance and clarity


The code uses repeated or clauses (x == 1 or x == 2 or x == 3) which results in multiple equality checks at runtime, slowing execution and reducing readability. This pattern is less maintainable as the list of values grows.

Replace the repeated or conditions with a single membership test using in and a tuple (x in (1, 2, 3)) to improve performance and clarity.

print("Yes")
elif x != 2 or x != 3:
print("also true")
Comment on lines +101 to +102

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 subsequent branches unreachable


elif x != 2 or x != 3 is a tautology. It captures all remaining values, making following conditions dead code and hiding logic errors.

Replace with and (x != 2 and x != 3) or rewrite using membership checks.


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:

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 reduce readability and speed


The condition x == 10 or x == 20 or x == 30 performs separate equality checks for each value, which is less efficient and harder to read. This can lead to longer execution times and more error-prone code in complex conditions.
Replace the repeated or comparisons with x in (10, 20, 30) to leverage Python's optimized membership test. This improves readability and performance by checking membership in a single operation.

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 expression a < b and b < c uses two separate comparisons combined with and, which works correctly but is less readable and concise. Using chained comparison a < b < c expresses the intended logic more clearly and is idiomatic in Python.

Replace a < b and b < c with a < b < c to improve code readability and follow Python best practices.


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 `/tmp` path risks file hijacking attacks


Hardcoding the path /tmp/.deepsource.toml allows attackers to predict and create or replace this file before the program opens it, enabling arbitrary file manipulation or injection. This vulnerability is due to lack of randomness and atomic creation of temporary files.

Use tempfile.TemporaryFile() or tempfile.NamedTemporaryFile() instead, which securely create temporary files with randomized names and proper permissions to prevent hijacking and race conditions.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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


Using open() without a with statement means the file resource won't be automatically closed, potentially causing resource leaks or file handle exhaustion if an explicit close() isn't called. This can affect system stability and file accessibility.
Use a with open('/tmp/.deepsource.toml', 'r') as f: block to ensure the file is properly closed after use, automatically releasing resources.

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()` crashes startup path


The __main__ block repeats a read-only open followed by write(). Running the script directly will fail before argument processing.

Replace with with open(..., "w") or "a" based on intended behavior.

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.

Using `range(len(...))` causes non-pythonic index loops


Using range(len(args)) forces manual indexing and iteration which is not idiomatic Python and can lead to errors or less readable code. It misses the benefits of iterator protocols that Python embraces.

Replace for i in range(len(args)): with for i, element in enumerate(args): to leverage Python's native iterator and counter combination for clarity and efficiency.

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` conditional expression can be replaced by `bool()` conversion


The code uses a conditional expression True if args[i] else False which redundantly checks the truthiness of args[i] to return a boolean value. This is unnecessarily verbose and can be replaced by the simpler and more direct bool(args[i]), which achieves the same result.

Replace the conditional expression with bool(args[i]) to make the code more concise and readable, improving maintainability without changing behavior.

assert has_truthy is not None
if has_truthy:
break
Loading