1010import logging
1111import os
1212import tempfile
13+ import importlib
1314from typing import Any , Iterator
1415
16+ # policyengine.core is imported for every simulation. Without this guard,
17+ # importing the package pulls both country modules into the process; a US run
18+ # can then fail before it starts if UK private-data credentials are absent.
19+ os .environ .setdefault ("POLICYENGINE_SKIP_COUNTRY_IMPORTS" , "1" )
20+
1521try :
1622 from src .modal .telemetry import split_internal_payload
1723except ModuleNotFoundError :
@@ -236,13 +242,11 @@ def group_subset(entity: str):
236242
237243
238244def _country_module (country : str ):
239- import policyengine as pe
240-
241245 country = country .lower ()
242246 if country == "us" :
243- return pe . us
247+ return importlib . import_module ( "policyengine.tax_benefit_models.us" )
244248 if country == "uk" :
245- return pe . uk
249+ return importlib . import_module ( "policyengine.tax_benefit_models.uk" )
246250 raise ValueError (f"Unsupported country: { country } " )
247251
248252
@@ -327,18 +331,10 @@ def _budget_result(country: str, baseline, reform) -> dict[str, float]:
327331
328332
329333def _poverty_result (country : str , baseline , reform ) -> dict [str , list [dict [str , Any ]]]:
330- import policyengine as pe
331-
332- if country == "us" :
333- baseline_poverty = pe .us .economic_impact_analysis (
334- baseline , reform
335- ).baseline_poverty
336- reform_poverty = pe .us .economic_impact_analysis (baseline , reform ).reform_poverty
337- else :
338- baseline_poverty = pe .uk .economic_impact_analysis (
339- baseline , reform
340- ).baseline_poverty
341- reform_poverty = pe .uk .economic_impact_analysis (baseline , reform ).reform_poverty
334+ country_module = _country_module (country )
335+ impact = country_module .economic_impact_analysis (baseline , reform )
336+ baseline_poverty = impact .baseline_poverty
337+ reform_poverty = impact .reform_poverty
342338
343339 return {
344340 "baseline" : baseline_poverty .dataframe .to_dict ("records" ),
@@ -347,12 +343,8 @@ def _poverty_result(country: str, baseline, reform) -> dict[str, list[dict[str,
347343
348344
349345def _analysis_result (country : str , baseline , reform ) -> dict [str , Any ]:
350- import policyengine as pe
351-
352- if country == "us" :
353- analysis = pe .us .economic_impact_analysis (baseline , reform )
354- else :
355- analysis = pe .uk .economic_impact_analysis (baseline , reform )
346+ country_module = _country_module (country )
347+ analysis = country_module .economic_impact_analysis (baseline , reform )
356348
357349 return {
358350 "decile_impacts" : analysis .decile_impacts .dataframe .to_dict ("records" ),
0 commit comments