Python
TODOs¶
- Python glossary
- How I've gotten better at Python
- Python Tricks
- Dan Bader of RealPython
- Python Morsels
- Trey Hunner weekly emails
- Python Tricks
- Keep up to date
Functions¶
Forced name params¶
- pass a
*
to separate positional args and keyword args
Mark a function as deprecated¶
- https://github.com/tantale/deprecated
- decorator
Trivia¶
def yell():
pass
bark = yell
del yell # only deletes one pointer to the function
bark() # still in the heap because there's still one pointer left
CLI¶
-m
flag: Module¶
python -m module_name args
- run a
m
odule python -m http.server
- start http server on port 8000 in current directory
python -m pdb path/to/file.py
- debug a Python script
python -m pip install ...
- guarantee that you're running the version of
pip
that's connected to the currentpython
- guarantee that you're running the version of
-i
flag: Interactive¶
Debug the state of a broken Python code when it crashed!
Although you should use breakpoint()
and pdb
$ python3 -i add.py 4 7
Traceback (most recent call last):
File "/home/trey/add.py", line 5, in <module>
print(sum(numbers))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
# can debug to see the state of the program when it crashed!
>>> __name__
'__main__'
>>> sys.argv
['add.py', '4', '7']
>>> numbers
['4', '7']
File system¶
Path¶
from pathlib import Path
file_directory = Path(__file__).parent.resolve()
another_path = file_directory / "sql_scripts"
Get an environment variable value¶
os.getenv()
is an alias to os.environ.get()
Equality¶
==
vs is
¶
is
: same ID- place in the stack/heap
id(x) => 140079600030400
==
: uses__eq__
- by default,
==
delegates tois
- by default,
isinstance
vs type()
¶
type
: returns the name of the typeisinstance([1,2,3], list)
- goes up the inheritance tree
- can catch more than comparing two
type
s
walrus operator¶
- new in Python 3.8
- assignment expression
- merge two lines into one
- assignment statements needs to be on their own line
- When to use?
- only if it makes your code more readable
Random¶
Pseudorandom¶
Closer to true random¶
Last update:
2023-04-24