Skip to content

Commit 3efdbce

Browse files
committed
Resolve envvar lazily
Because client is instantiated at import time. Closes replicate#4 Signed-off-by: Ben Firshman <ben@firshman.co.uk>
1 parent ad19268 commit 3efdbce

1 file changed

Lines changed: 9 additions & 4 deletions

File tree

replicate/client.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,9 @@
99
class Client:
1010
def __init__(self, api_token=None) -> None:
1111
super().__init__()
12+
# Client is instantiated at import time, so do as little as possible.
13+
# This includes resolving environment variables -- they might be set programmatically.
1214
self.api_token = api_token
13-
if self.api_token is None:
14-
self.api_token = os.environ.get("REPLICATE_API_TOKEN")
15-
1615
self.base_url = "https://api.replicate.com"
1716

1817
# TODO: make thread safe
@@ -31,7 +30,13 @@ def _post(self, path: str, **kwargs):
3130
return self.session.post(self.base_url + path, **kwargs)
3231

3332
def _headers(self):
34-
return {"Authorization": f"Token {self.api_token}"}
33+
return {"Authorization": f"Token {self._api_token()}"}
34+
35+
def _api_token(self):
36+
# Evaluate lazily in case environment variable is set with dotenv, or something
37+
if self.api_token is None:
38+
return os.environ.get("REPLICATE_API_TOKEN")
39+
return self.api_token
3540

3641
@property
3742
def models(self) -> ModelCollection:

0 commit comments

Comments
 (0)