165 Posts Tagged ‘python’ (Page 5)

(All tags.)


Python type hints: *args and **kwargs

When I started writing type hints, I was a little confused about what to do with Python’s variable argument operators, * and ** (often called *args and **kwargs). Here’s what I figured out.

Read more...

Python type hints: How to Use TypedDict

Take this function:

Read more...

Python type hints: Use object instead of Any

When starting out with Python type hints, it’s common to overuse typing.Any. This is dangerous, since Any entirely disables type checking for a variable, allowing any operation.

Read more...

How to List All Time Zones in Python

Python 3.9 introduced zoneinfo into the standard library. This module reads your operating system’s copy of the tz database. On older versions of Python, you can install the backports.zoneinfo package to use zoneinfo without upgrading.

Read more...

Three uses for functools.partial() in Django

Python’s functools.partial is a great tool that I feel is underused.

Read more...

Disabling FLoC, Google’s new advertising technology

Google has started rolling out FLoC, currently to 0.5% of Chrome users, and some sites are already disabling it. In this post we’ll cover what FLoC is, who’s disabling it, why, and how to do so on a Django site.

Read more...

Introducing the heroicons Python Package

heroicons is a free SVG icon set for your websites, from the creators of tailwindcss. SVG icons are great - they’re small, they sit inline in your HTML, and you can scaled and colour them with plain HTML and CSS. And heroicons is a great icon set - minimal, clear, and consistent.

Read more...

Reindexing all tables after upgrading to PostgreSQL 13

I recently upgraded my client ev.energy to PostgreSQL 13. The first feature listed in this version’s release notes is “Space savings and performance gains from de-duplication of B-tree index entries”. I reindexed all tables after the upgrade to take advantage of this deduplication and saw index storage savings of up to 90%.

Read more...

Django: convert a TestCase from using setUp() to setUpTestData()

Django’s TestCase class provides the setUpTestData() hook for creating your test data. It is faster than using the unittest setUp() hook because it creates the test data only once per test case, rather than per test.

Read more...

time-machine versus freezegun, a benchmark

I wrote my library time-machine last year as a way to speed up tests that need to accurately mock the current time.

Read more...

Cheap Bug Protection With pre-commit’s Regex Hooks

For all my linting needs these days I use the pre-commit framework. It has integrations with every tool I want to use, and uses Git’s hooks to prevent non-passing code from ever being committed.

Read more...

How to Limit Test Time in Django’s Test Framework

I recently optimized a client project’s test suite, and in the process found a test whose runtime had crept up ever since it had been written. The problematic test exercised an import process from a fixed past date until the current day. The test’s runtime therefore grew every day, until it reached over a minute.

Read more...

How to Override the gunicorn Server Header

In all current releases of the popular WSGI server gunicorn, the Server header reports the complete version of gunicorn. I spotted this on my new project DB Buddy. For example, with httpie to check the response headers:

Read more...

Python: mock the current date and time

If you’re testing Python code that relies on the current date or time, you will probably want to mock time to test different scenarios. For example, what happens when you run a certain piece of code on February 29? (A common source of bugs.)

Read more...

Cyber Monday discount for Speed Up Your Django Tests

Earlier this week I tweeted about my two part offer on my book Speed Up Your Django Tests for this year’s Cyber Monday.

Read more...

How to Mock Environment Variables in pytest

Sometimes tests need to change environment variables. This is fairly straightforward in pytest, thanks to os.environ quacking like a dict, and the mock.patch.dict decorator/context manager.

Read more...

Python: mock environment variables with unittest

Sometimes, tests need to change environment variables. This is straightforward in tests using Python’s unittest, thanks to os.environ quacking like a dict, and the mock.patch.dict decorator/context manager.

Read more...

Django: unit test a management command

When we write custom management commands, it’s easy to write integration tests for them with call_command(). This allows us to invoke the management command as it runs under manage.py, and retrieve the return code, standard output, and standard error. It’s great, but has some overhead, making our tests slower than necessary. If we have logic separated out of the command’s handle() method, it improves both readability and testability, as we can unit test it separately.

Read more...

A Guide to Python Lambda Functions

In Python, Lambda functions are rare compared to “normal” functions, and occasionally misunderstood or overused.

Read more...

Better Python Decorators with wrapt

A Python decorator wraps a target function with another wrapper function. This wrapper function can add any behavior you might want. For example, it can track execution times, redefine how the wrapped function runs, or modify return values.

Read more...

Why does Python raise ModuleNotFoundError when modifying Django’s INSTALLED_APPS?

Imagine we are installing the third party package django-cors-headers, which I maintain. Step one in its installation process is to install the package, so we run the command:

Read more...

How to Check if Python’s Output Buffering Is Enabled

By default, Python buffers output to standard output (stdout) and standard error (stderr). This means that output from your code might not show up immediately, making debugging harder.

Read more...

Python: fix SyntaxWarning: list indices must be integers or slices

Take this code, which we want to return a list of two breakfast orders:

Read more...

Python: fix SyntaxWarning: assertion is always true

Take this code:

Read more...

Python: fix SyntaxWarning: '<type>' object is not subscriptable

Take this code:

Read more...