Skip to content

Refactor dynamic base_url attribute on requests.Session #38

@gawbul

Description

@gawbul

Priority: High

Issue

The code dynamically adds a base_url attribute to requests.Session, which doesn't have this attribute by default. This creates a non-standard attribute through dynamic attribute assignment.

Current Code

# pyensemblrest/ensemblrest.py:123-124
for key, val in client_args_copy.items():
    if key in ("base_url", "proxies"):
        setattr(self.session, key, val)  # Adding base_url to requests.Session

# Later used as:
url = self.session.base_url + func["url"]  # type: ignore[attr-defined]

Problem

  • Requires type ignore comments
  • Non-standard use of requests.Session
  • Harder to understand for maintainers
  • May break with requests library updates

Recommendation

Store base_url as an instance attribute:

class EnsemblRest:
    def __init__(self, api_table: dict[str, Any] = ensembl_api_table, **kwargs: dict[str, Any]) -> None:
        self.base_url = kwargs.pop('base_url', ensembl_default_url)
        self.session_args = kwargs or {}
        # ... rest of init
        
    def call_api_func(self, api_call: str, api_table: dict[str, Any], **kwargs: dict[str, Any]) -> Any:
        # ...
        url = re.sub(
            r"\{\{(?P<m>[a-zA-Z1-9_]+)\}\}",
            lambda m: "%s" % kwargs.get(m.group(1)),
            self.base_url + func["url"],  # Use instance attribute
        )

Files to Update

  • pyensemblrest/ensemblrest.py - Add self.base_url and remove dynamic attribute

Testing

  • Run full test suite
  • Verify custom base_url still works

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions