Python

Tricks

Class inheritance

  • Use constructor from Base(i.e. Parent) class in the Child class, along with child’s constructor.
class a:
    def __init__(self,x):
        self.x = x
    def se(self,z):
        print(z*2)

class b(a):
    def __init__(self,x,y):
        self.y = y
        super().__init__(x)

We can use Base class methods(i.e. functions) by doing this:

b(1,2).se(3)

We can call constructor of Parent class by doing this:

b(1,2).x

We can call constructor of Child class by doing this:

b(1,2).y

Merging two dictionaries in Python 3.x

d1 = {"a":1, "b":2}
d2 = {"c":3, "d":4}
d1Ud2 = {**d1, **d2}

# Output: d1Ud2 = {"a":1, "b":2, "c":3, "d":4}

Circular Dependencies

I strongly suggest to see “NameError while calling the parent class method from another module” for more details.

Function annotation

This allows us to attach metadata to functions describing their parameters and return values. Read at PEP 3107 For example:

def kinetic_energy(m:'in KG', v:'in M/S')->'Joules':
        return 1/2*m*v**2

# Output: kinetic_energy.__annotations__ returns {'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}

'{:,} {}'.format(kinetic_energy(20,3000), kinetic_energy.__annotations__['return'])
# Output: 90,000,000.0 Joules'

Tips

Type tilda in MacBook

  • You type the accent tilde (shift `) then space: ~

Install Miniconda/Anaconda

  • Download it from its website then, in ubuntu
bash FILENAME.sh
  • To use Python in zsh
conda update conda
conda init zsh
  • To activate conda without showing (base)>
conda activate

or,

conda config --set changeps1 False
  • Install packages in a virtual environment
conda install -n tf PackageName
  • To see the list of virtual environments
conda env list

Or, you can also use

conda info --envs
  • To delete a virtual environment
conda env remove -n tf

Google Collab

  • Accessing file from Google drive
from google.colab import drive
drive.mount('/content/drive')
  • View LaTeX in Jupyter notebook
from IPython.display import Math, HTML
display(HTML("<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/"
               "latest.js?config=default'></script>"))
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
  • Install LaTeX using Jupyter cell in Ubuntu
!sudo apt-get update
!sudo apt-get install texlive-full
!sudo apt install texlive-latex-base
!sudo apt install texlive-fonts-extra

Install package from github

pip install git+https://github.com/titipata/arxivpy

Install Manim

  1. Install latex

  2. Install cairo, latex, ffmpeg, and sox by doing these inside Jupyter notebook’s cell:

!sudo apt-get install ffmpeg
!sudo apt-get install sox
!sudo apt-get install libcairo2-dev libjpeg-dev libgif-dev python3-dev libffi-dev
!python3 -m pip install pyreadline
!python3 -m pip install pydub
!python3 -m pip install pycairo
!pip install -r requirements.txt
  1. Clone Manim library
!git clone https://github.com/3b1b/manim.git
  1. Checking!
!cd manim
!python3 -m manim example_scenes.py SquareToCircle -pl
!python3 -m manim example_scenes.py OpeningManimExample -pl

Any issues see this Manim Tutorial.

  • Writing python file from Google collab notebook
%%writefile filename.py
# Write your python code below
print("Visit PhysicsLog.com")
  • Viewing the working directory
!ls
  • Accessing and run python file
!python3 filename.py

Running jupyter notebook(or lab) in wsl

  • Generate your notebook config
    jupyter notebook --generate-config
    
  • Edit the file at: ~/.jupyter/jupyter_notebook_config.py and disable launching browser by redirect file by changing this line to False (default value is True).

Simple HTTP server in Python

python -m SimpleHTTPServer  # In python 2
python -m SimpleHTTPServer <port number>

python3 -m http.server  # In python 3

Permalink at https://www.physicslog.com/cs-notes/python

Published on May 28, 2021

Last revised on Jul 2, 2023

References