Pages

Wednesday, December 2, 2026

Python pathlib.Path vs os.path: Writing Clean, Portable File Pipelines

If you have ever maintained a Python script that builds file paths with os.path.join(), splits extensions with os.path.splitext(), and checks file existence with os.path.exists(), you already know how noisy string-based path handling becomes. Every operation bounces between functions in os, os.path, and glob while treating paths as fragile plain strings.

Since Python 3.4, the built-in pathlib module offers an object-oriented alternative—Path—that makes file pipelines shorter, self-documenting, and portable across Windows, macOS, and Linux.

1. Joining Paths Without String Concatenation Bugs

With os.path, nested directories require nested function calls. With pathlib.Path, the / operator joins path segments cleanly regardless of operating system:

from pathlib import Path

root = Path("/tmp/howcodex-demo")
sub = root / "tutorials" / "python"

print("POSIX:", sub.as_posix())
print("Name:", sub.name, "Stem:", sub.stem)
print("Parents:", [p.name for p in sub.parents if p.name])
assert sub.as_posix().endswith("/tutorials/python")
assert (root / "index.html").suffix == ".html"
print("pathlib assertions passed!")

Because sub is a Path object rather than a raw string, common properties like .name (final component), .stem (filename without extension), .suffix (file extension), and .parent are immediately available without slicing strings.

2. Reading, Writing, and Creating Directories in One Line

For small configuration files, logs, or generated HTML snippets, Path eliminates manual open() boilerplate when you simply want to read or write text safely:

from pathlib import Path

out_dir = Path("build/reports")
out_dir.mkdir(parents=True, exist_ok=True)

report_file = out_dir / "summary.txt"
report_file.write_text("Build succeeded\n", encoding="utf-8")
content = report_file.read_text(encoding="utf-8")
print(content.strip())

Calling mkdir(parents=True, exist_ok=True) replaces the old os.makedirs(..., exist_ok=True) call, and explicitly passing encoding="utf-8" avoids Windows default code-page mismatches.

3. Scanning Files with .glob() and .rglob()

Instead of combining os.walk() with manual endswith() filters, Path.rglob() recursively matches patterns in a single readable expression:

from pathlib import Path

for md_file in sorted(Path("docs").rglob("*.md")):
    print(md_file.relative_to("docs"), md_file.stat().st_size)

4. Practical Rules When Mixing Path and Legacy APIs

  • Always use Path internally across your Python modules and helper functions.
  • If a third-party library expects a string (rare in modern Python since PEP 519), convert at the boundary with str(path) or os.fspath(path).
  • Use .resolve() when comparing paths or validating that user-supplied relative paths stay inside an allowed root directory.

If you are learning Python, Data Structures, SQL, or Web Development and want structured, zero-paywall walkthroughs, explore the free tutorial library at HowCodex (https://www.howcodex.com/).

Tuesday, December 1, 2026

Python SQLite Foreign Keys and CHECK Constraints: Catch Bad Data Before It Lands

SQLite is bundled with Python's standard library, making it ideal for local tools, prototypes, and background workers. However, two common surprises trip up beginners:

1. Foreign key constraints are disabled by default on every new SQLite connection.
2. Loose column types let invalid numbers (like negative order amounts) slip in unless you enforce CHECK rules.

Here is a self-contained pattern using Python's built-in sqlite3 module to enforce data integrity at the database layer.

1. Enable Foreign Keys and Define Constraints

Always execute PRAGMA foreign_keys = ON; right after opening a connection. Combine REFERENCES with CHECK constraints so the database rejects bad rows before they corrupt downstream queries:

import sqlite3
from datetime import datetime, timezone


def init_schema(conn: sqlite3.Connection) -> None:
conn.execute("PRAGMA foreign_keys = ON;")
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE
);

CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_id INTEGER NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
amount_cents INTEGER NOT NULL CHECK (amount_cents > 0),
created_utc TEXT NOT NULL
);
"""
)

2. Verify Constraints With Runnable Assertions

Instead of assuming constraints work, verify both valid writes and expected sqlite3.IntegrityError rejections in an in-memory database:

def run_checks() -> None:
conn = sqlite3.connect(":memory:")
init_schema(conn)
now_iso = datetime(2026, 12, 2, 2, 16, tzinfo=timezone.utc).isoformat()

# 1. Insert a valid customer and order using parameterized placeholders (?)
with conn:
cur = conn.execute(
"INSERT INTO customers (email) VALUES (?)",
("dev@example.com",),
)
customer_id = cur.lastrowid
conn.execute(
"INSERT INTO orders (customer_id, amount_cents, created_utc) VALUES (?, ?, ?)",
(customer_id, 4900, now_iso),
)

# 2. Orphaned customer_id must fail
fk_rejected = False
try:
with conn:
conn.execute(
"INSERT INTO orders (customer_id, amount_cents, created_utc) VALUES (?, ?, ?)",
(9999, 1500, now_iso),
)
except sqlite3.IntegrityError:
fk_rejected = True
assert fk_rejected, "Foreign key constraint did not trigger"

# 3. Non-positive amount_cents must fail
check_rejected = False
try:
with conn:
conn.execute(
"INSERT INTO orders (customer_id, amount_cents, created_utc) VALUES (?, ?, ?)",
(customer_id, -100, now_iso),
)
except sqlite3.IntegrityError:
check_rejected = True
assert check_rejected, "CHECK constraint did not trigger"

# 4. Confirm clean join output
row = conn.execute(
"""
SELECT c.email, o.amount_cents
FROM orders o
JOIN customers c ON https://www.google.com/url?q=http://c.id&source=gmail&ust=1796264203377000&sa=E = o.customer_id
"""
).fetchone()
assert row == ("dev@example.com", 4900)
print("All SQLite integrity checks passed.")


if __name__ == "__main__":
run_checks()

Key Takeaways

- Set PRAGMA foreign_keys = ON; per connection: SQLite resets this flag on every new session.
- Store money as integer cents (amount_cents): Avoids floating-point rounding bugs.
- Use parameterized ? queries: Prevents SQL injection and handles escaping cleanly.

---

Disclosure: I maintain HowCodex (https://www.google.com/url?q=https://www.howcodex.com/&source=gmail&ust=1796264203377000&sa=E), a free, no-paywall programming and computer science tutorial library covering Python, SQL/DBMS, Web Development, and Data Structures. If you are looking for structured beginner-to-intermediate walkthroughs on relational databases and Python, feel free to explore the guides there.

Sunday, November 22, 2026

Parsing UK order dates in Python without swapping day and month

Two order exports can contain the same value, 03/04/2026, and mean different things. A day-first export means 3 April. A month-first export means 4 March. Both are valid calendar dates, so trying one parser and falling back to the other only works when the first parser fails. It cannot resolve this case.

Choose the format from the source

Get the date format from the supplier's export specification or your own import configuration. The example below assumes one known exporter consistently uses DD/MM/YYYY and another uses MM/DD/YYYY. An export's country label by itself is not a format guarantee.

import re
from datetime import datetime

DATE_FORMATS = {"uk_export": "%d/%m/%Y", "us_export": "%m/%d/%Y"}
DATE_SHAPE = re.compile(r"[0-9]{2}/[0-9]{2}/[0-9]{4}")


def order_date(raw, source):
    if source not in DATE_FORMATS:
        raise ValueError("unknown source date format")
    if not DATE_SHAPE.fullmatch(raw):
        raise ValueError("expected two digits, slash, two digits, slash, four digits")
    return datetime.strptime(raw, DATE_FORMATS[source]).date().isoformat()


print(order_date("03/04/2026", "uk_export"))
print(order_date("03/04/2026", "us_export"))

Output with Python 3.12:

2026-04-03
2026-03-04

The regular expression enforces the shape promised by these exporters. Python's strptime() checks the calendar date and accepts an optional leading zero for day and month on its own. For this strict contract, 3/4/2026 is rejected by the shape check; 31/04/2026 passes that check but is rejected by the date parser.

Keep rows you cannot interpret out of the report

Record the row identifier, original date and reason in an exception report rather than silently changing formats. Ask the supplier to confirm the format, or request YYYY-MM-DD for future date-only exports. Treat timestamps with times and offsets as a separate input contract.

References: Python format-code documentation. For general background, see Howcodex’s Python 3 date and time guide. This post is shared on behalf of Howcodex.

Saturday, November 21, 2026

Python zip(strict=True) Can Raise After You've Already Written Two Rows

Suppose an export gives you three order IDs and a separate file gives you two amounts in cents. If you pair them with ordinary zip(), Python stops at the shorter input. The third order disappears from the output.

order_ids = ["A-101", "A-102", "A-103"]
amounts = [1299, 2499]

print(list(zip(order_ids, amounts)))
# [('A-101', 1299), ('A-102', 2499)]

Python 3.10 added strict=True to catch this mismatch. The catch is timing: zip() is lazy. It yields the first two pairs before the next iteration raises ValueError.

written = []

try:
    for row in zip(order_ids, amounts, strict=True):
        written.append(row)  # Stand-in for a write.
except ValueError:
    print(written)
    # [('A-101', 1299), ('A-102', 2499)]

Breaking early also skips the check on the unread part of the input. Turning on strict mode doesn't validate the whole batch upfront.

For a small batch, check first and write second

Consume the iterator before calling the writer. If the list construction fails, execution never reaches outbox.extend().

outbox = []

try:
    batch = list(zip(order_ids, amounts, strict=True))
except ValueError:
    assert outbox == []
else:
    outbox.extend(batch)

This protects the writer from an input-length mismatch. It doesn't make the writer itself atomic, and consuming an iterator can still advance or trigger side effects in that iterator.

For a larger import, put SQLite writes in a transaction

In Python 3.12+, sqlite3.connect(..., autocommit=False) lets a connection's with block commit on success or roll back when an exception escapes. Catch the error outside the block. In this example, two inserts are attempted before the length mismatch, but neither row remains.

import sqlite3

con = sqlite3.connect(":memory:", autocommit=False)
try:
    con.execute("CREATE TABLE orders (id TEXT PRIMARY KEY, cents INTEGER)")
    con.commit()

    try:
        with con:
            con.executemany(
                "INSERT INTO orders VALUES (?, ?)",
                zip(order_ids, amounts, strict=True),
            )
    except ValueError:
        assert con.execute("SELECT COUNT(*) FROM orders").fetchone() == (0,)
finally:
    con.close()

That rollback covers writes in this database transaction. It can't undo an email, file write, or API request. If the two exports can arrive in a different order, join them by order ID and check for duplicate and missing IDs. Two columns of the same length can still pair the wrong records.

References: Python zip documentation, PEP 618, and SQLite connection context manager.

Related reading from the site behind this post: Howcodex’s Python SQLite tutorial collection.

Friday, November 20, 2026

Python PATCH updates: Tell a missing nickname from null

A partial profile update has three meanings: an omitted nickname leaves the old one alone, JSON null clears it, and a string replaces it, including an empty string. Plain patch.get("nickname") returns None for the first two cases.

Use a private placeholder as the default and compare it by identity:

import json

MISSING = object()


def apply_nickname_patch(current, body):
    patch = json.loads(body)
    if not isinstance(patch, dict):
        raise ValueError("Expected a JSON object")

    nickname = patch.get("nickname", MISSING)
    if nickname is MISSING:
        return current
    if nickname is None or isinstance(nickname, str):
        return nickname
    raise ValueError("nickname must be a string or null")


assert apply_nickname_patch("Maple", '{}') == "Maple"
assert apply_nickname_patch("Maple", '{"nickname": null}') is None
assert apply_nickname_patch("Maple", '{"nickname": "Fern"}') == "Fern"
assert apply_nickname_patch("Maple", '{"nickname": ""}') == ""

Check is MISSING first. A truthiness check would lump None and "" together. Keep the placeholder inside Python and create it only once.

This is one endpoint's contract, not a complete JSON Merge Patch implementation. In Python 3.15, the built-in sentinel() provides an alternative: MISSING = sentinel("MISSING"). Reuse the same instance. The four assertions above passed with object() on Python 3.12 and 3.13; the newer alternative was checked against the documentation, not executed here.

Shared on behalf of Howcodex.

Thursday, November 19, 2026

In Python, subtract UTC instants to measure elapsed time

A support shift in New York starts at 00:30 and ends at 03:30 on the morning the clocks fall back. The wall clock shows a three-hour difference, but the shift lasts four hours. Subtracting the local Python datetimes directly can quietly give you the wrong duration.

Reproduce the difference

Use Python 3.9 or newer. If your machine lacks an IANA time-zone database, install Python's first-party tzdata package in the project environment.

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

ny = ZoneInfo("America/New_York")
utc = timezone.utc
start = datetime(2025, 11, 2, 0, 30, tzinfo=ny)
end = datetime(2025, 11, 2, 3, 30, tzinfo=ny)

wall_clock = end - start
elapsed = end.astimezone(utc) - start.astimezone(utc)
print(start.isoformat(), "→", end.isoformat())
print("Wall-clock difference:", wall_clock)
print("Elapsed duration:", elapsed)
assert wall_clock == timedelta(hours=3)
assert elapsed == timedelta(hours=4)

The first line shows the offset changing from UTC−04:00 to UTC−05:00. The next two lines report 3:00:00 and 4:00:00, respectively. When two aware datetime values have the same tzinfo object, subtraction ignores that object. Convert the endpoints to UTC before subtracting to measure elapsed time.

Disambiguate the repeated hour

At 01:15 that morning, the local reading occurs twice. Use fold=0 for the first occurrence and fold=1 for the second.

first = datetime(2025, 11, 2, 1, 15, tzinfo=ny, fold=0)
second = first.replace(fold=1)
assert first.utcoffset() == timedelta(hours=-4)
assert second.utcoffset() == timedelta(hours=-5)
assert second.astimezone(utc) - first.astimezone(utc) == timedelta(hours=1)

For completed events, store the UTC instant and convert it for display. For an appointment that follows local time, retain the date, time and zone name. Ask which occurrence the person means if the time is repeated, and separately validate times skipped in spring; attaching ZoneInfo does not perform that validation.

References: Python datetime arithmetic and Python zoneinfo and fold.


Site affiliation: Howcodex is operated by the account sharing this standalone, tested example.

Thursday, July 3, 2014

Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA

Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA


Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA

Posted: 03 Jul 2014 07:00 AM PDT

Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA

Every entrepreneur knows that starting a business is never an easy feat, but starting your business in America is said to be particularly challenging. While there may be challenges to business here in the states, there are plenty of advantages and opportunities, too. While some may find that sourcing your business abroad is the best course of action, there are many entrepreneurs who want to create their products and services at home in their local communities across America.

To help you understand some of the challenges and opportunities of making a business in America, here are three entrepreneurs who are choosing to stay Made in the USA.

Dodocase

DoDo Case, San Francisco, CA

Challenge: American Skilled Labor Costs

Opportunity: Save On Outsourced Manufacturing Costs

DODOcase has combined the craftsmanship of traditional bookbinding with the needs of a modern digital market, to create beautiful, one-of-a-kind iPod and iPad cases. Each DODOcase item is handmade by a local craftsman in their San Fran headquarters. But isn't all that skilled American labor too expensive. Co-founder of DODOcase, Patrick Buckley explained that while the perception often is that the cost of labor it too high, by manufacturing in-house, DODOcase is actually able to tighten up their supply cycle.

Things happen faster because they aren't waiting for outside vendors or overseas manufacturers and they don't have the extra shipping or foreign trade costs. Doing the real cost benefit analysis on domestic labor could end up surprising you. Don't rule skilled American labor out before you do the research.
Printful Logo

Printful, Burbank, CA

Challenge: Starting a US Business as a Foreign-National

Opportunity: Access to Resources and Skilled Labor

Printful offers automatic and on-demand printing fulfillment service that range from posters to greeting cards to mugs -- all designed to help make printing costs transparent and affordable to the small to medium sized online business. Perhaps even more unique than PRINTFUL being based in Burbank, California, is the fact that it has been co-founded in 2013, by Lauris Liberts, a Latvian born entrepreneur, who also co-founder of a Latvian social network Draugiem(.lv).

But isn't starting a business in the US, especially in California expensive? Wouldn't it be cheaper to start the business back in Latvia?

Lauris says that while the cost of doing business might be a bit higher in the US, the opportunities here far outweighed the monetary considerations. He said that while there were certainly challenges getting started, the access to technology, the skilled and educated labor force and the culture of innovation that permeate California made it the perfect culmination of business market factors he was looking for to start PRINTFUL. By providing businesses with options for one-off and on-demand printing with no subscription fees required, the company has really taken off, while helping small online businesses flourish, too.

There's more to starting your business than just costs: consider the market factors and culture your business will need to thrive.

Buck Knives Logo

Buck Knives,

Challenge: Outsourcing Backlash

Opportunity: American Made Builds A Brand

BUCK KNIVES. Founded back in the early part of the century, they made all their knives here in America. However, with the rising cost of domestic skilled labor, they took a gamble and starting outsourcing about 30% of their knife manufacturing to China. With a huge backlash! Customers didn't want Buck Knives made in China. They were willing to pay a higher price to keep that quality MADE IN THE USA. How could your brand be hurt by outsourcing overseas? With a century long history of being Made in the USA, outsourcing their manufacturing to China hurt the Buck brand. So after the stint in offshore manufacturing, Buck Knives returned 100% of their business to being made in Idaho. American labor could be an important part of your brand. Know the costs of outsourced labor before you decide.

The post Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA appeared first on Blogtrepreneur - The Business of Blogging For Busy Entrepreneurs.