简体   繁体   中英

Autocompletion in PyCharm based on type

I'm using PyCharm for python coding. The autocompletion in PyCharm is not as good as in IntelliJ (Java). Consider the below code

a = [1,2,3,4]
a.

In this case, after I press the dot , PyCharm gives the full set of autocompletion options. Consider the below case

def func_a(a):
    a.

Here, to the function func_a I'm passing a list as an argument. But when I press dot after a , PyCharm doesn't give any autocompletion options. I know this is because Python is dynamically typed language and PyCharm has no idea to determine what type a is.

But is there any way to tell PyCharm the type of a , may be in documentation comment or something like that? So, that PyCharm can give valid autocompletion options?

Yes, Python 3.5 introduces type hinting and Pycharm utilizes that.

Use

def func_name(param: type) -> return_type:

Like

def func_a(a: list):

Note that all type hints are completely optional and ignored by the interpreter. However, Pycharm can potentially help you detect type errors if you use it as a habit.

This might not answer your question but this will be helpful for those who just started using pycharm for Django application.

PyCharm does not give (It underlines some built in functions with red) auto-completion option for Django if you have started project with Pure Python . Pure Python option comes when you click on new project option from file menu or when you run pycharm to start new project. Pure Python is the default selected option on new project page. You should choose Django (the 2nd option) to get auto-completion option in PyCharm.

Hope this would be helpful for others.

Can do : (examples using list ):

def func_a(a:list):
    do_this()

Or manually check:

def func_a(a):
    if isinstance(a,list):
        do_this
    else:

        raise TypeError("expected type of 'list' but got type of '%s'"%type(a).__name__)        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM