- Python-сообщество
- Уведомления
- #1 Янв. 14, 2017 18:14:44
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- #2 Янв. 14, 2017 22:14:37
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- #3 Янв. 14, 2017 23:09:49
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- #4 Янв. 15, 2017 06:27:17
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- #5 Янв. 15, 2017 06:36:20
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- #6 Янв. 15, 2017 06:42:45
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- #7 Янв. 15, 2017 07:23:04
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- #8 Янв. 15, 2017 08:16:58
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- #9 Янв. 15, 2017 09:06:08
- дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
- PyCharm и автодополнение
- Автодополнение кода в шаблонах django в PyCharm Community
- 2 ответа 2
- Autocomplete not working in Pycharm #1682
- Comments
- Shourai commented Jul 24, 2019 •
- Code completion
- Basic completion
- Invoke basic completion
- Type-matching completion
- Invoke type-matching completion
- Statement completion
- Complete a method declaration
- Complete a code construct
- Complete statements in collections
- Hippie completion
- Expand a string at caret to an existing word
- Postfix code completion
- Enable and configure postfix completion
- Transform a statement with a postfix
- F-string completion
- Auto import on module name completion
- Configure code completion settings
- Completion tips and tricks
- Narrow down the suggestions list
- Accept a suggestion
- View reference
- View code hierarchy
- Use machine-learning-assisted code completion
- Troubleshooting
Python-сообщество
Уведомления
#1 Янв. 14, 2017 18:14:44
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
Всем доброго. Воткнулся в хрень и не могу оставить… Уже и дескрипторы и декораторы и мета пробовал, но не могу добиться автодополнения от PyCharm
Надо типа а-ля foreign_key и one_to_one как в models.Model Django. Надо, ох как надо автодополнение (широкая структура большой вложенности намечается), а к другой архитектуре кода не хочется прибегать. Так все лаконично и привычно.
Подскажите чем кто может.
Отредактировано zavx0z (Янв. 14, 2017 18:16:21)
#2 Янв. 14, 2017 22:14:37
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
Похоже Python не дает вариантов для PyCharm в этом случае. Уже все способы попробовал, какие в голову пришли, в книгах нашел, в YouTube, Google… ппц двум с половиной суток… досадно. Чтоб придумать то подобное
#3 Янв. 14, 2017 23:09:49
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
менять архитектуру приложения потому что в IDE не работает автодополнение….. я запомню это.
Миллион раз обсуждалась основная тема — из за динамической типизации невозможно сделать полностью грамотное автодополнение (например как в VisualStudio при работе с C/C++ или Delphi и тп).
Конкретно в вашем случае я ниче не понял. Причем тут декораторы, мета … да и в коде вашем .elems не существует
_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com
#4 Янв. 15, 2017 06:27:17
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
JOHN_16
Причем тут декораторы, мета … да и в коде вашем .elems не существует
Мета и дискрипторы я не стал в коде показывать, все равно они не оправдывают ожидания. Хотел только показать связь в модели.
Рассмотрим как дескрипторы.
Есть основной блок Main, у него есть свойство block_elems. block_elems — класс дескриптор Block, в который передается объект Elements и параметр prop.
Имеем:
Так вот ни каким методом я не могу затавить свойста торчать наружу с условием автодополнения.
Из этого примера видно для чего я еще пробовал использовать декораторы класса и мета. Нужно связать несвязанные классы, такие как Block и Elements, ManyToOne и Elem.
Отредактировано zavx0z (Янв. 15, 2017 06:46:55)
#5 Янв. 15, 2017 06:36:20
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
JOHN_16
менять архитектуру приложения потому что в IDE не работает автодополнение….. я запомню это.
Да, может и такое быть. Для меня основным приоритетом является удобное использование моделей для скорости написания основного кода приложения, где вся элементы вложенной структуры многократно взаимодействуют. Тем более что это должен быть фреймворк для множества проектов. И если по большой портянке в несколько тысяч строк искать отношения… или постоянно перемещаться по файлам в поисках связей… не продуктивно как-то получается и сулит получить кучу эксепшенов.
Хотелось бы конечно в таком виде как у Django, т.к. еще вторым в приоритете стоит задача лаконичного описания моделей с множественными свойствами и аттрибутами полей, ну и методов(куда без них).
ОСНОВНАЯ же задача передо мной стоит в многократном использовании моделей и всех их свойств в коде. Без автодополнения ну совсем не удобно. Не так ли?
Отредактировано zavx0z (Янв. 15, 2017 06:49:34)
#6 Янв. 15, 2017 06:42:45
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
JOHN_16
из за динамической типизации невозможно сделать полностью грамотное автодополнение
#7 Янв. 15, 2017 07:23:04
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
zavx0z
Есть такое понятие — хороший стиль программирования. Один из пунктов хорошего стиля — автодокументация кода. И питон не исключение, автодокументация кода в питоне делается так же как и в других языках — комментариями. А пайшарм понимает эти комментарии, более того он понимает несколько стилей этих комментариев. Я бы вам рекомендовал комментарии в стиле sphinx, пайшарм с ними работает замечательно.
#8 Янв. 15, 2017 08:16:58
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
FishHook
С документацией у меня все впоряде. Но чем документация поможет в моем случае?
— Автодополнение не заработает в этой модели благодаря документации.
— Документация не поможет в поиске динамических аттрибутов.
Или может я что-то не так понял, или Вы?
#9 Янв. 15, 2017 09:06:08
дескрипторы и декораторы и мета пробовал а PyCharm не поддается!
zavx0z
Без автодополнения ну совсем не удобно. Не так ли?
zavx0z
Ну и дальше по такому типу может быть очень глубоко.
Не думаю что это удобно. Я бы это назвал кошмар программиста. Такое скорее в java можно увидеть.
В ваших планах я вообще не увидел использования модулей и пакетов, используются только классы. Может это решит вашу проблему структуирования кода?
zavx0z
Возможно все… вот только еще пока никто не сделал.
Тоже не согласен. Вот у меня в одном приложении описания классов по сети с других машин грузятся по алгоритму с использованием шифрования. Как пичарм автодополнение сделает до того как приложение запущено и пройдена аутентификация пользователя? Никак. В общем случае возможно автодополенение в том случае когда вы уже выполнили приложение до определенной точки и вписываете текст программы именно в этом месте. Вы это имеете ввиду? Похоже нет. Просто технология написания программы в питоне может очень существенно отличаться от технологии C, C++, java и т.п. (также как отличаются технологии java и C++) .
Могу посоветовать посмотреть технологии Jupiter, Ipython, Wolfram Mathematica наконец.
Отредактировано doza_and (Янв. 15, 2017 09:26:50)
Источник
PyCharm и автодополнение
Как то года 4 назад писал я проект на питоне и юзал PyCharm, помнится я был от него в полном восторге, он тогда почти любую стороннюю библиотеку из тех что я использовал автодополнял самостоятельно (pygame, что-то там еще). А сейчас спустя 4 года я пишу на том же питоне, на том же PyCharm. И он нихрена не дополняет кроме того что есть в официальной поставке. Может надо что-то где то щелкнуть? А то не приятно писать так.
P.S. Сейчас использую Community Edition. А 4 года назал вроде её даже не было
пайтоне, а не питоне
Лайнекс, а не линукс!
Linux (/ˈlɪnəks/ LIN-uks or, less frequently used, /ˈlaɪnəks/ LYN-uks)
открой настройки проекта и надобавляй фасеты с нужными технологиями.
ахтунг: совет не опробован на реальном пичарме, ибо юзаю идею
Settings — Project Interpreter
Не PyQt случем не дополняет? Была у них такая бага.
тогда уж «пайсон», если выделываешься
Вот. А по теме мне тоже нечего сказать )
А что тут надо посмотреть? В настройках интерпретатора в поле packages есть те пакеты которые мне нужны, однако все равно ничего не отображается.
Pika, Unirest, IPy, Flask, SQLAlchemy, psutil
Не, Qt я не юзал, но зуб даю что тоже работать не будет
Более того он многие модули прямо в подсветке подчеркивает и пишет No Module Named, хотя при выполнении из того же шарма проблем нет
Источник
Автодополнение кода в шаблонах django в PyCharm Community
Не могу найти комбинацию горячих клавиш для автодополнения кода при работе в PyCharm c html5 файлом.
1. После ввода кода:
и нажатия горячих клавиш стало так:
2. После ввода кода:
и нажатия грячих клавиш стало так:
Все это увидел в видеокурсе по работе с Django тут и тут (ссылки именно на эти моменты видеокурса, нашел на yotube.com). Объяснений того, какие автор использует горячие клавиши не было, а найденные в интернете горячие клавиши не работают как в примере (наверно в PyCharm можно сохранять свои варианты автодополнения кода, но как это делать не знаю)
2 ответа 2
Похоже это сделано через Live Templates («Живые шаблоны»). Пример настройки для шаблона block/endblock:
Работает так: в html файле вы вводите <> (то что указано в поле «Abbrevation»), жмете Tab (или кнопку выбранную в комбо «Expand with», если там что-то другое — можно например поставить чтобы дополнялось при нажатии пробела), фигурные скобки заменяются на текст <% block %> <% endblock %>, курсор становится туда, где стоит $SELECTION$ в тексте шаблона.
Вообще, мне кажется, удобнее было бы сделать шаблон для for (так как он довольно часто используется). Например, аббревиатура
Чтобы работало, обязательно должен быть выбран контекст — HTML под полем текста шаблона (там где на скриншоте Applicable in HTML: HTML Text; HTML ). При создании шаблона там будет «No applicable contexts.» — нужно нажать на Define и выбрать HTML.
Для двойной скобки более простой шаблон: << $SELECTION$ >>
Источник
Autocomplete not working in Pycharm #1682
Comments
Shourai commented Jul 24, 2019 •
While using plotly 4.0 combined with Pycharm the autocompletion for plotly.graph_objects is not working.
Also the references to the objects are not found either, but the script does work.
I see some people on the community site with the same issue.
Works fine for e.g. pandas:
No completion is found when I type go. either.
However when I use import plotly.graph_objs as go , the references are found.
But the autocompletion still doesn’t work.
I have tried File > Invalidate Cache/Restart , to no avail.
There has been an issue like this before but it seems it had been solved: #389
When I open the same virtualenv within VScode the autocompletion works fine.
(The extension uses jedi for autocompletion I think).
I am not sure if this is an issue with plotly or pycharm.
The text was updated successfully, but these errors were encountered:
Источник
Code completion
This section covers various techniques of context-aware code completion that allow you to speed up your coding process.
Basic completion
Basic code completion helps you complete the names of classes, methods, and keywords within the visibility scope. When you invoke code completion, PyCharm analyses the context and suggests the choices that are reachable from the current caret position (suggestions also include Live templates).
Code completion is available for custom file types. However, PyCharm does not recognize the structure of such files, and suggests options regardless of whether they are appropriate in the current context.
Basic completion is also available for a non-English keyboard layout.
If basic code completion is applied to a part of a field, parameter, or variable declaration, PyCharm suggests a list of possible names depending on the item type.
Invoking Basic code completion for the second time shows the names of classes, functions, modules, and variables.
Invoke basic completion
Start typing a name.
Press Ctrl+Space or choose Code | Code Completion | Basic from the main menu.
The images below show basic code completion for the following cases:
Methods:
Method parameters:
Dictionaries:
Django templates:
File paths completion in Python string literals:
If necessary, press Ctrl+Space for the second time (or press Ctrl+Alt+Space ).
This shows the names of classes, functions, modules, and variables.
Type-matching completion
Smart type-matching code completion filters the suggestions list and shows only the types applicable to the current context.
Invoke type-matching completion
Start typing. By default, PyCharm displays the code completion popup automatically as you type. If automatic completion is disabled, press Ctrl+Shift+Space or choose Code | Code Completion | Type-Matching from the main menu.
Press Ctrl+Shift+Space or choose Code | Code Completion | Type-Matching from the main menu.
The most suitable suggestion for the current context is highlighted.
If necessary, press Ctrl+Shift+Space once again.
Statement completion
You can create syntactically correct code constructs by using statement completion Ctrl+Shift+Enter . It inserts the necessary syntax elements and gets you in a position where you can start typing the next statement.
Complete a method declaration
Start typing a method declaration and press Ctrl+Shift+Enter after the opening parenthesis.
PyCharm automatically completes a method declaration with the mandatory parameter self . Start typing a method declaration in a Python class, and PyCharm will insert self after the opening bracket of the parameters list. This behavior is configurable in the Smart Keys page of the editor settings.
Complete a code construct
Start typing a code construct and press Ctrl+Shift+Enter .
PyCharm automatically completes the construct and adds the required punctuation. The caret is placed at the next editing position.
Complete statements in collections
PyCharm automatically inserts a trailing comma before a line break in multiline collection literals. In dict literals, it inserts a colon between a key and a value. Press Ctrl+Shift+Enter to invode statement completion:
Note that because of the language ambiguity regarding syntax of some incomplete collection literals, a colon is inserted neither after the first key of a dict literal nor after the first item of a parenthesized tuple.
Hippie completion
Hippie completion is a completion engine that analyses your text in the visible scope and generates suggestions from the current context. It helps you complete any word from any of the currently opened files.
Expand a string at caret to an existing word
Type the initial string and do one of the following:
Press Alt+/ or choose Code | Code Completion | Cyclic Expand Word to search for matching words before the caret.
Press Alt+Shift+/ or choose Code | Code Completion | Cyclic Expand Word (Backward) to search for matching words after the caret and in other open files.
The first suggested value appears, and the prototype is highlighted in the source code.
Accept the suggestion, or hold the Alt key and keep pressing / until the desired word is found.
Postfix code completion
Postfix code completion helps you reduce backward caret jumps as you write code. You can transform an already-typed expression to a different one based on a postfix you type after the dot, the type of expression, and its context.
Enable and configure postfix completion
Go to Settings / Preferences | Editor | General | Postfix Completion and select the Enable postfix completion checkbox.
Select Tab , Space , or Enter to be used for expanding postfix templates.
Enable/disable a particular postfix template for the selected language.
Transform a statement with a postfix
Type an expression and then type a postfix after a dot, for example, .if:
The initial expression gets wrapped with an if statement:
You can disable certain postfix completion templates in the Editor | General | Postfix Completion page of the IDE settings Ctrl+Alt+S .
You can select Tab , Space , or Enter to expand postfix templates.
You can edit the predefined postfix templates, for example, to replace a long key with a shorter one, or to expand the list of applicable expression types. Due to PyCharm limitations, you cannot create any custom postfix templates for Python.
Postfix completion options are shown as part of the basic completion suggestions list. To see a full list of postfix completions applicable in the current context, press Ctrl+J .
F-string completion
Whenever you open a curly brace in an ordinary string literal, PyCharm provides the same completion suggestions as for an f-string. When you select one of the suggested options, the IDE automatically converts the literal into an f-string by adding a missing f prefix and a closing curly brace.
Auto import on module name completion
PyCharm automatically adds an import statement when you refer any module member or package in the Python code and invoke code completion. Auto-import on code completion is also applied to some popular package name aliases, such as np for numpy or pd for pandas .
Configure code completion settings
To configure code completion options, go to the Editor | General | Code Completion page of the IDE settings Ctrl+Alt+S .
You can choose the following settings:
Select if you want to sort items in the suggestions list in the alphabetical order instead of sorting them by relevance.
You can change this behavior at any time by clicking in the suggestion list and toggling the Sort by Name option.
Select to automatically show a popup for each item in the suggestions list with the documentation for the class, method, or field currently highlighted in the lookup list.
In the field to the right, specify the delay (in milliseconds), after which the popup should appear.
Completion tips and tricks
Narrow down the suggestions list
You can narrow down the suggestions list by typing any part of a word (even characters from somewhere in the middle) or invoking code completion after a dot separator. PyCharm will show suggestions that include the characters you’ve entered in any positions.
This makes the use of wildcards unnecessary:
In case of CamelCase or snake_case names, type the initial letters only. PyCharm automatically recognizes and matches the initial letters.
Accept a suggestion
You can accept a suggestion from the list in one of the following ways:
Press Enter or double-click a list item to insert it to the left of the caret.
Press Tab to replace the characters to the right from the caret.
Use Ctrl+Shift+Enter to make the current code construct syntactically correct (balance parentheses, add missing braces and semicolons, and so on).
You can also use specific keys to insert the selected completion suggestion: go to the Editor | General | Code Completion page of the IDE settings Ctrl+Alt+S and select the Insert selected suggestion by pressing space, dot, or other context-dependent keys option. These keys depend on the language, your context, and so on.
While this setting helps you save time, turning it on may result in items being inserted accidentally.
View reference
You can use the Definitions by pressing Ctrl+Shift+I when you select an entry in the suggestions list:
You can use the Quick Information view by pressing Ctrl+Q when you select an entry in the suggestions list:
View code hierarchy
You can view code hierarchy when you’ve selected an entry from the suggestions list:
Ctrl+H — view type hierarchy
Ctrl+Shift+H — view method hierarchy.
Use machine-learning-assisted code completion
You can utilize machine learning models to rank most suitable items higher in the suggestions list.
To do so, press Ctrl+Alt+S to open the IDE settings and select Editor | General | Code Completion , and then enable the Sort completion suggestions based on machine learning option under Machine Learning-Assisted Completion .
The and arrow icons indicate whether the relevance of a suggestion is increasing or decreasing and therefore the suggestion has moved up or down the list.
The ML completion mechanism doesn’t add any new elements but orders the elements retrieved from the script or runtime. Data are not exposed anywhere; they are collected locally.
This feature is experimental, so ranking might not change noticeably.
Troubleshooting
If code completion doesn’t work, this may be due to one of the following reasons:
The Power Save Mode is on ( File | Power Save Mode ). Turning it on minimizes power consumption of your laptop by eliminating the background operations, including error highlighting, on-the-fly inspections, and code completion.
Your file doesn’t reside in a content root, so it doesn’t get the required class definitions and resources needed for code completion.
A file containing classes and functions that you want to appear in completion suggestions list is marked as a plain text file.
External libraries that contain functions that you want to appear in the completion suggestions list are not added as dependencies or global libraries .
Источник