Klein routers share too much state between class- and instance-level copies
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 838
- Forks
- 123
- Avg merge
- 7h 58m
- Merged PRs (30d)
- 12
Description
A use-case to set the stage:
I want to generalize my approach to handle_errors and sub-routes. This means I want to do something like:
@attr.s
class RootAPI:
remoteErrorHandlerConfig = attr.ib()
router = Klein()
@router.route("/subroute", branch=True)
def subroute(self, request):
domainObject = SubAPI()
subRouter = domainObject.router
subRouter.handle_errors(Exception)(
lambda other, request, failure: self.errorHandler(request, failure)
)
return subRouter.resource()
Then I want to test this thing.
The problem is that SubAPI.router, another Klein object, shares mutable state with all other instance router objects, due to this code. Rather than doing k._error_handlers = self._error_handlers[:], we do k._error_handlers = self._error_handlers.
Perhaps the existing state-sharing behavior has to be preserved for compatibility, but:
- the attributes aren't exposed as settable via a constructor, so I can't create a new
Kleinmyself - the construction of the URL map is class-scope, so there's no way to pull in the work the
@routedecorator does without re-writing it completely myself - some of these attributes are (inconsistently!) private, which means even if I had a constructor where I could pass them, I can't retrieve the thing I want to pass.
There should be some way to derive a bound Klein object from an existing Klein object which doesn't share state and can be configured on a per-instance basis, so that my dependency-injected remoteErrorHandlerConfig can be passed along.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with src/klein/app.py at the linked lines 158-163, then trace how the class-scope route decorators build the URL map and how instance routers are created. The work is done when a bound Klein object can be derived from an existing one, retain its routes, and configure mutable state independently per instance without breaking compatibility.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100