Skip to content

Latest commit

 

History

History
64 lines (49 loc) · 6.72 KB

File metadata and controls

64 lines (49 loc) · 6.72 KB

Flashcards — Python Fundamentals

Spaced-repetition deck covering Modules 1–6: environment setup, data types, operators, control flow, functions, and object-oriented programming. Uses the Obsidian spaced-repetition Question::Answer format.

Environment and Versions

Which Python version should new security tooling target?::Python 3.9 or newer — Path.is_relative_to() and zoneinfo arrived in 3.9, and Python 2 has been end-of-life since 2020. Why should you never run sudo pip install?::It writes into the system interpreter, can break distribution tooling (Kali ships many Python-based tools), and mixes engagement dependencies into the OS. What does a virtual environment give you?::An isolated interpreter and package set per project, so dependencies never collide and a pinned requirements.txt reproduces the environment exactly. Which command creates and activates a venv on Linux?::python3 -m venv .venv then source .venv/bin/activate. Why pin dependencies with pip freeze > requirements.txt?::So a scan or exploit reruns identically on a retest months later, rather than silently picking up different library versions.

Data Types

What is the difference between str and bytes?::str is text (Unicode); bytes is raw binary. Sockets and hash functions require bytes — convert with .encode("utf-8") and .decode(). When should you use a set instead of a list?::When you need uniqueness or fast membership tests — in is O(1) on a set and O(n) on a list. You give up ordering. Why is a tuple usable as a dictionary key but a list is not?::Tuples are immutable and therefore hashable; lists are mutable and unhashable. What does / return in Python 3?::Always a float. Use // for integer (floor) division. Why does 0.1 + 0.2 == 0.3 evaluate to False?::Binary floating point cannot represent those decimals exactly. Compare with math.isclose(), or use decimal.Decimal for exact arithmetic. What is wrong with def scan(hosts=[])?::The default list is created once at definition time and shared across every call. Use hosts=None and create the list inside the function.

Operators

What is the difference between == and is?::== compares values; is compares object identity. Reserve is for None, True, and False. Why is if x: wrong when you mean if x is not None:?::Empty containers, empty strings, and 0 are all falsy, so a legitimate empty or zero result is treated as missing. Why compare secrets with hmac.compare_digest() rather than ==?::== short-circuits at the first differing byte, leaking information about the secret through timing. What does short-circuit evaluation mean for and?::Evaluation stops at the first falsy operand — so if in_scope(h) and probe(h): never probes a host that failed the scope check. How do you write a range check idiomatically?::A chained comparison, e.g. 0 < port <= 65535.

Control Flow

Where does the filtering if go in a list comprehension?::At the end, after the for clause, and it takes no else: [x for x in it if cond]. Where does a conditional expression go in a comprehension?::Before the for clause, and it must have an else: [a if cond else b for x in it]. What does the else clause on a for loop do?::It runs when the loop completes without hitting break. Why must a retry loop be bounded?::An unbounded while loop retrying a failing network call hammers the target and never terminates. Bound it with an attempt counter or a deadline. What happens if you mutate a list while iterating over it?::Elements are silently skipped. Iterate over a copy, or build a new list. When should you use a generator expression instead of a list comprehension?::When you iterate only once and the data is large — a generator streams with constant memory instead of building the whole list.

Functions

What is the difference between *args and **kwargs?::*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. Are Python arguments passed by value or by reference?::By object reference — mutating a passed list changes it for the caller; rebinding the name does not. What does a function return when it has no return statement?::None. What is a decorator?::A callable that wraps a function to add behaviour — retry, timing, logging, or authorization — without modifying the function body. Why prefer a comprehension over map() with a lambda?::It is more readable, and it avoids creating a throwaway function for a one-line transformation.

Object-Oriented Programming

What is the difference between a class attribute and an instance attribute?::A class attribute is defined in the class body and shared by every instance; an instance attribute is assigned on self and unique per object. Lookup checks the instance first, then the class. Why is a mutable class attribute dangerous?::Every instance shares the same object, so one target's results appear under another's. Initialise mutable state in __init__ instead. When should a method be a @classmethod?::When it needs the class but not an instance — typically an alternate constructor. It must build with cls(...) so subclasses work correctly. When should a method be a @staticmethod?::When it belongs to the class conceptually but needs neither self nor cls. If a class accumulates many, a plain module is usually clearer. What does super() actually do?::It delegates to the next class in the method resolution order — not simply "the parent". That is what makes cooperative multiple inheritance and mixins work. Why is __private not a security control?::Double underscores trigger name mangling to _ClassName__private, which is trivially reachable. It prevents accidental collisions, not access. What is the difference between __str__ and __repr__?::__str__ is the human-readable form used by print(); __repr__ is the unambiguous developer form used by the REPL, containers, and tracebacks. If you write only one, write __repr__. What happens if you define __eq__ without __hash__?::The class becomes unhashable and cannot be used in a set or as a dict key. Use @dataclass(frozen=True) or define __hash__ too. What is duck typing?::Code depends on an object having the method it calls, not on its class. The contract is implicit and failures appear at call time. When is an abstract base class better than duck typing?::At plugin or public-API boundaries, where you want the contract enforced at instantiation rather than discovered mid-run.

Related

  • [[Python-Environment-Setup/Readme|Python Environment Setup]] through [[Object-Oriented-Programming/Readme|Object-Oriented Programming]] — the modules this deck drills
  • [[Flashcards/Readme|Flashcards]] — deck index
  • [[Readme|Python for Security Professionals]] — course home