liveBook · Manning

Query cleaning

As explained in Practices of the Python Pro

Query cleaning is the transformation of search-query text to remove unwanted spaces and quotes and normalize its casing.

Query cleaning transforms search text by removing unwanted spaces and quotes and normalizing casing. A single cleaning entry point lets callers request cleaned queries without knowing each transformation. section 10.1.3

One request instead of several calls

Instead of calling remove_spaces, remove_quotes, and normalize throughout an application, call clean_query(query). The wrapper preserves separate responsibilities while hiding their sequence from the search procedure. section 10.1.3 section 10.1.2

Listing 10.6. Simplifying a shared interface
import re


def _remove_spaces(query):                             #1
    query = query.strip()
    query = re.sub(r'\s+', ' ', query)
    return query


def _normalize(query):
    query = query.casefold()
    return query


def _remove_quotes(query):
    query = re.sub(r'"', '', query)
    return query


def clean_query(query):                                #2
    query = _remove_spaces(query)
    query = _remove_quotes(query)
    query = _normalize(query)
    return query


if __name__ == '__main__':
    search_query = input('Enter your search query: ')
    search_query = clean_query(search_query)           #3
    print(f'Running a search for "{search_query}"')

Shows the component transformations and the simplified shared interface used to clean a query. section 10.1.3

How Practices of the Python Pro covers it

How deep it goes
Demonstrates the transformations and wrapper design, while deferring fuller class-based encapsulation.
Examples
Shows whitespace removal, quote removal, case normalization, and a search procedure that invokes the cleaning functions.
What you can do after
Apply it via Python functions by composing transformations behind a reusable clean_query interface.
How it connects
Connects query cleaning to loose coupling, separation of concerns, cohesion, and encapsulation.

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.