简体   繁体   中英

How to organize Python code into collapsable / expandable chunks?

In Pycharm, there's "code structurure" side bar which provides a tree to navigate through the code, but, it is only useful when the code has classes and methods and objects. If nothing of that is in code then it is useless. My question is: is there any way in which I dictate that this is a block, and I want to be able to collapse it and expand it? Something similar to Jupyter where the code is inherently divided to cells.

Currently, I'm doing this:

# ---------------------------------- chunck x blah blah -----------------------

EDIT: Most of comments say that I'm dumb and I don't know how to code efficiently and that I should use functions and classes. Guys, I know how to use those, that's not my question. Thanks.

PyCharm allows you to define 'code cells' when you have 'Scientific Mode' enabled. These code cells are collapsible and expandable. To quote from the PyCharm website :

A “code cell” is a block of lines to be executed all at once in the integrated Python console. You can define cells simply by adding inline comments #%% to your regular Python files. PyCharm detects these comments and shows you a special run icon in the left gutter. Clicking this icon triggers the execution of a cell:

在此处输入图片说明

The only catch is that Scientific Mode and its code cell functionality are only available in PyCharm Professional Edition.

Turns out that the answer is very simple: Select the code, right click, do custom folding

在此处输入图片说明

I sometimes use True conditional statements to create collapsible blocks in PyCharm and other IDEs. This also helps me to visually relate all indented code, access it when needed, and collapse it, when I'm focusing on other parts of my code.

if True:
   # block code goes here

A fancier way is to use a descriptive string in the condition. The description stays visible for a collapsed block. You can also disable these with negation anytime, if needed.

if 'Define similarities':
    Dot = lambda x, y: x @ y
    CosSim = lambda x, y: x @ y / (x @ x)**0.5 / (y @ y)**0.5

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