userprovided

"Never trust user input!" is also true outside the security context: You cannot be sure users always provide you with valid and well-formatted data.
For a wide range of data, the Python package userprovided:
- checks for validity and plausibility
- normalizes input
- converts into standardized formats
- performs basic security checks
The code has type hints (PEP 484, using modern PEP 604 X | Y syntax) and provides useful log and error messages.
Userprovided has functionality for the following inputs:
- parameters:
- Tolerant vs. strict validators: fall back to a default, or stop the program.
- Check a dictionary for valid, needed, and unknown keys.
- Avoid keys without value in a dictionary to ensure all values are present.
- Convert into a set from lists, strings and tuples.
- Parse separated strings into a set with support for quotes and escaping.
- Check range of numbers and strings to validate if values are in a specific range.
- Check integer range with strict integer type enforcement.
- Clean and trim strings by stripping whitespace and converting empty input to None or a custom value.
- Enforce boolean type to reject truthy/falsy values.
- Parse a boolean from config/env/form spellings (yes/no/on/off/1/0) into a real
bool.
- Check a string against allowed options and return the canonical spelling.
- Convert to an integer or fail instead of silently using a default.
- Convert to a number or fail for values that may have decimals.
- Validate AWS S3 bucket names against AWS naming rules.
- url:
- Normalize a URL and drop specific keys from the query part of it.
- Normalize a hostname to one canonical form (trailing dots, punycode, IPv6 spellings).
- Check if a string is a URL.
- Check for shortened URLs from known URL shortening services.
- Determine a file extension from a URL and the MIME-type sent by the server.
- Extract domain from URL with optional subdomain removal, supporting 2-part TLDs.
- Extract domain from a hostname for callers that already hold a bare hostname instead of a URL.
- Extract the host of a URL in canonical form, optionally with its port, as an identity key.
- Extract TLD from URL correctly identifying both standard and 2-part TLDs.
- Check if a URL belongs to a domain with subdomain matching.
- Limits of the two-part TLD list and when to reach for a dedicated package.
- ip:
- Check for loopback addresses (127.0.0.0/8, ::1, localhost).
- Check for private addresses (RFC 1918, IPv6 unique-local).
- Check for link-local addresses (169.254.0.0/16 incl. cloud metadata, fe80::/10, .local).
- Check for potential SSRF targets combining all three checks.
- hash:
- Is the hash method available?
- Calculate a file hash and (optionally) compare it to an expected value.
- Calculate a string hash for non-security use cases like cache keys.
- date:
- Does a given date exist?
- Convert English and German long format dates to ISO strings.
- mail:
- Check if a string is a valid email address.
- finance:
- Validate ISIN (International Securities Identification Number).
- Validate IBAN (International Bank Account Number).
- geo:
- Validate coordinates to check if latitude and longitude are within valid Earth ranges.
- err:
- The exceptions this package raises and how to catch them.
Installation
The recommended way is to install userprovided into a virtual environment. This keeps it isolated from your system Python and avoids permission problems. (Do not use sudo pip: installing into the system Python as root can break packages managed by your operating system, and recent Linux distributions block it by default.)
On Linux / macOS:
python3 -m venv .venv
source .venv/bin/activate
pip install userprovided
On Windows (py is the Python launcher that ships with the official Python installer):
py -m venv .venv
.venv\Scripts\activate
pip install userprovided
To upgrade to the latest version (with the virtual environment activated):
pip install userprovided --upgrade
Tested and Used in Production
userprovided has 100% test coverage, no external dependencies, and is used in production by projects such as:
Handle Parameters
Tolerant vs. Strict Validators
This module offers two families of validators. Picking the wrong one is the
difference between a program that keeps running with a silently substituted
value and one that stops with an actionable message.
|
Tolerant |
Strict |
| Functions |
numeric_in_range, int_in_range, string_in_range |
strict_int, strict_numeric, parse_boolean, one_of |
| Invalid value |
logs at debug level, returns your fallback |
raises ValidationError |
| Converts strings? |
no, the value must already have the right type |
yes — '8' becomes 8 |
| Error message |
none, the caller never learns |
names the value, the parameter and its origin |
| Use for |
a pipeline that must not stop for one bad record |
config files, environment variables, command line arguments |
Use the tolerant family when processing continues regardless: one
implausible value among thousands should not abort a scraping run.
Use the strict family at an application's input boundary. A mistyped
setting in a config file should stop the program at startup and say what to
fix — not silently run with a default the user did not choose.
# Tolerant: out of range, so the fallback is returned and logged at debug.
userprovided.parameters.int_in_range('workers', 500, 1, 32, 4)
# => 4
# Strict: out of range, so it raises.
userprovided.parameters.strict_int('500', name='workers', minimum=1, maximum=32)
# => ValidationError: Invalid value '500' for workers - must be 32 or smaller.
Both families distinguish a bad value from a wrong type. A value a user
could plausibly have typed is a value problem: the strict validators raise
ValidationError (a subclass of ValueError), the tolerant ones fall back.
A wrong type — None, a list, a bool — always raises TypeError, in both
families, because that is a bug in the calling code rather than something an
end user can fix. The single exception is enforce_boolean,
which has raised ValueError for a non-bool since 1.0 and keeps doing so.
Check a Parameter Dictionary
If your application accepts parameters in the form of a dictionary, you have to test if all needed parameters are provided and if there are any unknown keys (maybe due to typos). There is a method for that:
userprovided.parameters.validate_dict_keys(
dict_to_check = {'a': 1, 'b': 2, 'c': 3},
allowed_keys = {'a', 'b', 'c', 'd'},
necessary_keys = {'b', 'c'})
Returns True if the dictionary dict_to_check contains only allowed keys and all necessary keys are present.
Avoid Keys without Value in a Dictionary
Check if all keys in a dictionary have a value. Return False if the value for any key is empty. Works for strings (including whitespace only), dictionaries, lists, tuples, and sets.
# returns True:
userprovided.parameters.keys_neither_none_nor_empty({'a': 123, 'b': 'example'})
# returns False:
userprovided.parameters.keys_neither_none_nor_empty({'a': ' ', 'b': 'example'})
userprovided.parameters.keys_neither_none_nor_empty({'a': None, 'b': 'example'})
userprovided.parameters.keys_neither_none_nor_empty({'a': list(), 'b': 'example'})
Convert into a set
Convert a string, a tuple, or a list into a set (i.e. no duplicates, unordered):
userprovided.parameters.convert_to_set(list)
Parse Separated Strings into a Set
Parse comma-separated (or custom separator) strings into a set of trimmed, non-empty values. This function supports:
- Custom separators (default: comma)
- Quoted fields to include the separator character within values
- Backslash escaping for special characters
- Automatic trimming and deduplication
# Basic comma-separated values
userprovided.parameters.separated_string_to_set('a, b, c')
# => {'a', 'b', 'c'}
# Quoted fields with separator inside
userprovided.parameters.separated_string_to_set('"hello, world", foo, bar')
# => {'hello, world', 'foo', 'bar'}
# Escaped separator
userprovided.parameters.separated_string_to_set('a\\,b, c')
# => {'a,b', 'c'}
# Custom separator
userprovided.parameters.separated_string_to_set('a|b|c', sep='|')
# => {'a', 'b', 'c'}
# Empty fields and whitespace are handled
userprovided.parameters.separated_string_to_set('a, , b, ,c')
# => {'a', 'b', 'c'}
# Disable quote parsing if needed
userprovided.parameters.separated_string_to_set('"a,b",c', allow_quotes=False)
# => {'"a', 'b"', 'c'}
# Returns None for None input
userprovided.parameters.separated_string_to_set(None)
# => None
Parameters:
raw_string: The string to parse (or None)
sep: Separator character (default: ',')
allow_quotes: Enable quote parsing (default: True)
quote_char: Quote character (default: '"')
Raises:
TypeError: If separator/quote_char is not a string
ValueError: If separator/quote_char is not a single character, if quote_char equals separator, or if quotes are unclosed
Check Range of Numbers and Strings
def numeric_in_range(parameter_name,
given_value,
minimum_value,
maximum_value,
fallback_value) -> int | float
def string_in_range(string_to_check,
minimum_length,
maximum_length,
strip_string: bool = True) -> bool
userprovided.parameters.is_port(int)
# Checks if the port is integer and within the
# valid range from 0 to 65535. A non-integer — including a
# bool, which is a subclass of int — raises TypeError.
Check Integer Range
Similar to numeric_in_range, but with strict type checking to ensure all values are exactly integers (not floats). This is useful when you need to guarantee integer types, for example when working with array indices, counts, or IDs.
# Returns the value if within range
userprovided.parameters.int_in_range(
parameter_name='user_age',
given_value=25,
minimum_value=0,
maximum_value=120,
fallback_value=18
)
# => 25
# Returns fallback if out of range
userprovided.parameters.int_in_range(
parameter_name='page_number',
given_value=500,
minimum_value=1,
maximum_value=100,
fallback_value=1
)
# => 1 (fallback value, logs at debug level)
# Rejects floats even if they represent whole numbers
userprovided.parameters.int_in_range(
parameter_name='count',
given_value=5.0, # This is a float, not an int
minimum_value=1,
maximum_value=10,
fallback_value=5
)
# => TypeError: Value must be an integer.
The function validates that minimum ≤ maximum and that the fallback value is within the allowed range.
Clean and Trim Strings
Strip leading and trailing whitespace from strings. Empty or whitespace-only strings are converted to None by default, or to a custom value via the empty_as parameter. This is a trivial operation, but it is a repeating input normalization pattern in web applications: HTML forms submit empty fields as '' rather than omitting them. Before storing form data in a database, empty strings should be converted to None so that the column is NULL instead of an empty string.
userprovided.parameters.clean_trim('')
# => None
userprovided.parameters.clean_trim(' ')
# => None
userprovided.parameters.clean_trim(' hello ')
# => 'hello'
userprovided.parameters.clean_trim(None)
# => None
Parameters:
value: The input string or None.
empty_as: The value to return when input is None, empty, or whitespace-only. Defaults to None. Set to '' to keep empty strings, or use a custom placeholder.
userprovided.parameters.clean_trim('', empty_as='N/A')
# => 'N/A'
userprovided.parameters.clean_trim(' ', empty_as='')
# => ''
Raises:
TypeError: If value is not a string or None.
Enforce Boolean Type
Validates that a parameter is exactly of type bool (True or False), not just a truthy or falsy value. Use this when you need to ensure strict boolean parameters and avoid subtle bugs from implicit type conversions.
# Valid boolean values pass
userprovided.parameters.enforce_boolean(True)
# => No error
userprovided.parameters.enforce_boolean(False, parameter_name='debug_mode')
# => No error
# Truthy/falsy values are rejected
userprovided.parameters.enforce_boolean(1)
# => ValueError: Value of parameter must be boolean, i.e True / False
userprovided.parameters.enforce_boolean('true')
# => ValueError: Value of parameter must be boolean, i.e True / False
Parse a Boolean
Where enforce_boolean rejects anything that is not already a bool, parse_boolean converts the boolean spellings delivered by config files, environment variables, and HTML forms into a real bool. It accepts 1 / yes / true / on (→ True) and 0 / no / false / off (→ False), case-insensitively and after trimming whitespace (mirroring configparser.BOOLEAN_STATES). Real booleans pass through unchanged. Unlike the tolerant helpers, it never falls back to a default — an unrecognized value raises userprovided.err.ValidationError (a subclass of ValueError).
userprovided.parameters.parse_boolean('yes') # => True
userprovided.parameters.parse_boolean(' Off ') # => False
userprovided.parameters.parse_boolean(True) # => True
# Unrecognized values raise, with an actionable, source-aware message:
userprovided.parameters.parse_boolean(
'nope', name='verbose', source='in config.ini')
# => ValidationError: Invalid value 'nope' for verbose in config.ini -
# must be a boolean (true/false, yes/no, on/off, 1/0).
The optional name and source keywords are used only to build the error message, so a user learns which value to fix and where. A non-string, non-bool argument (e.g. None) raises TypeError.
Check a String against Allowed Options
one_of checks that a string is one of a set of allowed options and returns the member from the allowed collection — so it validates and normalizes in one call: the caller gets the registered spelling, no matter how the user cased or padded the input. Matching is case-insensitive by default (set case_sensitive=True for exact matching); surrounding whitespace is always stripped. Like parse_boolean, it never falls back to a default — an unknown option raises userprovided.err.ValidationError (a subclass of ValueError) listing the allowed options in sorted order.