Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Section divider in Spyder

Tags:

python

spyder

Is there a section divider in Spyder that is similar to R's '--'? Using '--' in R script automatically divide codes in different sections. One can find different sections, especially if the code is long. I wonder if there is a similar feature in Spyder.

Currently, I'm just using """ or ## such as

"""
Created on Mon Feb 11 11:24:15 2019

"""

or

##Section 1

They do not divide code in sections.

like image 429
Roger Avatar asked May 11 '19 02:05

Roger


2 Answers

I'm not sure how it works on R, but you can use lines that start with comments of the form:

# %%

Different parts of your code are separated by them and then you can run each section separately if you want.

like image 85
s.devia10 Avatar answered Sep 28 '22 02:09

s.devia10


Here are some examples :

Example 1 : One cell with navigable sections

#%% Notes

#### Defining Code Cells
# A “code cell” in Spyder is a block of lines, typically in a script, that can be 
# easily executed all at once.
# You can separate cells by lines starting with either: 
# 1) #%% (standard cell separator)
# 2) # %% (standard cell separator, when file has been edited with Eclipse)
# 3) # <codecell> (IPython notebook cell separator)

#### Cell heirarchy
# To nest navigable sections within a cell, use "#### ~some heading~"
# To nest subcells within a cell, use "#%% >> #%%% >> #%%%% .... "

In Outline Explorer (Spyder) appears as:

File.py
  % Notes
    # Section 1
    # Section 2

Example 2 : Cell with subcells

#%% Main cell

#%%% Nested cell 1
#%%%% Nested(2) cell 1
#%%%% Nested(2) cell 2

#%%% Nested cell 2

Using this structure, the nested cells can be executed separately.

File.py
  % Main Cell
    % Nested cell 1
      % Nested(2) cell 1
      % Nested(2) cell 2
    % Nested cell 2
like image 22
rahul-ahuja Avatar answered Sep 28 '22 01:09

rahul-ahuja