Fundamentals 9 min read

Python Tips: String Manipulation, Iterator Slicing, Context Managers, Slots, Resource Limits, and More

This article presents a collection of practical Python techniques—including string cleaning with translation tables, iterator slicing with itertools, skipping file headers, keyword‑only arguments, custom context‑manager objects, memory‑saving __slots__, CPU and memory resource limits, export control via __all__, and simplified total ordering—illustrated with concise code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Tips: String Manipulation, Iterator Slicing, Context Managers, Slots, Resource Limits, and More

The article introduces several useful Python tricks that are not commonly covered in other tutorials.

String Input Cleanup

It shows how to normalize user input by translating characters using a mapping table, replacing whitespace characters and removing unwanted symbols, and mentions extending this approach with the unicodedata module.

<code>user_input = "This  \nstring has  some whitespaces...  \n"
character_map = {
    ord('\n'): ' ',
    ord('\t'): ' ',
    ord('\r'): None,
}
user_input.translate(character_map)  # This string has some whitespaces...</code>

Iterator Slicing (Slice)

Since slicing a generator raises TypeError , the article demonstrates using itertools.islice to obtain a sub‑range of items.

<code>import itertools
s = itertools.islice(range(50), 10, 20)
for val in s:
    ...</code>

Skipping the Beginning of an Iterable

For files that start with comment lines, itertools.dropwhile can discard those lines before processing the actual content.

<code>string_from_file = """// Author: ...\n// License: ...\nActual content..."""
import itertools
for line in itertools.dropwhile(lambda line: line.startswith("//"), string_from_file.split("\n")):
    print(line)
</code>

Keyword‑Only Arguments (kwargs)

Defining a function with a leading * forces callers to use keyword arguments, preventing positional misuse.

<code>def test(*, a, b):
    pass
# test("value for a", "value for b")  # TypeError
test(a="value", b="value 2")  # Works</code>

Creating Objects that Support the with Statement

Two approaches are shown: implementing __enter__ and __exit__ methods in a class, and using contextlib.contextmanager to write a generator‑based context manager.

<code>class Connection:
    def __enter__(self):
        # Initialize connection...
        pass
    def __exit__(self, type, value, traceback):
        # Close connection...
        pass
with Connection() as c:
    ...

from contextlib import contextmanager
@contextmanager
def tag(name):
    print(f"<{name}>")
    yield
    print(f"</{name}>")
with tag("h1"):
    print("This is Title.")
</code>

Saving Memory with __slots__

Defining __slots__ replaces the per‑instance attribute dictionary with a fixed‑size array, reducing memory usage but disallowing dynamic attributes and multiple inheritance.

<code>class Person:
    __slots__ = ["first_name", "last_name", "phone"]
    def __init__(self, first_name, last_name, phone):
        self.first_name = first_name
        self.last_name = last_name
        self.phone = phone
</code>

Limiting CPU and Memory Usage

Using the resource and signal modules, the article shows how to set hard limits on CPU time and memory allocation for a Python process.

<code>import signal, resource, os

def time_exceeded(signo, frame):
    print("CPU exceeded...")
    raise SystemExit(1)

def set_max_runtime(seconds):
    soft, hard = resource.getrlimit(resource.RLIMIT_CPU)
    resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard))
    signal.signal(signal.SIGXCPU, time_exceeded)

def set_max_memory(size):
    soft, hard = resource.getrlimit(resource.RLIMIT_AS)
    resource.setrlimit(resource.RLIMIT_AS, (size, hard))
</code>

Controlling What Gets Exported

By defining __all__ , a module can explicitly list the names that should be exported; leaving it empty prevents any export.

<code>def foo():
    pass
def bar():
    pass
__all__ = ["bar"]
</code>

Simplifying Comparison Operators with functools.total_ordering

The decorator generates the full set of rich comparison methods when only __lt__ and __eq__ are provided.

<code>from functools import total_ordering
@total_ordering
class Number:
    def __init__(self, value):
        self.value = value
    def __lt__(self, other):
        return self.value < other.value
    def __eq__(self, other):
        return self.value == other.value
print(Number(20) > Number(3))
print(Number(1) < Number(5))
print(Number(15) >= Number(15))
print(Number(10) <= Number(2))
</code>

In conclusion, while not every feature described is essential for everyday Python development, each can be handy for simplifying otherwise verbose tasks, and all are part of the Python standard library.

Iteratorstandard-libraryContext Managerfunctoolsstring-manipulationslotsresource limits
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.