Skip to content

Commit 4452997

Browse files
Python: Replace wildcard imports with explicit imports (#3908)
* Python: Replace wildcard imports with explicit imports - Replace all 'from ... import *' with explicit symbol imports - Add __all__ declarations to namespace packages for re-exports - Update CODING_STANDARD.md to prohibit wildcard imports - Maintain exported API and preserve all functionality fixes #3605 * Refine wildcard guidance example text * Simplify explicit exports without self-aliases
1 parent a39fd69 commit 4452997

6 files changed

Lines changed: 378 additions & 25 deletions

File tree

‎python/CODING_STANDARD.md‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -403,22 +403,37 @@ If in doubt, use the link above to read much more considerations of what to do a
403403

404404
### Explicit Exports
405405

406-
> **Note:** This convention is being adopted. See [#3605](https://github.com/microsoft/agent-framework/issues/3605) for progress.
406+
**All wildcard imports (`from ... import *`) are prohibited** in production code, including both `.py` and `.pyi` files. Always use explicit import lists to maintain clarity and avoid namespace pollution.
407407

408-
Define `__all__` in each module to explicitly declare the public API. Avoid using `from module import *` in `__init__.py` files as it can impact performance and makes the public API unclear:
408+
Define `__all__` in each module to explicitly declare the public API, then import specific symbols by name:
409409

410410
```python
411-
# ✅ Preferred - explicit __all__ and imports
411+
# ✅ Preferred - explicit __all__ and named imports
412412
__all__ = ["Agent", "Message", "ChatResponse"]
413413

414414
from ._agents import Agent
415415
from ._types import Message, ChatResponse
416416

417-
# ❌ Avoid - star imports
418-
from ._agents import *
419-
from ._types import *
417+
# ✅ For many exports, use parenthesized multi-line imports
418+
from ._types import (
419+
AgentResponse,
420+
ChatResponse,
421+
Message,
422+
ResponseStream,
423+
)
424+
425+
# ❌ Prohibited pattern: wildcard/star imports (do not use)
426+
# from ._agents import <all public symbols>
427+
# from ._types import <all public symbols>
420428
```
421429

430+
**Rationale:**
431+
- **Clarity**: Explicit imports make it clear exactly what is being exported and used
432+
- **IDE Support**: Enables better autocomplete, go-to-definition, and refactoring
433+
- **Type Checking**: Improves static analysis and type checker accuracy
434+
- **Maintenance**: Makes it easier to track symbol usage and detect breaking changes
435+
- **Performance**: Avoids unnecessary symbol resolution during module import
436+
422437
## Performance considerations
423438

424439
### Cache Expensive Computations

‎python/packages/core/agent_framework/__init__.py‎

Lines changed: 281 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,284 @@
99
_version = "0.0.0" # Fallback for development mode
1010
__version__: Final[str] = _version
1111

12-
from ._agents import * # noqa: F403
13-
from ._clients import * # noqa: F403
14-
from ._logging import * # noqa: F403
15-
from ._mcp import * # noqa: F403
16-
from ._middleware import * # noqa: F403
17-
from ._sessions import * # noqa: F403
18-
from ._telemetry import * # noqa: F403
19-
from ._tools import * # noqa: F403
20-
from ._types import * # noqa: F403
21-
from ._workflows import * # noqa: F403
12+
from ._agents import Agent, BaseAgent, RawAgent, SupportsAgentRun
13+
from ._clients import (
14+
BaseChatClient,
15+
SupportsChatGetResponse,
16+
SupportsCodeInterpreterTool,
17+
SupportsFileSearchTool,
18+
SupportsImageGenerationTool,
19+
SupportsMCPTool,
20+
SupportsWebSearchTool,
21+
)
22+
from ._logging import get_logger, setup_logging
23+
from ._mcp import MCPStdioTool, MCPStreamableHTTPTool, MCPWebsocketTool
24+
from ._middleware import (
25+
AgentContext,
26+
AgentMiddleware,
27+
AgentMiddlewareLayer,
28+
AgentMiddlewareTypes,
29+
ChatAndFunctionMiddlewareTypes,
30+
ChatContext,
31+
ChatMiddleware,
32+
ChatMiddlewareLayer,
33+
ChatMiddlewareTypes,
34+
FunctionInvocationContext,
35+
FunctionMiddleware,
36+
FunctionMiddlewareTypes,
37+
MiddlewareException,
38+
MiddlewareTermination,
39+
MiddlewareType,
40+
MiddlewareTypes,
41+
agent_middleware,
42+
chat_middleware,
43+
function_middleware,
44+
)
45+
from ._sessions import (
46+
AgentSession,
47+
BaseContextProvider,
48+
BaseHistoryProvider,
49+
InMemoryHistoryProvider,
50+
SessionContext,
51+
register_state_type,
52+
)
53+
from ._telemetry import (
54+
AGENT_FRAMEWORK_USER_AGENT,
55+
APP_INFO,
56+
USER_AGENT_KEY,
57+
USER_AGENT_TELEMETRY_DISABLED_ENV_VAR,
58+
prepend_agent_framework_to_user_agent,
59+
)
60+
from ._tools import (
61+
FunctionInvocationConfiguration,
62+
FunctionInvocationLayer,
63+
FunctionTool,
64+
normalize_function_invocation_configuration,
65+
tool,
66+
)
67+
from ._types import (
68+
AgentResponse,
69+
AgentResponseUpdate,
70+
Annotation,
71+
ChatOptions,
72+
ChatResponse,
73+
ChatResponseUpdate,
74+
Content,
75+
ContinuationToken,
76+
FinalT,
77+
FinishReason,
78+
FinishReasonLiteral,
79+
Message,
80+
OuterFinalT,
81+
OuterUpdateT,
82+
ResponseStream,
83+
Role,
84+
RoleLiteral,
85+
TextSpanRegion,
86+
ToolMode,
87+
UpdateT,
88+
UsageDetails,
89+
add_usage_details,
90+
detect_media_type_from_base64,
91+
map_chat_to_agent_update,
92+
merge_chat_options,
93+
normalize_messages,
94+
normalize_tools,
95+
prepend_instructions_to_messages,
96+
validate_chat_options,
97+
validate_tool_mode,
98+
validate_tools,
99+
)
100+
from ._workflows import (
101+
DEFAULT_MAX_ITERATIONS,
102+
AgentExecutor,
103+
AgentExecutorRequest,
104+
AgentExecutorResponse,
105+
Case,
106+
CheckpointStorage,
107+
Default,
108+
Edge,
109+
EdgeCondition,
110+
EdgeDuplicationError,
111+
Executor,
112+
FanInEdgeGroup,
113+
FanOutEdgeGroup,
114+
FileCheckpointStorage,
115+
FunctionExecutor,
116+
GraphConnectivityError,
117+
InMemoryCheckpointStorage,
118+
InProcRunnerContext,
119+
Runner,
120+
RunnerContext,
121+
SingleEdgeGroup,
122+
SubWorkflowRequestMessage,
123+
SubWorkflowResponseMessage,
124+
SwitchCaseEdgeGroup,
125+
SwitchCaseEdgeGroupCase,
126+
SwitchCaseEdgeGroupDefault,
127+
TypeCompatibilityError,
128+
ValidationTypeEnum,
129+
Workflow,
130+
WorkflowAgent,
131+
WorkflowBuilder,
132+
WorkflowCheckpoint,
133+
WorkflowCheckpointException,
134+
WorkflowContext,
135+
WorkflowConvergenceException,
136+
WorkflowErrorDetails,
137+
WorkflowEvent,
138+
WorkflowEventSource,
139+
WorkflowEventType,
140+
WorkflowException,
141+
WorkflowExecutor,
142+
WorkflowMessage,
143+
WorkflowRunnerException,
144+
WorkflowRunResult,
145+
WorkflowRunState,
146+
WorkflowValidationError,
147+
WorkflowViz,
148+
create_edge_runner,
149+
executor,
150+
handler,
151+
resolve_agent_id,
152+
response_handler,
153+
validate_workflow_graph,
154+
)
155+
156+
__all__ = [
157+
"AGENT_FRAMEWORK_USER_AGENT",
158+
"APP_INFO",
159+
"DEFAULT_MAX_ITERATIONS",
160+
"USER_AGENT_KEY",
161+
"USER_AGENT_TELEMETRY_DISABLED_ENV_VAR",
162+
"Agent",
163+
"AgentContext",
164+
"AgentExecutor",
165+
"AgentExecutorRequest",
166+
"AgentExecutorResponse",
167+
"AgentMiddleware",
168+
"AgentMiddlewareLayer",
169+
"AgentMiddlewareTypes",
170+
"AgentResponse",
171+
"AgentResponseUpdate",
172+
"AgentSession",
173+
"Annotation",
174+
"BaseAgent",
175+
"BaseChatClient",
176+
"BaseContextProvider",
177+
"BaseHistoryProvider",
178+
"Case",
179+
"ChatAndFunctionMiddlewareTypes",
180+
"ChatContext",
181+
"ChatMiddleware",
182+
"ChatMiddlewareLayer",
183+
"ChatMiddlewareTypes",
184+
"ChatOptions",
185+
"ChatResponse",
186+
"ChatResponseUpdate",
187+
"CheckpointStorage",
188+
"Content",
189+
"ContinuationToken",
190+
"Default",
191+
"Edge",
192+
"EdgeCondition",
193+
"EdgeDuplicationError",
194+
"Executor",
195+
"FanInEdgeGroup",
196+
"FanOutEdgeGroup",
197+
"FileCheckpointStorage",
198+
"FinalT",
199+
"FinishReason",
200+
"FinishReasonLiteral",
201+
"FunctionExecutor",
202+
"FunctionInvocationConfiguration",
203+
"FunctionInvocationContext",
204+
"FunctionInvocationLayer",
205+
"FunctionMiddleware",
206+
"FunctionMiddlewareTypes",
207+
"FunctionTool",
208+
"GraphConnectivityError",
209+
"InMemoryCheckpointStorage",
210+
"InMemoryHistoryProvider",
211+
"InProcRunnerContext",
212+
"MCPStdioTool",
213+
"MCPStreamableHTTPTool",
214+
"MCPWebsocketTool",
215+
"Message",
216+
"MiddlewareException",
217+
"MiddlewareTermination",
218+
"MiddlewareType",
219+
"MiddlewareTypes",
220+
"OuterFinalT",
221+
"OuterUpdateT",
222+
"RawAgent",
223+
"ResponseStream",
224+
"Role",
225+
"RoleLiteral",
226+
"Runner",
227+
"RunnerContext",
228+
"SessionContext",
229+
"SingleEdgeGroup",
230+
"SubWorkflowRequestMessage",
231+
"SubWorkflowResponseMessage",
232+
"SupportsAgentRun",
233+
"SupportsChatGetResponse",
234+
"SupportsCodeInterpreterTool",
235+
"SupportsFileSearchTool",
236+
"SupportsImageGenerationTool",
237+
"SupportsMCPTool",
238+
"SupportsWebSearchTool",
239+
"SwitchCaseEdgeGroup",
240+
"SwitchCaseEdgeGroupCase",
241+
"SwitchCaseEdgeGroupDefault",
242+
"TextSpanRegion",
243+
"ToolMode",
244+
"TypeCompatibilityError",
245+
"UpdateT",
246+
"UsageDetails",
247+
"ValidationTypeEnum",
248+
"Workflow",
249+
"WorkflowAgent",
250+
"WorkflowBuilder",
251+
"WorkflowCheckpoint",
252+
"WorkflowCheckpointException",
253+
"WorkflowContext",
254+
"WorkflowConvergenceException",
255+
"WorkflowErrorDetails",
256+
"WorkflowEvent",
257+
"WorkflowEventSource",
258+
"WorkflowEventType",
259+
"WorkflowException",
260+
"WorkflowExecutor",
261+
"WorkflowMessage",
262+
"WorkflowRunResult",
263+
"WorkflowRunState",
264+
"WorkflowRunnerException",
265+
"WorkflowValidationError",
266+
"WorkflowViz",
267+
"add_usage_details",
268+
"agent_middleware",
269+
"chat_middleware",
270+
"create_edge_runner",
271+
"detect_media_type_from_base64",
272+
"executor",
273+
"function_middleware",
274+
"get_logger",
275+
"handler",
276+
"map_chat_to_agent_update",
277+
"merge_chat_options",
278+
"normalize_function_invocation_configuration",
279+
"normalize_messages",
280+
"normalize_tools",
281+
"prepend_agent_framework_to_user_agent",
282+
"prepend_instructions_to_messages",
283+
"register_state_type",
284+
"resolve_agent_id",
285+
"response_handler",
286+
"setup_logging",
287+
"tool",
288+
"validate_chat_options",
289+
"validate_tool_mode",
290+
"validate_tools",
291+
"validate_workflow_graph",
292+
]
Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,33 @@
11
# Copyright (c) Microsoft. All rights reserved.
22

3-
from ._assistant_provider import * # noqa: F403
4-
from ._assistants_client import * # noqa: F403
5-
from ._chat_client import * # noqa: F403
6-
from ._exceptions import * # noqa: F403
7-
from ._responses_client import * # noqa: F403
8-
from ._shared import * # noqa: F403
3+
from ._assistant_provider import OpenAIAssistantProvider
4+
from ._assistants_client import (
5+
AssistantToolResources,
6+
OpenAIAssistantsClient,
7+
OpenAIAssistantsOptions,
8+
)
9+
from ._chat_client import OpenAIChatClient, OpenAIChatOptions
10+
from ._exceptions import ContentFilterResultSeverity, OpenAIContentFilterException
11+
from ._responses_client import (
12+
OpenAIContinuationToken,
13+
OpenAIResponsesClient,
14+
OpenAIResponsesOptions,
15+
RawOpenAIResponsesClient,
16+
)
17+
from ._shared import OpenAISettings
18+
19+
__all__ = [
20+
"AssistantToolResources",
21+
"ContentFilterResultSeverity",
22+
"OpenAIAssistantProvider",
23+
"OpenAIAssistantsClient",
24+
"OpenAIAssistantsOptions",
25+
"OpenAIChatClient",
26+
"OpenAIChatOptions",
27+
"OpenAIContentFilterException",
28+
"OpenAIContinuationToken",
29+
"OpenAIResponsesClient",
30+
"OpenAIResponsesOptions",
31+
"OpenAISettings",
32+
"RawOpenAIResponsesClient",
33+
]

0 commit comments

Comments
 (0)