Dividing Python module into multiple regions
Asked Answered
V

12

93

In C# we can create regions by using

#region
// some methods
#endregion

Is there any way to format python code in similar fashion so that I can keep all my relevant methods in one block?

Vina answered 25/11, 2011 at 6:42 Comment(0)
B
13

I recommend you have a look at PyDev. If you structure your Python code well it will be very useful to have a document outline and code folding. Unfortunately I don't think you can do arbitrary structures like #region C# (VS) or #pragma mark in C/C++/ObjC (Xcode/CDT).

Bucharest answered 25/11, 2011 at 6:56 Comment(3)
Note that in PyDev, if you add a comment starting with: "#---", that comment should appear in the outline to help you structure things (you can do ctrl+shift+4 on a line to add that comment block).Ovine
True. Still not the same as #region, but very useful anyway.Bucharest
Actually, I've found #region and #endregion working quite FINE in VSCode as well.Perspicacious
L
128

Looks like PyCharm has it, see here: https://www.jetbrains.com/help/pycharm/2016.1/code-folding.html#using_folding_comments

For Python files, the following two styles are supported. You should not mix both of them in a single file.

#<editor-fold desc="Description">
...
#</editor-fold>

or

#region Description
...
#endregion

Visual Studio accepts "region" too

Layla answered 26/11, 2013 at 18:50 Comment(7)
The link is not valid anymore. Any tips?Mukund
Don't worry about the link, in PyCharm, simply use #region and #endregionEschatology
Can confirm that this works in VS Code too. beginning a region with #region and ending it with #endregionSubdeacon
Using this in VSCode & Pycharm... it's awesome! thank you!Huck
Sadly, it appears the reformatter Black likes neither syntax and inserts a space after the # in both instancesDiplomate
PyCharm seems to cope okay with having a space after the #.Maladminister
In PyCharm, you also have to activate region folding by ticking Settings > Editor > General > Code Folding > Custom folding regions (latest tested in version 2023.1)Jadajadd
N
20

With Python Tools for Visual Studio you can use:

#region My Block of Code
def f1():
    pass
def f2():
    pass
#endregion

Then you can fold the regions same way you do on C#.

Nomothetic answered 27/11, 2015 at 2:5 Comment(0)
S
15

With VS Code you can simply create regions like this and even add names for the regions:

#region some name
#Some very long code
#endregion

It can be then folded into the following:

#region some name...
Scopolamine answered 21/4, 2019 at 17:22 Comment(4)
How is your answer different to @DarienPardinas's answer? Your answer is 4 years older and you forgot to mention that you need Python Tools to get this functionality.Dowery
@DarienPardina's answer is about Visual Studio, mine is for VS Code. But you are probably right that VS Code extension for Python is needed marketplace.visualstudio.com/items?itemName=ms-python.pythonScopolamine
Fair enough. Might be good to include that link into your answer. :)Dowery
Thanks to you, the link is now included in the comment ;) I think that's enough. But I highly doubt that someone will code in Python in VS Code without this extension already installed.Scopolamine
B
13

I recommend you have a look at PyDev. If you structure your Python code well it will be very useful to have a document outline and code folding. Unfortunately I don't think you can do arbitrary structures like #region C# (VS) or #pragma mark in C/C++/ObjC (Xcode/CDT).

Bucharest answered 25/11, 2011 at 6:56 Comment(3)
Note that in PyDev, if you add a comment starting with: "#---", that comment should appear in the outline to help you structure things (you can do ctrl+shift+4 on a line to add that comment block).Ovine
True. Still not the same as #region, but very useful anyway.Bucharest
Actually, I've found #region and #endregion working quite FINE in VSCode as well.Perspicacious
C
9

To keep PyCharm from complaining about the PEP 8 violation use

#  region region name here
your code here
#  endregion
Cummings answered 28/2, 2018 at 22:25 Comment(0)
G
3

I know it is a older post, currently with VS CODE in version 1.53.2 it is possible to use #region [name of the region] [block of code] #endregion [the same name of the region you put in the beginning of region]

#region NameOfRegion
def name().....
#endregion NameOfRegion

region retracted expanded region

Gamo answered 26/2, 2021 at 16:14 Comment(0)
R
1

In sublime text 3 you can simply type a comment and indent your code as if it was under the comment and then you can fold it just like C#

# Region
    (some code here...)
Roddie answered 16/2, 2017 at 8:39 Comment(1)
Bad idea, as depending on the interpreter it extra indents in python can be illegal.Scandinavian
C
1

Yes you can in same way as we did in c#,but keep in mind this is for pycharm IDE example

#region Description
...
#endregion

reference here

Chace answered 27/5, 2017 at 7:4 Comment(0)
L
1

Not sure if this works in other editors, but in spyder

# %%

starts a new section. Can be used to fold code or run just segments of code.

Landscape answered 6/9, 2022 at 2:48 Comment(0)
S
1

In PyCharm:

# region ----- description
...
# endregion

In Visual Studio Code with Python expansion:

#region ----- description
...
#endregion
Sturm answered 1/10, 2022 at 15:6 Comment(0)
F
0

without any need for any other tool, I cheat nasty with this :-

true=True if true:

and then fold the if statement using the basic editor tools.

Nesting them means is is possible to fold up groups of blocks

Foremast answered 5/7, 2021 at 6:22 Comment(2)
Actually started almost exclusively regioning as suggested by @GamoForemast
(tl;dr) Knowing the IDE/Editor would be more helpful Really, this question is not about C#, or Python, since comparative use of comment markups is only relevant to the IDE/Editor in use at the time - the questioned might have been better advised to provide a little context in terms of their IDE/Platform to better inform respondents as to the true thrust of the question in order to deliver more relevant and appropriate answers more deserving of reputation.Foremast
H
-7

Just use classes ... not sure why this is so difficult

class MyNewClass:
    def MyFirstMethod(self):
        print("MyFirstMethod in MyFirstClass")

This will provide the structure you are looking for. Tested and works since Python 2.6

if you have not used classes in Python you can call them much like you do in c#

x = MyNewClass()
x.MyFirstMethod()

Enjoy

Headwork answered 31/3, 2014 at 16:14 Comment(3)
Class use like this is more akin to namespaces than regions.Babyblueeyes
Not a reasonable solution. Take the example of django's models. Models are generally very fat, with plenty of data, and plenty of methods to act upon that data. Once a model gets to a reasonable size, it's a good idea to partition up the fields to sit closer to their methods. Using folding tags to highlight the regions is a perfect use. Now I can quickly identify where I should put a new method to do with state management, a new field to do with payment information, etc.Erebus
Even with static or class methods you will have to type more to use the method or property, with instance ones you will have to initialize the class. So for organizing the class in regions you will have to deal with 2 classes?Guardianship

© 2022 - 2024 — McMap. All rights reserved.