Defer optional nkeys import into auth setup - #979
Conversation
A top-level `import nkeys` made `import nats.client` fail with ImportError on a plain `pip install nats-core`, since nkeys ships only as the `[nkeys]` extra. Move it into the nkey/JWT auth setup helpers — its only consumers — after their early returns, so the base package loads without the extra, pre-built handlers and JWT parsing stay nkeys-free, and deriving a signer from a seed raises a clear hint.
|
Claude finished @caspervonb's task in 2m 2s —— View job PR Review
The fix is correct and necessary. The top-level A few notes: Correctness — The deferred-import helper (
Performance — Python caches modules in Pre-built handler paths — Both functions correctly short-circuit before touching Overall: one minor suggestion left as an inline comment; the core fix is sound. |
| msg = f"Invalid jwt argument: {jwt!r}" | ||
| raise TypeError(msg) | ||
|
|
||
| nkeys = _import_nkeys() |
There was a problem hiding this comment.
Minor: _import_nkeys() is placed after all the file I/O (.read_text() / .read_bytes()), so a user without nkeys installed who passes a .creds or seed file will have that file read before the clear ImportError is raised. This is inconsistent with _setup_nkey_auth, where _import_nkeys() is called before the seed file is read.
Consider moving the call to just after the early-return guard, mirroring _setup_nkey_auth. Not a bug — the error is still clear and actionable — but the current placement does unnecessary file I/O before failing.
Matches _setup_nkey_auth, so a missing nkeys package raises its ImportError before any JWT or seed file is read.
|
Review comments addressed, PTAL @claude |
|
Claude finished @caspervonb's task in 59s —— View job Re-review of addressed comments
The inline comment has been fully addressed in commit What changed — def _setup_jwt_auth(jwt):
if isinstance(jwt, tuple) and callable(jwt[0]):
return jwt # pre-built handlers: no nkeys needed
nkeys = _import_nkeys() # ← now here, before any I/O
if isinstance(jwt, Path):
creds_content = jwt.read_text() # file I/O only reached with nkeys present
...This exactly mirrors Overall — both helpers are now consistent, the fix is correct, and no issues remain. LGTM. |
A top-level
import nkeysbrokeimport nats.clienton a plainpip install nats-core: nkeys ships only as the[nkeys]extra, so the unconditional import raisedImportErrorfor everyone not using nkey/JWT auth.The import now lives in the two auth-setup helpers (its only consumers), after their early returns. The base package loads without the extra, pre-built handler tuples and JWT parsing stay nkeys-free, and deriving a signer from a seed raises a clear
Install nats-core[nkeys].hint — mirroring how the websocket extra is guarded inconnection.py.