Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions graphrag/config/environment_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@

def read_key(value: KeyValue) -> str:
"""Read a key value."""
if not isinstance(value, str):
return value.value.lower()
return value.lower()
# Avoid isinstance for str first -- cheaper in general to check == type if type is frequently str
if type(value) is str:
return value.lower()
return value.value.lower()


class EnvironmentReader:
Expand All @@ -41,14 +42,18 @@ def env(self):
def _read_env(
self, env_key: str | list[str], default_value: T, read: Callable[[str, T], T]
) -> T | None:
# Avoid creating a new list if already a list
if isinstance(env_key, str):
env_key = [env_key]
env_keys = (env_key,)
else:
env_keys = env_key

for k in env_key:
for k in env_keys:
# Inline .upper() and avoid creating a variable for k.upper() unnecessarily.
# Call read once.
result = read(k.upper(), default_value)
if result is not default_value:
return result

return default_value

def envvar_prefix(self, prefix: KeyValue):
Expand Down Expand Up @@ -127,11 +132,13 @@ def float(
) -> float | None:
"""Read a float configuration value."""
key = read_key(key)
if self.section and key in self.section:
return float(self.section[key])
return self._read_env(
env_key or key, default_value, lambda k, dv: self._env.float(k, dv)
)

section = getattr(self, "section", None)
if section is not None and key in section:
return float(section[key])
# Avoid lambda for hot path
env = self._env
return self._read_env(env_key or key, default_value, env.float)

def list(
self,
Expand Down