Python中给函数创建别名是否为最佳实践?性能影响如何?
Great question! Let's unpack this common Python pattern step by step.
性能影响:几乎可以忽略
First off, let's address the performance concern. When you do p = print, you're just creating a reference (alias) to the existing print function object—you're not copying the function itself.
- In the global scope: The performance difference between calling
print()andp()is negligible. Both involve a global name lookup, which is fast enough for nearly all use cases. - In a local scope (inside a function): If you assign the built-in
printto a local variablep, callingp()might be slightly faster than callingprint(), since local name lookups are marginally quicker than global ones. But this difference is so tiny that you'd only notice it in extreme scenarios (like millions of repeated calls in a tight loop). For everyday code, don't worry about it.
Is this a best practice? It depends.
This is where context matters most:
❌ Avoid in production/collaborative code (unless it's a standard alias)
Giving common functions like print a random short alias like p hurts code readability. Other developers (or future you!) will have to pause and figure out what p refers to—this adds unnecessary cognitive load.
The only exception here is industry-standard aliases like import numpy as np or import pandas as pd. These are universally recognized in the Python ecosystem, so they don't harm readability.
✅ Perfect for interactive environments
If you're working in a Python shell, Jupyter Notebook, or REPL, aliases like p = print are totally fine! They save you typing time when you're experimenting, testing snippets, or doing quick calculations—readability isn't a concern here because only you're using the code.
✅ Useful for function substitution
Another valid use case is when you need to swap out a function without rewriting all your calls. For example, if you want to replace standard print with a custom logging function in a module:
def custom_print(msg): print(f"[LOG] {msg}") p = custom_print p("Hello world") # Uses the custom function instead of built-in print
This keeps your code DRY (Don't Repeat Yourself) and makes it easy to switch back later if needed.
Final Recommendation
- Interactive use: Go for it—alias away to save time and keystrokes.
- Production/collaborative code: Stick to standard aliases only. Avoid one-off shortcuts like
p = printunless you have a clear, documented reason (like function substitution).
内容的提问来源于stack exchange,提问作者reza

