Google IT Automation with Python flashcards
Google IT Automation with Python · Build recall with a focused review session.
32 cards. Read the term and the definition here. The deck at the top of this page is optional.
- Mutable vs immutable types
- Lists, dicts, and sets are mutable and change in place, so aliases see edits. Ints, floats, strings, and tuples are immutable; rebinding a name creates a new object instead.
- Slice stop exclusion
- In s[start:stop:step], the stop index is excluded. s[0:3] returns the first three characters, and a negative step like s[::-1] reverses the sequence.
- dict.get default
- dict.get(key, default) returns the value if the key exists and the default otherwise, avoiding a KeyError. dict[key] raises KeyError when the key is absent.
- try else finally
- The else block runs only when the try block raised no exception. The finally block always runs, even after a return, making it suitable for cleanup such as closing files.
- with open file mode
- open(path, mode, encoding) with a with statement closes the file automatically. Mode r reads, w truncates and writes, a appends, x creates exclusively, and b selects binary mode.
- argparse required option
- argparse.ArgumentParser().add_argument("--port", type=int, required=True) declares a mandatory integer option. parse_args() returns a namespace whose port attribute is already converted to int.
- __main__ guard
- Code inside if __name__ == "__main__": executes only when the file is run directly. When the file is imported, __name__ equals the module name and the block is skipped.
- Generator expression memory
- A generator expression such as (x*x for x in data) yields items lazily and holds one item at a time, while a list comprehension builds the entire list in memory at once.
- os.walk tuple output
- os.walk(top) yields a tuple (dirpath, dirnames, filenames) for each directory under top. Editing dirnames in place prunes which subdirectories are visited next.
- subprocess.run check
- subprocess.run(cmd, capture_output=True, text=True, check=True) returns a CompletedProcess with stdout, stderr, and returncode. check=True raises CalledProcessError when the exit code is non-zero.
- shutil.copy2 versus move
- shutil.copy2 copies a file and preserves metadata such as timestamps. shutil.move relocates or renames a file or directory, removing the source after a successful transfer.
- shutil.disk_usage return
- shutil.disk_usage(path) returns a named tuple with total, used, and free bytes for the filesystem containing that path. Divide by 1024**3 to express values in gigabytes.
- os.scandir DirEntry
- os.scandir(path) yields DirEntry objects exposing name, path, is_file(), is_dir(), and stat(). Cached type information avoids a separate system call per directory entry.
- os.getpid and getppid
- os.getpid() returns the process ID of the running Python process, and os.getppid() returns the ID of its parent. subprocess.Popen exposes the child's PID as the pid attribute.
- pathlib glob pattern
- pathlib.Path(directory).glob("*.log") yields Path objects matching the pattern in that directory. The rglob method searches recursively through all subdirectories.
- os.chmod mode bits
- os.chmod(path, 0o755) sets permission bits, where 0o755 grants owner read-write-execute and group and others read-execute. os.stat(path).st_mode reads the current mode.
- Git staging area
- The staging area, or index, holds changes selected with git add that will enter the next commit. git diff shows unstaged changes; git diff --staged shows staged changes.
- Merge versus rebase
- git merge joins two histories with a merge commit and preserves both parent lines. git rebase replays commits onto a new base, creating linear history but new commit hashes.
- git fetch versus pull
- git fetch downloads remote objects and updates remote-tracking branches without touching the working tree. git pull performs a fetch followed by a merge or rebase of the current branch.
- git reset hard soft
- git reset --soft moves HEAD but keeps changes staged. --mixed also unstages them. --hard additionally discards working-tree changes and is destructive to uncommitted work.
- git revert safe undo
- git revert creates a new commit that inverts the changes of an earlier commit. It is safe on shared branches because it does not rewrite existing history, unlike git reset.
- Detached HEAD state
- A detached HEAD occurs when HEAD points directly to a commit instead of a branch, for example after git checkout of a hash. New commits are unreferenced unless a branch is created.
- Merge conflict markers
- Conflicts insert <<<<<<<, =======, and >>>>>>> markers around competing versions. Edit the file to the intended result, remove markers, run git add, then commit the resolution.
- Pull request status checks
- GitHub pull requests can require status checks and approving reviews before merging. Protected branches enforce these rules, blocking direct pushes and merges that fail required checks.
- git bisect bug search
- git bisect performs a binary search over commits between a known good and a known bad revision, marking each tested commit good or bad until the first bad commit is identified.
- CSV DictReader usage
- csv.DictReader(file) yields one dict per row keyed by the header row, so fields are accessed by name. Open the file with newline="" to avoid blank lines on some platforms.
- requests raise_for_status
- Response.raise_for_status() raises requests.HTTPError when the status code is 4xx or 5xx. Always pass a timeout argument so a stalled server cannot block the script forever.
- unittest setUp tearDown
- In unittest.TestCase, setUp runs before each test method and tearDown after it, providing fresh fixtures per test. Class-level variants setUpClass and tearDownClass run once.
- pytest fixture decorator
- The @pytest.fixture decorator marks a function whose return value is injected into test functions that name it as a parameter. Fixtures handle setup and teardown via yield.
- smtplib send_message
- smtplib.SMTP(host, port) connects to a mail server; starttls() upgrades to TLS, login() authenticates, and send_message(EmailMessage) sends a message with headers and body.
- re.search versus match
- re.search scans the whole string for the first match, while re.match only checks at the start. re.findall returns all non-overlapping matches as a list of strings or tuples.
- logging.exception in except
- Calling logging.exception(message) inside an except block logs the message at ERROR level together with the full traceback, which aids troubleshooting automated scripts that run unattended.