Python中如何传递参数才能在PyCharm的子函数中获得智能提示(Auto Complete)

个人开发的时候, 我平时都是用 dict [来+回]传递参数, 自己觉得比较方便. 但是没有智能提示, 感觉这个缺点很不好. 会不会有更好的解决方案? 谢谢!

# !/usr/bin/env python
# coding=utf-8
import time

环境: PyCharm + Python 2.7

假设 main 是 web 程序的入口

def main(): args = { ‘time’: time.time(), # 每次访问 都获取不一样的时间[用时间来举例] ‘string’: ‘123’, ‘list’: [], ‘int’: 0, ‘dict’: dict(), ‘more’: ‘…’, ‘return’: ‘’, # 为了方便返回内容 } test(args) # 本文件内传递

print args['return']
print args['m']  # 这里有 Auto Complete

def test(args): print args[‘more’] # 输入 m 的时候,没有智能提示, Auto Complete print args[‘time’] # 使用 time.sleep(1) args[‘return’] = time.time() # 返回内容

if name == ‘main’: main()

1


Python中如何传递参数才能在PyCharm的子函数中获得智能提示(Auto Complete)

22 回复

就算是为了执行效率和可维护性,用个 class 不就搞定了,非要用 dict


要让PyCharm在子函数里正确识别参数类型并给出智能提示,关键得用类型注解(Type Hints)。直接在函数定义里用 : type 标注参数和返回类型,PyCharm就能在调用时推导出类型信息。

举个例子,比如你有个处理用户数据的函数:

def process_user_data(name: str, age: int, scores: list[float]) -> dict:
    """处理用户数据"""
    avg_score = sum(scores) / len(scores) if scores else 0.0
    return {
        "name": name,
        "age": age,
        "avg_score": avg_score
    }

def main():
    # 在这里调用 process_user_data,PyCharm就能对参数给出智能提示了
    result = process_user_data("Alice", 30, [95.5, 88.0, 91.5])
    print(result)

如果参数是个自定义类,也一样:

class User:
    def __init__(self, user_id: int, username: str):
        self.user_id = user_id
        self.username = username

def get_user_info(user: User) -> str:
    return f"User {user.username} (ID: {user.user_id})"

# 调用时,PyCharm会知道 user 参数应该有 .username 和 .user_id 属性

对于复杂的嵌套类型,可以用 from typing import List, Dict, Optional 这些来标注,比如 Optional[str] 表示可能是 str 也可能是 None。这样标注之后,PyCharm在函数内部和调用处都能提供准确的代码补全和类型检查。

核心就一句话:把类型注解写清楚,PyCharm的提示就准了。

class 也不会提示呀, 我写一个例子

不建议使用 dict 来传递参数,调用者怎么知道应该传哪些?漏了很正常

python 已经很灵活了,没必要更灵活

我写的例子有什么问题没有

不应该用 self 传参数吗 😂


def init(self, t, name):
self.t = t
self.name = name

还是没有的, 是我理解错你的意思了吗?

I think the editor don’t know python, they just support completion of words you typed before.

你需要 type hinting

自动过滤了 3 楼的评论么

传字典就是蛋疼中的蛋疼,matplotlib 就是典型一个。。

namedtuple or 仅有属性的类

我正在看, 测试一下就知道了. 谢谢

其他非常相关的建议,我先回复了.

最新文档中 https://www.jetbrains.com/help/pycharm/type-hinting-in-pycharm.html

最后部分 给了工具 Using Typeshed 今天办完事情回来,立刻尝试.

好东西呀

额,我明白你的意思了, 如果不用 type hint 的话,Python 怎么知道你的 main 函数的参数 one 到底是什么呢?
你可以试试 type hint

def main(one: dict) -> int:
“”“Python 3.5+”""
one.



def main(one):
assert isinstance(one, dict)
one.

PyCharm 支持从 docstring 取得类型信息。你只要不懒,按照 Sphinx 支持的格式规范写点文档注释就行了。

比如这个例子(我用了 Google Style Docstring。你也可以选择 reStructuredText style 或者 NumPy Style )。

https://gist.github.com/korepwx/ecfb9479cbfb27adb38ddf5d5d9db8d6

我用 Docstring 不用 Typehint 的原因主要有两点。第一,正儿八经的项目,反正 docstring 总是要写的,把类型说明顺便放到 docstring 里面也没啥不妥。第二,Python 2.x 不支持 type-hinting,我最近写的项目都是 2&3 兼容的。

我个人不喜欢为了迁就 IDE 来更改代码风格

你这个是我最想要的答案. 非常非常感谢.

还给力的给了例子.

回到顶部