Python - robbiehume/CS-Notes GitHub Wiki
Colab Notebooks
Links
- Python Functions: Lambdas, Closures, Decorators, and Currying
- Intro to Advanced Python Topics
- Good example project
- Advanced topics (Medium)
General resource websites:
Look into
- funcy: https://funcy.readthedocs.io/en/stable/overview.html
- pprint: https://docs.python.org/3/library/pprint.html
General Notes
- Check if variable or attribute exists, without causing an error if it doesn't:
-
if 'myVar' in locals(): # myVar exists in local scope if 'myVar' in globals(): # myVar exists in global scope if hasattr(obj, 'attr_name'): # obj.attr_name exists
-
- Convert str to json, only if it exists
data = json.loads(body) if (body := event.get("body")) else body
Python Environment Notes
pip
- Install pip: link
- PyPI is the central repository of software that pip uses to download from
- pip installs packages, which are usually bunded into 'wheels' (.whl) prior to installation
- A wheel is a zip-style archive that contains all the files necessary for a typical package installation
- It may be best to run it as
python3 -m pip
instead of using the system-installed pip- Why you should use
python -m pip
- This uses executes pip using the Python interpreter you specified as python
- This is beneficial so you know what pip version is being used if you have multiple python versions installed
- Why you should use
Tips
- See package dependencies:
pipdeptree
- Install it first with
pip install pipdeptree
- Install it first with
- Loop through n first elements in list link:
for item in itertools.islice(my_list, n)
Wheel files (.whl)
Virtual environments (venv)
- Complete guide to python virtual environments
- Virtual environments are used when you want to be more explicit and limit packages to a specific project
- You should never install stuff into your global Python interpreter when you develop locally
- To create an environment:
python -m venv
Version features
3.8
- Assignment Expressions (link): can use
:=
in an expression in a while loop or if statement to assign and evaluate it- Ex:
if (y := 2) > 1:
# sets y = 2 and evaluates the expression as 2 > 1 - Ex:
while (user_input := input("Enter text: ")) != "stop":
# keeps getting user input until "stop" is entered - Can also use it in list comprehensions:
[result for i in range(5) if (result := func(i)) == True]
- It is more efficient because it potentially only makes half the func() calls compared to
[func(i) for i in range(5) if func(i) == True]
- It is more efficient because it potentially only makes half the func() calls compared to
- Ex:
3.9
- Dictionary unions:
d1 | d2
results in new dictionary resulting from the union of d1 and d2- Can use
|=
to do an in-place union:d1 |= d2
// will make d1 equal to the resulting union
- Can use
- String methods to remove prefix and suffixes:
.removeprefix()
and.removesuffix()
Python Language Notes
Variables and parameter passing
- Deep dive into variables in Python
- Python uses pass-by-object-reference for function parameter passing
- Any changes to the actual object held in the parameter will change the original variable
- Any reassignment will not be reflected in the original variable
- When passing a variable of a mutable object (list, dict, set, classes, etc.), make sure that you pass a copy if you don't want the original variable object to be modified by any changes in the function
Dunder Methods (aka Magic Methods)
- Dunder methods are methods that allow instances of a class to interact with the built-in functions and operators of the language
** (un)packing
Add to google colab:
- String methods:
.startswith()
and.endswith()
instead of string slicing - Create dictionary from two diffferent sequences / collections:
dict(zip(list1, list2))
- Update multiple key/value pairs in a dticitonary:
d1.update(key1=val1, key2=val2)
ord1.update({'key1': 'val1', 'key2': 'val2'})
- Ex:
class_grades.update(algebra='A', english='B')
- Ex:
Dictionaries:
Generators:
http, requests, & urllib(3) modules
http
requests
urllib3
- placeholder