Skip to content

Latest commit

 

History

History
1147 lines (661 loc) · 33.3 KB

File metadata and controls

1147 lines (661 loc) · 33.3 KB

Spyder IDE Windows Setup

Downloading and Installing Spyder

Spyder is developed on GitHub and the latest release is on the GitHub Spyder Releases Page. Select the Windows Installer:

img_001

Microsoft Edge may block the download, select the download and then select Keep:

img_002

img_003

Select Show More:

img_004

Select Keep Anyway:

img_005

Double click the Windows application to begin the install:

img_006

Select Next:

img_007

Select I Agree:

img_008

Select Just Me and Next:

img_009

Spyder will be installed in:

%LOCALAPPDATA%\spyder-6

Select Next:

img_010

img_011

img_012

Select Install:

img_013

Select Next:

img_014

Select Finish:

img_015

Spyder 6 will display a Start Menu shortcut, right click it and select Pin to Start:

img_016

Spyder IDE Basics

When Spyder is first launched, a prompt to begin a tour will display:

img_017

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'

img_018

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'

img_019

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 :

img_020

If part of an identifier is input for example text.cap followed by a , the identifier text.capitalize will display:

img_021

img_022

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()>

img_023

A method is called using parenthesis, the docstring displays, which provided details about any input parameters:

img_024

A new str instance is returned to the console:

In [4]: text.capitalize()
Out[4]: 'Hello'

img_025

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:

img_026

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:

img_027

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

img_028

If the following is input:

In [8]: text.replace

And replace is right clicked, it can be inspected (shortcut key Ctrl + i):

img_029

This opens more detailed help, in the help pane:

img_030

Spyder has a script editor.

img_031

The script file can be saved in Documents as script.py:

img_032

img_033

img_034

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

img_035

Using #%% creates a cell:

#%% Import Libraries
import numpy as np 
import matplotlib.pyplot as plt 

Cells can be collapsed:

img_036

img_037

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:

img_038

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:

img_039

img_040

The Variables x and y display in the Variable Explorer:

img_041

The plot displays as a static image using the inline backend. This static images displays on the plots pane:

img_042

The plotting backend can be changed to an interactive plot using the qtagg backend:

img_043

If the last line is selected, the currently selected selection can be run:

img_044

The plot now displays in its own window:

img_045

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:

img_046

All variables and imports are lost and the cell execution number returns to 1:

img_047

the script editor will display a list of identifiers from an object name after a .:

img_048

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')

img_049

The entire Script file can be run, using Run File:

img_050

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:

img_051

It can be opened externally:

img_052

img_053

The Variable x is a ndarray and can be expanded in the Variable Explorer:

img_054

img_055

If a deliberate mistake is made in the code, that would introduce a SyntaxError notice that the script editor displays a warning:

img_056

The following code will run, but is not formatted correctly:

img_057

Spacing issues can be corrected using the autopep8 formatter. Select format file or extension with autopep8:

img_058

Notice the spacing is fixed:

img_059

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:

img_060

The Edit Menu can be used to Comment/Uncomment several lines of code:

img_061

Notice an error is highlighted because the Variables x and y are used but not assigned:

img_062

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:

img_063

Blank spaces can be shown on the script editor by selecting source → show blank spaces:

img_064

img_065

A docstring template can be autogenerated for the function by inputting:

def greet_user(user_name):
    """
    print(f'Hello {user_name}')

img_066

img_067

def greet_user(user_name):
    """
    

    Parameters
    ----------
    user_name : TYPE
        DESCRIPTION.

    Returns
    -------
    None.

    """
    print(f'Hello {user_name}')

This template can be filled out:

img_068

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')

img_069

Another cell can be made to call the function:

img_070

The cell where the function was defined, will be collapsed, in order to optimise space:

img_071

img_072

Notice that when the function name is input:

greet_user

that the docstring created displays:

img_073

This function can be called and provided with the input string 'Philip':

greet_user('Philip')

img_074

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:

img_075

In the above script file, the function is defined and called:

img_076

If this script file is saved as another script file called module.py:

img_077

img_078

Both script.py and module.py can be viewed, side by side by selecting split horizontally:

img_079

Both script.py and module.py are found in the same folder:

img_080

This means that module.py can be imported in script.py using:

import module # no file extension

img_081

Identifiers from the module can be accessed using a .:

import module 
module.

img_082

If the panel with module.py is closed, code can be input in script.py:

img_083

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:

img_084

Alternatively an object such as a function can be imported from the module:

img_085

from module import user_greeting

img_086

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')

img_087

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')

img_088

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')

img_089

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.__

img_090

In the console the data model identifiers can be viewed by inputting:

text.__

followed by a :

img_091

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

img_092

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:

img_093

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:

img_094

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__':

img_095

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

img_096

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__':

img_097

If module.py is updated to:

text = 'hello'

if __name__ == '__main__':
    print('Diagnostic Code')

img_098

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:

img_099

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:

img_100

ModuleNotFoundError

If Help → Dependencies is selected:

img_101

A number of mandatory and optional dependencies are listed, which are include libraries from the scientific stack numpy, pandas and matplotlib:

img_102

Notice seaborn is not listed. If it is attempted to be imported:

import seaborn

There is a ModuleNotFoundError:

img_103

seaborn is not installed.

spyder-runtime Environment

Spyder uses its own spyder-runtime environment that is conda based. Spyder is installed in local application data:

%LOCALAPPDATA%

img_104

There is a spyder-6 subfolder:

img_105

This folder contains the base, environment. In the scripts subfolder there is a conda.exe:

img_106

img_107

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:

img_111

The spyder-runtime environment is in its own subfolder:

img_112

The spyder-runtime environment has its own Scripts folder which contains its python.exe. It also has its own Lib subfolder:

img_113

Which contains the standard modules such as datetime.py which is a single script file:

img_114

Or email which is a folder of script files, including the __init__.py which recall is imported when the folder is imported:

img_115

The site-packages folder contains third-party libraries:

img_116

This has the subfolder folder numpy:

img_117

Which has its __init__.py file:

img_118

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:

img_119

img_120

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 Installation

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):

img_121

img_122

Microsoft Edge may block the download, select the download and then select Keep:

img_123

img_124

img_125

Launch the Miniforge setup:

img_126

Select Next:

img_127

Select I Agree:

img_128

Select Just Me and Next:

img_129

Install in the default location and select Next. This will be within:

%USERPROFILE%

img_130

img_131

img_132

Select Install, using only the recommended options:

img_133

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:

img_134

Select Finish:

img_135

Miniforge will display in the Start Menu:

img_136

When launched it displays (base), indicating the (base) environment:

img_137

Going to:

%USERPROFILE%

img_138

img_139

Then Miniforge3

img_140

Shows the python.exe and associated scripts folder:

img_141

The conda.exe is found here:

img_142

Initialising conda with the Windows Terminal

Right click the Start Button and select Terminal (Admin):

img_143

Select Yes at the User Account Control:

img_144

Notice the Windows Terminal has no (base) because it is not initialised:

img_145

To initialise conda, the Windows Terminal execution policy should be set to RemoteSigned using:

Set-ExecutionPolicy RemoteSigned

img_146

Then conda can be initialised by inputting:

.\miniforge3\Scripts\conda init --all

img_147

Details about the changes will be listed, close the Terminal:

img_148

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:

img_149

Notice it now has the (base) prefix:

img_150

Creating a Custom spyder-env Environment (conda)

Before using conda it should be updated to the latest version using:

conda update conda

img_151

The channels will be conda-forge by default:

img_152

Input y in order to proceed:

img_153

The conda package manager is now updated:

img_154

Inputting:

cls

will clear the screen:

img_155

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.

img_156

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:

img_157

Details about packages to be downloaded will be shown:

img_158

Details about packages to be installed will be shown:

img_159

Input y in order to proceed:

img_160

The packages are installed in the environment but it is not activated:

img_161

To activate it use:

conda activate spyder-env

img_162

Notice the prefix is now (spyder-env) meaning this environment is activated:

img_163

An ipython shell can be launched:

img_164

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:

img_165

If email, datetime, numpy, matplotlib, pandas and seaborn are imported, their __file__ can be checked. Notice these are in the spyder-env environment:

img_166

Selecting the Custom spyder-env Environment (conda)

In Spyder, the default environment spyder-runtime is selected:

img_167

Go to Tools → Preferences:

img_168

Select IPython Interpretter:

img_169

Select Use the Following Interpretter and select spyder-env (conda) from the dropdown list:

img_170

Select Apply:

img_171

Close Spyder and relaunch. spyder-env should be shown at the bottom and now seaborn can be imported:

import seaborn as sns

img_172

MikTek Installation

MikTex is required in order to use TeX in matplotlib. MikTex can be downloaded from its software download page MikTeX Downloads:

img_173

img_174

Launch the installer:

img_175

Accept the License Agreement and select Next:

img_176

Select Install only for me and select Next:

img_177

Use the default file location in:

%LOCALAPPDATA%

and select Next:

img_178

Select Next:

img_179

Select Start:

img_180

Select Next:

img_181

Select Next:

img_182

Select Close:

img_183

MikTeX will display in the notification tray, select it:

img_184

Select Updates and select Update Now:

img_185

Close the MikTeX Console to update the MikTex Console:

img_186

Select Packages and search for type1cm, select Install:

img_187

Select OK:

img_188

Repeat for cm-super, geometry, underscore, and zhmetrics.

Changing Default Plot Backend

The default plot backend can be changed, by selecting Tools → Preferences:

img_189

Then IPython Console → Graphics and changing the backend to Qt:

img_190

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)

img_191

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.

PowerToys

The automatic backend does not stay on top, when Spyder is selected, the plot is behind Spyder:

img_192

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:

img_193

img_194

Launch the installer:

img_195

Select I Agree to the License Terms and Conditions:

img_196

Select Close:

img_197

The shortcut key , Alt + t can be usd to toggle on/of Always On Top:

img_198

img_199

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:

img_200

img_201

img_202

Updating

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

Return to Python Tutorials