Reputation: 31652
My class looks something like this:
class MyConfig(BaseSettings):
model_config = SettingsConfigDict(
env_file=get_configs(),
)
I didn't realize that my get_configs()
seems to be getting called on import. I discovered this when I had a bug in that function and pytest collection was failing.
Is this a python behavior or something specific to how the model_config
attribute of the BaseSettings
class works? It doesn't make sense to me because I would expect my get_configs()
function to only get called when the code that is actually instantiating MyConfig
is executed.
Upvotes: 0
Views: 50
Reputation: 77407
This is normal python behavior for any class. Python executes the body of the class definition the same as it would execute module level code - accounting for the fact that it is within the class. For instance, at module level, a function definition (e.g. def foo(): return 1
), binds the already-compiled function to the name "foo" in the module namespace. In a class definition, a method (e.g., def foo(self): return 1
), the function object is bound to "foo" in the class namespace.
In your case, the class level "model_config" is assigned the result of the function call.
Upvotes: 1