Skip to content

Commit 01ff86a

Browse files
committed
added load_dotenv monkey patch to display a warning if it is called after ibind has been imported
1 parent 6f6767c commit 01ff86a

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

ibind/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@
99
from ibind.client.ibkr_definitions import snapshot_keys_to_ids
1010
from ibind.support.errors import ExternalBrokerError
1111
from ibind.support.logs import ibind_logs_initialize
12-
from ibind.support.py_utils import execute_in_parallel
13-
12+
from ibind.support.py_utils import execute_in_parallel, patch_dotenv
1413

1514
__all__ = [
1615
'ibind_logs_initialize',
@@ -31,3 +30,4 @@
3130
'ExternalBrokerError',
3231
]
3332

33+
patch_dotenv()

ibind/support/py_utils.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import copy
22
import inspect
33
import os
4+
import sys
45
import threading
56
import time
67
import traceback
8+
import warnings
79
from concurrent.futures import ThreadPoolExecutor, as_completed
810
from enum import Enum, EnumMeta
911
from functools import wraps
@@ -324,4 +326,22 @@ def print_table(my_dict, column_order=None):
324326
column_size = [max(map(len,col)) for col in zip(*rv)]
325327
formatter = ' '.join(["{{:>{}}}".format(i) for i in column_size])
326328
for i, item in enumerate(rv):
327-
print(formatter.format(*item))
329+
print(formatter.format(*item))
330+
331+
def patch_dotenv():
332+
try:
333+
import dotenv
334+
from dotenv import load_dotenv
335+
336+
# Wrap the original load_dotenv function
337+
def warn_if_late_load(*args, **kwargs):
338+
if 'ibind.var' in sys.modules:
339+
warnings.warn("⚠️ WARNING: `load_dotenv()` was called after `ibind` was imported. Environment variables were already read and changes may not take effect. Call `load_dotenv()` before importing `ibind` to ensure proper behavior.", RuntimeWarning, stacklevel=2)
340+
return load_dotenv(*args, **kwargs)
341+
342+
# Replace the original load_dotenv with the wrapped version
343+
dotenv.load_dotenv = warn_if_late_load
344+
345+
except ImportError:
346+
pass # dotenv is not installed, nothing to patch
347+

0 commit comments

Comments
 (0)