Skip to content

Switchout hasattr for getattr wherever possible #1605

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 26, 2025

Conversation

rhatdan
Copy link
Member

@rhatdan rhatdan commented Jun 25, 2025

This greatly simplifies the code logic.

Summary by Sourcery

Enhancements:

  • Replace hasattr checks with getattr calls providing default values in ramalama/engine.py, model.py, quadlet.py, kube.py, model_factory.py, cli.py, oci.py, and stack.py to streamline argument handling logic

Copy link
Contributor

sourcery-ai bot commented Jun 25, 2025

Reviewer's Guide

This PR refactors conditional attribute existence checks across the codebase by replacing repetitive hasattr patterns with concise getattr calls and default values, simplifying argument parsing, option handling, and constructor fallbacks.

Class diagram for updated argument attribute access patterns

classDiagram
    class Engine {
        +args
        +exec_args
        +add_pull_newer()
        +add_network()
        +add_oci_runtime()
        +add_privileged_options()
        +cap_add(cap)
        +use_tty()
        +add_subcommand_env()
        +add_env_option()
        +add_tty_option()
        +add_detach_option()
        +add_port_option()
        +add_device_options()
        +add_rag()
        +handle_podman_specifics()
        +add(newargs)
    }
    class Model {
        +remove(args)
        +get_container_name(args)
        +base(args, name)
        +add_oci_runtime(conman_args, args)
        +add_rag(exec_args, args)
        +exec_model_in_container(model_path, cmd_args, args)
        +setup_mounts(model_path, args)
        +build_exec_args_bench(args, model_path)
        +validate_args(args)
        +vllm_serve(args, exec_model_path)
        +llama_serve(args, exec_model_path, chat_template_path, mmproj_path)
        +handle_runtime(args, exec_args, exec_model_path)
        +serve(args, quiet=False)
    }
    class Quadlet {
        +ai_image
        +name
        +args
        +exec_args
        +_gen_image(name, image)
        +_gen_name(quadlet_file)
        +_gen_model_volume(quadlet_file)
        +_gen_port(quadlet_file)
        +_gen_rag_volume(quadlet_file)
    }
    class Kube {
        +ai_image
        +name
        +args
        +exec_args
    }
    class ModelFactory {
        +pruned_model
        +draft_model
        +split_model
        +mnt_path
        +create_url()
    }
    class Stack {
        +args
        +name
        +host
    }
    Engine --> Model
    ModelFactory --> Model
    Quadlet --> Model
    Kube --> Model
    Stack --> Engine
    Stack --> Model
    Stack --> Quadlet
    Stack --> Kube
    Stack --> ModelFactory
Loading

File-Level Changes

Change Details Files
Consolidated argument flag checks using getattr defaults
  • Replaced hasattr(self.args, X) and self.args.X with getattr(self.args, X, default) in various add_* and handler methods
  • Simplified truthiness checks for flags such as network, oci_runtime, privileged, detach, rag, port, device, noheading, notrunc, webui, runtime_args
  • Unified label-adding logic to use getattr(args, arg, None) instead of nested hasattr guards
ramalama/engine.py
ramalama/model.py
ramalama/cli.py
ramalama/oci.py
ramalama/model_factory.py
Streamlined list iteration for optional collections
  • Replaced conditional iteration over env list with for env in getattr(args, 'env', [])
  • Ensured safe handling of device and runtime_args lists via getattr defaults
ramalama/engine.py
Refactored constructor assignments with default fallbacks
  • Used getattr(args, 'MODEL', model) to assign ai_image in Quadlet and Kube classes
  • Simplified name assignment using getattr(args, 'name', None) or genname() in Quadlet, Kube, and Stack
ramalama/quadlet.py
ramalama/kube.py
ramalama/stack.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @rhatdan, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request primarily focuses on refactoring the codebase to replace instances of hasattr() checks followed by attribute access with the more Pythonic and often cleaner getattr() function. While the main intent is to simplify code logic and improve readability, a detailed review of the changes reveals several instances where the conversion has inadvertently altered the original conditional behavior, which could lead to different program execution paths under specific conditions.

Highlights

  • Code Modernization and Readability: Replaced numerous hasattr(obj, 'attr') and obj.attr patterns with the more concise and Pythonic getattr(obj, 'attr', default_value) across the codebase. This improves readability and reduces boilerplate.
  • Consistent Attribute Access: Standardized the way optional or potentially missing attributes are handled, leveraging getattr's ability to provide a fallback value.
  • Introduced Behavioral Changes: Several instances of hasattr to getattr conversion have subtly, or in some cases, significantly altered the original conditional logic. These changes affect how certain command-line arguments or object attributes are interpreted, potentially leading to different execution paths than before. Specific examples include logic related to nocapdrop, ARGS, subcommand, port, rag, and name attributes in various modules.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @rhatdan - I've reviewed your changes - here's some feedback:

  • Consider extracting a helper (e.g. arg_val(name, default)) to encapsulate the repeated getattr(self.args, ..., default) pattern and reduce duplication.
  • Verify that each default passed to getattr preserves the original truthiness semantics (e.g. distinguishing empty string vs None) to avoid unintended behavior changes.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider extracting a helper (e.g. `arg_val(name, default)`) to encapsulate the repeated `getattr(self.args, ..., default)` pattern and reduce duplication.
- Verify that each default passed to `getattr` preserves the original truthiness semantics (e.g. distinguishing empty string vs `None`) to avoid unintended behavior changes.

## Individual Comments

### Comment 1
<location> `ramalama/engine.py:80` </location>
<code_context>
                 "--security-opt=label=disable",
             ]
-            if not hasattr(self.args, "nocapdrop"):
+            if getattr(self.args, "nocapdrop", False):
                 self.exec_args += [
                     "--cap-drop=all",
</code_context>

<issue_to_address>
Logic inversion may alter behavior for nocapdrop.

Previously, capabilities were dropped unless 'nocapdrop' was set. Now, they are only dropped if 'nocapdrop' is True, which reverses the intended logic and may cause capabilities to be dropped in unintended cases.
</issue_to_address>

### Comment 2
<location> `ramalama/engine.py:92` </location>
<code_context>
         if not sys.stdin.isatty():
             return False
-        if not (hasattr(self.args, "ARGS") and self.args.ARGS):
+        if getattr(self.args, "ARGS", None):
             return False
-        if not (hasattr(self.args, "subcommand") and self.args.subcommand == "run"):
</code_context>

<issue_to_address>
Logic for ARGS in use_tty is now inverted.

This change may alter use_tty's behavior. Please confirm if this is intentional.
</issue_to_address>

### Comment 3
<location> `ramalama/model.py:240` </location>
<code_context>

     def add_rag(self, exec_args, args):
-        if not hasattr(args, "rag") or not args.rag:
+        if getattr(args, "rag", None):
             return exec_args

</code_context>

<issue_to_address>
Logic for add_rag is now inverted.

Previously, the function exited if 'rag' was missing or falsy. Now, it exits if 'rag' is present and truthy, which likely prevents adding 'rag' when it should be added.
</issue_to_address>

### Comment 4
<location> `ramalama/quadlet.py:118` </location>
<code_context>
         files: list[UnitFile] = []

-        if not hasattr(self.args, "rag") or not self.rag:
+        if getattr(self.args, "rag", None):
             return files

</code_context>

<issue_to_address>
Logic for _gen_rag_volume is now inverted.

This change causes the function to skip generating rag volumes when rag is set, which is the opposite of the previous logic.
</issue_to_address>

### Comment 5
<location> `ramalama/cli.py:273` </location>
<code_context>
 def post_parse_setup(args):
     """Perform additional setup after parsing arguments."""
-    if hasattr(args, "MODEL") and args.subcommand != "rm":
+    if getattr(args, "MODEL", "rm") != "rm":
         resolved_model = shortnames.resolve(args.MODEL)
         if resolved_model:
</code_context>

<issue_to_address>
Default value for MODEL may cause unexpected behavior.

Defaulting to 'rm' may unintentionally trigger the condition. Recommend checking if MODEL is set explicitly instead.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

self.exec_args += ["--privileged"]
else:
self.exec_args += [
"--security-opt=label=disable",
]
if not hasattr(self.args, "nocapdrop"):
if getattr(self.args, "nocapdrop", False):
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Logic inversion may alter behavior for nocapdrop.

Previously, capabilities were dropped unless 'nocapdrop' was set. Now, they are only dropped if 'nocapdrop' is True, which reverses the intended logic and may cause capabilities to be dropped in unintended cases.

@@ -89,9 +89,9 @@ def cap_add(self, cap):
def use_tty(self):
if not sys.stdin.isatty():
return False
if not (hasattr(self.args, "ARGS") and self.args.ARGS):
if getattr(self.args, "ARGS", None):
Copy link
Contributor

Choose a reason for hiding this comment

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

question (bug_risk): Logic for ARGS in use_tty is now inverted.

This change may alter use_tty's behavior. Please confirm if this is intentional.

@@ -237,7 +237,7 @@ def add_oci_runtime(self, conman_args, args):
return conman_args

def add_rag(self, exec_args, args):
if not hasattr(args, "rag") or not args.rag:
if getattr(args, "rag", None):
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Logic for add_rag is now inverted.

Previously, the function exited if 'rag' was missing or falsy. Now, it exits if 'rag' is present and truthy, which likely prevents adding 'rag' when it should be added.

quadlet_file.add("Container", "PublishPort", f"{self.args.port}:{self.args.port}")

def _gen_rag_volume(self, quadlet_file: UnitFile):
files: list[UnitFile] = []

if not hasattr(self.args, "rag") or not self.rag:
if getattr(self.args, "rag", None):
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Logic for _gen_rag_volume is now inverted.

This change causes the function to skip generating rag volumes when rag is set, which is the opposite of the previous logic.

ramalama/cli.py Outdated
@@ -270,7 +270,7 @@ def parse_arguments(parser):

def post_parse_setup(args):
"""Perform additional setup after parsing arguments."""
if hasattr(args, "MODEL") and args.subcommand != "rm":
if getattr(args, "MODEL", "rm") != "rm":
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (bug_risk): Default value for MODEL may cause unexpected behavior.

Defaulting to 'rm' may unintentionally trigger the condition. Recommend checking if MODEL is set explicitly instead.

Comment on lines +201 to 203
if getattr(args, "name", None):
return args.name

return genname()
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): We've found these issues:

Suggested change
if getattr(args, "name", None):
return args.name
return genname()
return args.name if getattr(args, "name", None) else genname()

@@ -291,7 +291,7 @@ def exec_model_in_container(self, model_path, cmd_args, args):
def setup_mounts(self, model_path, args):
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Low code quality found in Model.setup_mounts - 17% (low-code-quality)


ExplanationThe quality score for this function is below the quality threshold of 25%.
This score is a combination of the method length, cognitive complexity and working memory.

How can you solve this?

It might be worth refactoring this function to make it shorter and more readable.

  • Reduce the function length by extracting pieces of functionality out into
    their own functions. This is the most important thing you can do - ideally a
    function should be less than 10 lines.
  • Reduce nesting, perhaps by introducing guard clauses to return early.
  • Ensure that variables are tightly scoped, so that code using related concepts
    sits together within the function rather than being scattered.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request aims to simplify the codebase by replacing hasattr with getattr, which is a great initiative for improving code clarity. While many of the changes are correct and beneficial, I've identified several instances where the new implementation incorrectly alters the original logic, introducing bugs. These include logical inversions, incorrect condition changes, and a critical issue that could lead to a crash. Please review the detailed comments to address these issues.

ramalama/cli.py Outdated
@@ -270,7 +270,7 @@ def parse_arguments(parser):

def post_parse_setup(args):
"""Perform additional setup after parsing arguments."""
if hasattr(args, "MODEL") and args.subcommand != "rm":
if getattr(args, "MODEL", "rm") != "rm":
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The logic in this condition has been changed incorrectly. The original code checked for the existence of args.MODEL AND that args.subcommand was not "rm". The new code getattr(args, "MODEL", "rm") != "rm" effectively checks if args.MODEL exists and is not "rm", or if it doesn't exist, defaults to "rm" (making the condition false).

However, the critical part args.subcommand != "rm" is completely lost. Furthermore, if args.MODEL is a list (e.g., ['mymodel'] when the subcommand is rm), getattr(args, "MODEL", "rm") would return ['mymodel'], and ['mymodel'] != "rm" would evaluate to True. This would cause the code block to execute for the rm subcommand, which was not the original intent and will lead to unexpected behavior.

To preserve the original logic while using getattr, the condition should explicitly check for the existence of args.MODEL and the subcommand value.

Suggested change
if getattr(args, "MODEL", "rm") != "rm":
if getattr(args, "MODEL", None) is not None and args.subcommand != "rm":

@@ -741,7 +745,7 @@ def get_available_port_if_any() -> int:

def compute_serving_port(args, quiet=False) -> str:
# user probably specified a custom port, don't override the choice
if hasattr(args, "port") and args.port not in ["", str(DEFAULT_PORT)]:
if getattr(args, "port", None) not in ["", str(DEFAULT_PORT)]:
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

This change introduces a potential AttributeError. If args.port does not exist, getattr(args, "port", None) will return None. The condition None not in ["", str(DEFAULT_PORT)] will then evaluate to True, and the next line target_port = args.port will raise an AttributeError because args.port does not exist.

To fix this, the default value for getattr should be one of the values in the list, like "", to make the condition False when the attribute is missing.

Suggested change
if getattr(args, "port", None) not in ["", str(DEFAULT_PORT)]:
if getattr(args, "port", "") not in ["", str(DEFAULT_PORT)]:

self.exec_args += ["--privileged"]
else:
self.exec_args += [
"--security-opt=label=disable",
]
if not hasattr(self.args, "nocapdrop"):
if getattr(self.args, "nocapdrop", False):
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The logic for handling nocapdrop has been inverted. The original code, if not hasattr(self.args, "nocapdrop"), drops capabilities if the --nocapdrop flag is not present. The new code, if getattr(self.args, "nocapdrop", False), will not drop capabilities if the flag is absent, which is the opposite of the original behavior. This has security implications as capabilities might not be dropped when they should be.

The condition should be negated to preserve the original logic.

Suggested change
if getattr(self.args, "nocapdrop", False):
if not getattr(self.args, "nocapdrop", False):

Comment on lines 92 to 95
if getattr(self.args, "ARGS", None):
return False
if not (hasattr(self.args, "subcommand") and self.args.subcommand == "run"):
if getattr(self.args, "subcommand", "") == "run":
return False
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The logic for the checks on ARGS and subcommand has been inverted. The original code used if not (condition): return False, which is equivalent to if condition: pass else: return False. The new code uses if condition: return False, which is the opposite.

This inverts the conditions under which a TTY is used. While the new logic for ARGS seems more appropriate for a TTY check (i.e., don't use TTY if ARGS are provided), this is a silent logic change that should be carefully reviewed. The inversion for subcommand is particularly suspect, as it now prevents using a TTY for the run command.

To avoid unintended side effects, it's best to stick to a direct translation of the original logic.

Suggested change
if getattr(self.args, "ARGS", None):
return False
if not (hasattr(self.args, "subcommand") and self.args.subcommand == "run"):
if getattr(self.args, "subcommand", "") == "run":
return False
if not getattr(self.args, "ARGS", None):
return False
if not (getattr(self.args, "subcommand", "") == "run"):
return False

if getattr(args, "rag", None):
return exec_args
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The logic for the rag check has been inverted. The original code was if not hasattr(args, "rag") or not args.rag:, which would skip the RAG setup if rag was not specified or was falsy. The new code if getattr(args, "rag", None): will now skip the RAG setup if rag is specified, which is the opposite of the intended behavior.

Suggested change
if getattr(args, "rag", None):
return exec_args
if not getattr(args, "rag", None):
return exec_args

@@ -145,7 +145,7 @@ def create_url(self) -> URL:
model = URL(self.pruned_model, urlparse(self.model).scheme)
self.set_optional_model_store(model)
model.draft_model = self.draft_model
if hasattr(self, 'split_model'):
if getattr(self, 'split_model', None):
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Replacing hasattr(self, 'split_model') with getattr(self, 'split_model', None) changes the logic. hasattr only checks for the attribute's existence, whereas the new code also checks for its truthiness.

The split_model attribute can be an empty dictionary ({}), which is falsy. In this case, the original code would execute the if block because hasattr would return True. However, the new code if getattr(self, 'split_model', None): would evaluate bool({}) which is False, thus skipping the block. This could lead to model.split_model not being set correctly.

It's safer to stick with hasattr here to only check for the attribute's presence.

Suggested change
if getattr(self, 'split_model', None):
if hasattr(self, 'split_model'):

Comment on lines 118 to 119
if getattr(self.args, "rag", None):
return files
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The logic for checking rag has been inverted. The original code if not hasattr(self.args, "rag") or not self.rag: would continue to generate the RAG volume if rag was specified. The new code if getattr(self.args, "rag", None): will return files if rag is specified, which means the RAG volume generation is skipped. This is the opposite of the intended behavior.

Suggested change
if getattr(self.args, "rag", None):
return files
if not getattr(self.args, "rag", None):
return files

@rhatdan rhatdan force-pushed the chat branch 6 times, most recently from 15cc4a1 to b877f1a Compare June 25, 2025 20:11
@ericcurtin ericcurtin merged commit 61efb04 into containers:main Jun 26, 2025
13 of 24 checks passed
@ericcurtin
Copy link
Member

Shouldn't have merged, meant to approve, I'll keep an eye on the build and fix accordingly

@ericcurtin
Copy link
Member

Somewhat related, I like how a bot suggested, set the default as this for me:

    parser.add_argument(
        "--api-key",
        type=str,
        default=os.getenv("API_KEY"),
        help="OpenAI-compatible API key. Can also be set via the API_KEY environment variable.",
    )

ideally in default we should call a function that handles the, config file, env var precedence. With CLI option taking precedence over everything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants