Skip to content

Conversation

@Xyerophyte
Copy link

Problem

The DomainsResponse class (and other ModelSimple-based list response models) could not be iterated, causing ApiAttributeError when attempting common operations:

domains = domain_api.DomainApi(api_client).list_domains(id, version)
[domain for domain in domains]  # ❌ ApiAttributeError: DomainsResponse has no attribute '0'

Users had to access the internal _data_store directly, breaking the abstraction.

Root Cause

DomainsResponse inherits from ModelSimple and stores a list in its value attribute. When Python's iteration protocol calls __getitem__(0), the existing implementation only accepted string attribute names, not integer indices.

Solution

Enhanced the ModelSimple class in fastly/model_utils.py with sequence protocol support:

  1. __getitem__ - Now accepts integers and slices, delegating to the underlying value list/tuple
  2. __iter__ - Returns an iterator over the sequence in value
  3. __len__ - Returns the length of the sequence in value

The implementation intelligently handles:

  • Lists and tuples as sequences (iterable)
  • Dicts and other objects as single items (to avoid iterating dict keys)
  • Backward compatibility with existing attribute access

What Now Works

domains = domain_api.DomainApi(api_client).list_domains(id, version)

len(domains)              # ✓ Get count
domains[0]                # ✓ Index access  
domains[1:3]              # ✓ Slicing
list(domains)             # ✓ Convert to list
[d for d in domains]      # ✓ List comprehension
for domain in domains:    # ✓ Iteration
    print(domain)

Testing

  • Added comprehensive test suite in tests/test_model_simple_sequence.py
  • Tests cover iteration, indexing, slicing, len(), edge cases (empty, single item)
  • All tests pass ✓

Documentation

  • Updated CHANGELOG.md (v12.0.0 bug fixes section)
  • Fix is backward-compatible with existing code

Impact

  • Affects all ModelSimple instances that wrap sequences
  • Makes list-based response models behave intuitively
  • No breaking changes - purely additive functionality

- Add __iter__, __len__, and enhanced __getitem__ to ModelSimple
- Fixes ApiAttributeError when iterating DomainsResponse and similar models
- Users can now use for loops, list comprehensions, indexing, and len()
- Add comprehensive test coverage in test_model_simple_sequence.py
- Update CHANGELOG.md for v12.0.0

Fixes issue where DomainsResponse._data_store had to be accessed directly
to iterate over domain lists. Now DomainsResponse and other ModelSimple
list-based responses behave like native Python sequences.
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.

1 participant