Spyder is developed on GitHub and the latest release is on the GitHub Spyder Releases Page. Select the Windows Installer:
Microsoft Edge may block the download, select the download and then select Keep:
Select Show More:
Select Keep Anyway:
Double click the Windows application to begin the install:
Select Next:
Select I Agree:
Select Just Me and Next:
Spyder will be installed in:
%LOCALAPPDATA%\spyder-6
Select Next:
Select Install:
Select Next:
Select Finish:
Spyder 6 will display a Start Menu shortcut, right click it and select Pin to Start:
When Spyder is first launched, a prompt to begin a tour will display:
To the bottom right is the IPython Console, where commands can be input individually. Notice the cells are numbered, by execution oder. The code can be input:
In [1]: 'hello'
Out[1]: 'hello'
This value was input and returned as an output. the value can also be assigned to an object name using the =
operator:
In [2]: text = 'hello'
This object name text
displays on the Variable Explorer. It has the type str
. The identifiers from the str
class can be accessed from text
by typing in text.
followed by a ↹
:
If part of an identifier is input for example text.cap
followed by a ↹
, the identifier text.capitalize
will display:
When this is input, the method is referenced and the output displays where the method is defined, in this case, in the str
class:
In [3]: text.capitalize
Out[3]: <function str.capitalize()>
A method is called using parenthesis, the docstring displays, which provided details about any input parameters:
A new str
instance is returned to the console:
In [4]: text.capitalize()
Out[4]: 'Hello'
Note text
remains assigned to the original str
instance 'hello'
. This new str
instance can be assigned to text
which reassigns the value of text
. The right hand side is carried out first (using the original value of text
which was hello
)
In [5]: text.capitalize()
This is then reassigned to the object
name on the right hand side
In [5]: text = text.capitalize()
The value of the new instance now displays under text
in the Variable Explorer:
Other methods such as replace
can be examined. A docstring displays showing the mandatory positional parameters old
(position 0
) and new
(position 1
). This is followed by the optional parameter value
(position 2
) which has a default value -1
, meaning all replacements of the old substring will be replaced with the new substring. Any parameter provided before the /
must be supplied positionally only:
In [6]: text.replace('ll', '7')
Out[6]: 'He7o'
Using named parameters:
In [7]: text.replace(old='ll', new='7')
is not allowed because these parameters occur before the /
in the docstring
If the following is input:
In [8]: text.replace
And replace
is right clicked, it can be inspected (shortcut key Ctrl
+ i
):
This opens more detailed help, in the help pane:
Spyder has a script editor.
The script file can be saved in Documents as script.py
:
In a Python script the #
means a comment:
# Import Libraries
import numpy as np # numeric python library
import matplotlib.pyplot as plt # matrix plotting library
Using #%%
creates a cell:
#%% Import Libraries
import numpy as np
import matplotlib.pyplot as plt
Cells can be collapsed:
Other cells can be created:
#%% Import Libraries
import numpy as np
import matplotlib.pyplot as plt
#%% Create Data
x = np.array([0, 1, 2, 3, 4,])
y = 2 * x
#%% Plot Data
plt.plot(x, y)
A cell from a script file can be ran using the run cell button:
This cell is still highlighted after execution. The cell and advance to the next cell button is more useful when running through each cell in a script file:
The Variables x
and y
display in the Variable Explorer:
The plot displays as a static image using the inline
backend. This static images displays on the plots pane:
The plotting backend can be changed to an interactive plot using the qtagg
backend:
If the last line is selected, the currently selected selection can be run:
The plot now displays in its own window:
The kernel can be restarted, removing all variables and imports by selecting Consoles → Restart Kernel and then selecting Yes. Alternatively typing exit
into the console restarts the kernel:
All variables and imports are lost and the cell execution number returns to 1
:
the script editor will display a list of identifiers from an object
name after a .
:
The figure can be saved using:
#%% Import Libraries
import numpy as np
import matplotlib.pyplot as plt
#%% Create Data
x = np.array([0, 1, 2, 3, 4,])
y = 2 * x
#%% Plot Data
plt.plot(x, y)
#%% Save Figure
plt.savefig('fig1.png')
The entire Script file can be run, using Run File:
the files pane displays the current working directory, which is the same folder, that the script.py
file is stored in. Note fig1.png
is also saved here:
It can be opened externally:
The Variable x
is a ndarray
and can be expanded in the Variable Explorer:
If a deliberate mistake is made in the code, that would introduce a SyntaxError
notice that the script editor displays a warning:
The following code will run, but is not formatted correctly:
Spacing issues can be corrected using the autopep8 formatter. Select format file or extension with autopep8:
Notice the spacing is fixed:
Spyder also has the opinionated formatter black, however black's opinionated formatting gives string quotations that are inconsistent to Python and Python standard libraries. Ruff integration with a ruff.toml file which can be used to specify a preferred quote option such as single quotes isn't available but is a planned feature:
The Edit Menu can be used to Comment/Uncomment several lines of code:
Notice an error is highlighted because the Variables x
and y
are used but not assigned:
A custom function can be created:
def greet_user(user_name):
print(f'Hello {user_name}')
Note every line of code belonging to the code block is indented by 4 spaces:
Blank spaces can be shown on the script editor by selecting source → show blank spaces:
A docstring template can be autogenerated for the function by inputting:
def greet_user(user_name):
"""
print(f'Hello {user_name}')
def greet_user(user_name):
"""
Parameters
----------
user_name : TYPE
DESCRIPTION.
Returns
-------
None.
"""
print(f'Hello {user_name}')
This template can be filled out:
def greet_user(user_name):
"""
greets the user
Parameters
----------
user_name : str
The name of the user.
Returns
-------
None.
"""
print(f'Hello {user_name}')
Note code not part of the function is not indented:
def greet_user(user_name):
"""
greets the user
Parameters
----------
user_name : str
The name of the user.
Returns
-------
None.
"""
print(f'Hello {user_name}')
print('Code not part of the function')
Another cell can be made to call the function:
The cell where the function was defined, will be collapsed, in order to optimise space:
Notice that when the function name is input:
greet_user
that the docstring created displays:
This function can be called and provided with the input string 'Philip'
:
greet_user('Philip')
When this script file is run, the function is called and the print
function in the functions body is used to print 'Hello Philip'
which is shown in the cell output:
In the above script file, the function is defined and called:
If this script file is saved as another script file called module.py
:
Both script.py
and module.py
can be viewed, side by side by selecting split horizontally:
Both script.py
and module.py
are found in the same folder:
This means that module.py
can be imported in script.py
using:
import module # no file extension
Identifiers from the module can be accessed using a .
:
import module
module.
If the panel with module.py
is closed, code can be input in script.py
:
The function greet_user
can be accessed from the imported module
:
import module
module.greet_user('Philip')
When run, the print statement displays in the console:
Alternatively an object
such as a function can be imported from the module
:
from module import user_greeting
exit
will be input to restart the kernel which prevents some issues such as reloading modules. Essentially when an instruction is made to reload a module, it will be skipped as there is a performance loss by loading the same module twice. This is problematic when working on the module as changes aren't reflected.
The function can be imported and called as before:
from module import user_greeting
user_greeting('Philip')
If the module module.py
is copied into a subfolder subfolder
. The module can be accessed from the subfolder by use of a .
in this case:
from subfolder.module import user_greeting
user_greeting('Philip')
module.py
can be copied to __init__.py
. __init__.py
is known as the initialisation file, that is imported when the folder is imported:
from subfolder import user_greeting
user_greeting('Philip')
Identifiers beginning with a double underscore __
and ending in __
are part of the Python datamodel, colloquially they are sometimes called dunder identifiers. These can be accessed from the str
instance text by inputting:
text = 'hello'
text.__
In the console the data model identifiers can be viewed by inputting:
text.__
followed by a ↹
:
If the __add__
data model identifier for example is selected and input with open parenthesis, the docstring displays:
text.__add__(
Note the return value instructs the preferred builtins
function or operator to use, in this case +
:
text + text
The operator behind the scenes uses:
text.__add__(text)
Where the text
instance before the .
is the str
instance the method is called from known as self
. The second instance provided in the function is known as value
:
This method is defined in the str
class. Note when called from the str
class, the instance self
must be provided, in addition to the instance value
:
str.__add__(text, text)
There are a number of data model identifiers in the script file which can be accessed using __
In this case the data model identifiers __file__
and __name__
will be examined:
These can be printed in the script file:
print(__file__)
print(__name__)
Note when this file is run, i.e. is the first input argument to the ipython magic %runfile
, it is regarded as the main script file being executed and has the data model __name__
as '__main__'
:
module.py
and script.py
can be opened side by side. If the following code is in module
:
print(__file__)
print(__name__)
And if the following code is in script
:
import module
When script.py
is run, the code in the module
is run as it is imported. Notice that __name__
is now 'module'
and not '__main__'
. This is because the first input argument %runfile
is script.py
and this is the main script known as '__main__'
:
If module.py
is updated to:
text = 'hello'
if __name__ == '__main__':
print('Diagnostic Code')
Note when module
is run, the instance text
is instantiated and is shown on the Variable Explorer. It is the '__main__'
module and the diagnostic code prints:
If the module is imported in script.py
:
import module
the condition to the if
code block is False
because this is not the '__main__'
module, so the diagnostic code does not run. The variable module.text
is instantiated and can be accessed in the console:
If Help → Dependencies is selected:
A number of mandatory and optional dependencies are listed, which are include libraries from the scientific stack numpy
, pandas
and matplotlib
:
Notice seaborn
is not listed. If it is attempted to be imported:
import seaborn
There is a ModuleNotFoundError
:
seaborn
is not installed.
Spyder uses its own spyder-runtime
environment that is conda based. Spyder is installed in local application data:
%LOCALAPPDATA%
There is a spyder-6
subfolder:
This folder contains the base
, environment. In the scripts subfolder there is a conda.exe
:
The Spyder installer is conda
based, the purpose of the base environment is for use of the conda.exe
which is a package manager that is used to install packages and create Python environments. There is an envs
folder which contaisn Python environments:
The spyder-runtime
environment is in its own subfolder:
The spyder-runtime
environment has its own Scripts
folder which contains its python.exe.
It also has its own Lib
subfolder:
Which contains the standard modules such as datetime.py
which is a single script file:
Or email
which is a folder of script files, including the __init__.py
which recall is imported when the folder is imported:
The site-packages
folder contains third-party libraries:
This has the subfolder folder numpy
:
Which has its __init__.py
file:
There is also the subfolder matplotlib
. This also has a __init__.py
file. Typically for matplotlib
, a module within the library is imported called pyplot
opposed to the entire library:
Note there is no seaborn
subfolder as it is not preinstalled with Spyder.
The Spyder installer is conda
based, the base environment is used to update conda
, which is in turn is used to update the spyder-runtime
environment when there is a Spyder update available. This conda
is not intended to be used by the end user.
Miniforge is a minimal installer for conda
which uses the community channel conda-forge
by default. The Miniforge base
environment is used only for the conda
package manager and other packages are typically installed in separate Python environments. Note Anaconda/Miniconda are not recommended as they use a tainted repository anaconda
by default which has commercial restrictions and older package versions which often result with incompatibilities with the current version of Spyder.
Miniforge is developed on GitHub and the latest release is on the GitHub Miniforge Releases Page. Note Mambaforge is considered obsolete and therefore the installers listed at the top should be avoided.
For Windows the Miniforge3-x.xx.x-x-Windows-x86_64.exe
or Miniforge3-Windows-x86_64.exe
should be selected (these are the same installer):
Microsoft Edge may block the download, select the download and then select Keep:
Launch the Miniforge setup:
Select Next:
Select I Agree:
Select Just Me and Next:
Install in the default location and select Next. This will be within:
%USERPROFILE%
Select Install, using only the recommended options:
It is not recommended to add base
to the Windows Environmental Variables Path as this locks a single environment to the Terminal and is less flexible than initialising conda.
Select next:
Select Finish:
Miniforge will display in the Start Menu:
When launched it displays (base)
, indicating the (base)
environment:
Going to:
%USERPROFILE%
Then Miniforge3
Shows the python.exe
and associated scripts
folder:
The conda.exe
is found here:
Right click the Start Button and select Terminal (Admin):
Select Yes at the User Account Control:
Notice the Windows Terminal has no (base)
because it is not initialised:
To initialise conda, the Windows Terminal execution policy should be set to RemoteSigned using:
Set-ExecutionPolicy RemoteSigned
Then conda
can be initialised by inputting:
.\miniforge3\Scripts\conda init --all
Details about the changes will be listed, close the Terminal:
Right click the Start button and select Terminal. The Admin version should not be sued, it was only used previously so the Execution Policy could be changed:
Notice it now has the (base)
prefix:
Before using conda
it should be updated to the latest version using:
conda update conda
The channels will be conda-forge
by default:
Input y
in order to proceed:
The conda package manager is now updated:
Inputting:
cls
will clear the screen:
A new environment can be created using:
conda create -n spyder-env spyder-kernels python seaborn scikit-learn pyarrow sympy openpyxl xlrd xlsxwriter lxml sqlalchemy tabulate pyqt ffmpeg ruff
This has spyder-kernels
which is required for Spyder to use the environment. seaborn
which has numpy
, pandas
and matplotlib
as dependencies. scikit-learn
for machine learning. pyarrow
, openpyxl
, xlrd
, xlsxwriter
, lxml
, sqlalchemy
, tabulate
for various file pandas formats. pyqt
for matplotlib's interactive backend and ffmpeg
for saving matplotlib animations.
-n
means name and spyder-env
is the name of the Python environment. Specifying an environment using -n
means changes to that environment will be made opposed to base
which is the currently activate environment.
These packages will all be installed from the conda-forge
channel. In the spyder-env
folder which is found in the envs
subfolder of base
:
Details about packages to be downloaded will be shown:
Details about packages to be installed will be shown:
Input y
in order to proceed:
The packages are installed in the environment but it is not activated:
To activate it use:
conda activate spyder-env
Notice the prefix is now (spyder-env)
meaning this environment is activated:
An ipython
shell can be launched:
Notice two programming languages are used, highlighted is PowerShell using the programming language PowerShell and below is the ipython shell using the python programming language:
If email
, datetime
, numpy
, matplotlib
, pandas
and seaborn
are imported, their __file__
can be checked. Notice these are in the spyder-env
environment:
In Spyder, the default environment spyder-runtime
is selected:
Go to Tools → Preferences:
Select IPython Interpretter:
Select Use the Following Interpretter and select spyder-env
(conda) from the dropdown list:
Select Apply:
Close Spyder and relaunch. spyder-env
should be shown at the bottom and now seaborn can be imported:
import seaborn as sns
MikTex is required in order to use TeX in matplotlib. MikTex can be downloaded from its software download page MikTeX Downloads:
Launch the installer:
Accept the License Agreement and select Next:
Select Install only for me and select Next:
Use the default file location in:
%LOCALAPPDATA%
and select Next:
Select Next:
Select Start:
Select Next:
Select Next:
Select Close:
MikTeX will display in the notification tray, select it:
Select Updates and select Update Now:
Close the MikTeX Console to update the MikTex Console:
Select Packages and search for type1cm
, select Install:
Select OK:
Repeat for cm-super
, geometry
, underscore
, and zhmetrics
.
The default plot backend can be changed, by selecting Tools → Preferences:
Then IPython Console → Graphics and changing the backend to Qt:
If the following is plotted:
#%% Import Libraries
import numpy as np
import matplotlib.pyplot as plt
#%% Create Data
x = np.array([0, 1, 2, 3, 4,])
y = 2 * np.pi * np.sin(x)
#%% Plot Data
plt.plot(x, y)
plt.xlabel(R'$x$', usetex=True)
plt.ylabel(R'$2 \pi \sin{x}$', usetex=True)
Tex will render in the figure labels. This may take a couple of minutes for the first plot with TeX, while matplotlib configures the system fonts.
The automatic backend does not stay on top, when Spyder is selected, the plot is behind Spyder:
This can be changed using PowerToys. PowerToys is developed on GitHub and the latest release is on the GitHub Spyder Releases Page. Select the Per User Installer:
Launch the installer:
Select I Agree to the License Terms and Conditions:
Select Close:
The shortcut key ⊞
, Alt
+ t
can be usd to toggle on/of Always On Top:
This allows modification and visualisation of the plot using the console.
Other useful tools are available such as a color picker which is activated using ⊞
, ⇧
+ c
:
There is a new release of Spyder, approximately every month. When available a prompt for the upgrade should display and Spyder should update using packages from conda-forge
using its internal conda
package manager:
If an external conda environment was created, it will need to be updated, with a compatible version of spyder-kernels
. Open up the Windows Terminal an updte the conda
package manager in base:
conda update conda
Then activate spyder-env
and searh for updates to all packages:
conda activate spyder-env
conda update --all