.. vim: set fileencoding=utf-8: .. -*- coding: utf-8 -*- .. +--------------------------------------------------------------------------+ | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | | | +--------------------------------------------------------------------------+ ******************************************************************************* Nomenclature ******************************************************************************* This guide presents naming conventions and patterns for Python and Rust projects. The lists are not exhaustive, and new patterns may emerge for specific domains or requirements. When working with third-party APIs or established codebases, it may be appropriate to follow their existing naming conventions rather than those presented here. The goal is consistency within a given context rather than rigid adherence to these patterns. Modules, Packages, and Crates =============================================================================== - Prefer single-word names: ``users``, ``authentication``, ``storage``. - Use plurals for collections of related modules or classes: ``parsers``, ``validators``. - Use ``-ation`` suffixes for functionality areas: ``authentication``, ``configuration``. - Avoid underscores by making portmanteau words: ``datastore`` not ``data_store``, ``userauth`` not ``user_auth``. **Python distribution packages and Rust crates:** Prefer single words; use ``kebab-case`` if compound names are required: frigid emcd-projects **Python and Rust modules:** Prefer single words; use ``snake_case`` if compound names are required: processors # plural for collection userauth # portmanteau for "user authentication" configuration # -ation for functionality area Classes =============================================================================== General Guidance ------------------------------------------------------------------------------- - Use ``Async`` suffix for asynchronous interfaces, if you need to distinguish between asynchronous and synchronous varieties with the same module or package. - Avoid ``Type`` suffix except when fitting to existing framework. I.e., do **not** follow the pattern in Python's ``types`` module (``NoneType``, etc...) unless there is good reason to do so. Abstract Classes ------------------------------------------------------------------------------- - Suffix with ``Abstract`` for abstract base classes if you need to distinguish between concrete and abstract classes within the same module or package. However, prefer to name concrete classes with additional detail so that such distinction is not necessary. - Use adjective names for interface-like classes when they describe capabilities. .. code-block:: python class DictionaryAbstract: ''' Abstract base for dictionary types. ''' class Dictionary( DictionaryAbstract ): ''' Concrete class derived from abstract one. ''' class Comparable: ''' Interface for objects supporting comparison. ''' class Immutable: ''' Interface for objects preventing modification. ''' **Rust traits** follow similar patterns: - **Capability adjectives:** ``Sized``, ``Clone``, ``Send``, ``Sync`` - **Ability suffixes:** ``Readable``, ``Writable``, ``Comparable`` - **Action agents:** ``Iterator``, ``Parser``, ``Builder``, ``Formatter`` - **Behavior descriptions:** ``Default``, ``Debug``, ``Display`` .. code-block:: rust trait Comparable { fn compare( &self, other: &Self ) -> Ordering; } trait ConfigurationBuilder { fn build( self ) -> Configuration; } Base Classes ------------------------------------------------------------------------------- - Use ``Base`` or ``Common`` suffix for base classes. - Use ``Extension``/``Supplement`` (Latin-derived) or ``Mixin`` (Germanic-like) suffix for mix-in classes. Choose the suffix which matches the rest of the name. .. code-block:: python class DictionaryBase: ''' Base class for dictionary implementations. ''' class LoggingMixin: ''' Adds logging capabilities to classes. ''' Container Classes ------------------------------------------------------------------------------- Name based on behavior rather than implementation. I.e., talk about **what** instances of a class do and not **how** they do it. .. code-block:: python class ProducerDictionary: ''' Dictionary producing values on demand. ''' class QueueAsync: ''' Queue with asynchronous interface. ''' Enum Classes ------------------------------------------------------------------------------- - Use plural nouns for enum class names. - Use PascalCase for enum members to reflect singleton semantics. .. code-block:: python class States: Initial = auto( ) Execution = auto( ) Complete = auto( ) Exception Classes ------------------------------------------------------------------------------- - Follow standard hierarchy: ``Omniexception`` -> ``Omnierror`` -> specific exceptions. - Use present tense verbs with these patterns: - ``[]Failure`` for operation failures - ``[]Interruption`` for interrupted operations - ``[]Invalidity`` for invalid states/data - Use ``[]Error`` for other error cases. .. code-block:: python class ConfigureFailure( Omnierror ): ''' Raised when configuration fails. ''' class AttributeInvalidity( Omnierror ): ''' Raised when attribute value is invalid. ''' class ProcessInterruption( Omniexception ): ''' Raised when process is interrupted. ''' Metaclasses ------------------------------------------------------------------------------- - Use ``Class``/``Factory`` (Latin-derived) or ``Builder``/``Maker`` (Germanic-derived) suffix. .. code-block:: python class ValidatorClass( type ): ''' Metaclass for creating validator classes. ''' class SetBuilder( type ): ''' Metaclass for building set classes. ''' Special Purpose Classes ------------------------------------------------------------------------------- Use appropriate suffix pairs based on purpose: - ``Proxy`` (Latin-derived) or ``Wrapper`` (Germanic-derived) for delegation patterns - ``Coordinator``/``Manager``/``Supervisor`` (Latin-derived) or ``Overseer`` (Germanic-derived) for resource management - ``Spectator``/``View`` for limited access patterns .. code-block:: python class WeakrefWrapper: ''' Wraps object with weak reference semantics. ''' class ConnectionManager: ''' Manages database connections. ''' class DictionaryView: ''' Provides read-only view of dictionary. ''' Variables and Attributes =============================================================================== - Prefer single-word names: ``name``, ``count``, ``timeout``, ``callback``. - Avoid repeating the class or function name in variable names: - ``User.name`` not ``User.user_name`` - ``validate_email( address )`` not ``validate_email( email_address )`` - ``parse_json( content )`` not ``parse_json( json_content )`` - Avoid truncations: prefer ``configuration`` over ``config``, ``options`` over ``opts``, ``arguments`` over ``args``. - Portmanteau words are acceptable: ``configfile`` instead of ``configuration_file``, ``envvar`` instead of ``environment_variable``. - Use context-appropriate specificity: ``start_time`` when multiple time values exist, ``time`` when unambiguous. .. code-block:: python class DatabaseConnection: timeout: float # Not connection_timeout host: str # Not database_host def validate_email( address: str ) -> bool: # Not email_address ''' Validates email address format. ''' def parse_configuration( filename: str ) -> dict[ str, __.typx.Any ]: # Not config_file ''' Parses configuration from file. ''' Constants and Module-Level Variables =============================================================================== **True constants** (immutable values): - Use ``ALL_CAPS`` with underscores separating words. - Use suffixes for semantic grouping: ``TIMEOUT_DEFAULT``, ``TIMEOUT_MAXIMUM``, ``RETRIES_MAXIMUM`` not ``DEFAULT_TIMEOUT``, ``MAX_TIMEOUT``, ``MAX_RETRIES``. - Group related constants with common prefixes: ``HTTP_OK``, ``HTTP_NOT_FOUND``, ``HTTP_SERVER_ERROR``. **Module-level caches** (internal mutability): - Use leading underscore: ``_connection_pool``, ``_configuration_cache``. - These have internal mutability even though they cannot be reassigned as module attributes. .. code-block:: python # True constants API_VERSION = '2.1.0' TIMEOUT_DEFAULT = 30.0 TIMEOUT_MAXIMUM = 300.0 RETRIES_MAXIMUM = 3 HTTP_OK = 200 HTTP_NOT_FOUND = 404 HTTP_SERVER_ERROR = 500 # Module-level caches (internal mutability) _connection_pool = ConnectionPool( ) _cached_settings = { } Functions =============================================================================== General Patterns ------------------------------------------------------------------------------- ``_``: Where verb describes the action and noun describes the target. ``_``: For methods only. Chainable operations typically returning modified copies. Noun Placeholders ------------------------------------------------------------------------------- - ````: Named property or field of an object - ````: Distinct part of a larger system or application - ````: Boolean predicate or state - ````: Raw or structured information, regardless of location - ````: Execution context (process, thread, task) managed by current process - ````: Optional functionality that can be enabled/disabled - ````: Data serialization format (JSON, XML, etc.) - ````: Planned future execution - ````: In-process entity (instance of a Python class) - ````: Callback or event handler - ````: Claim on future resource usage - ````: Entity external to the current process (file, network service, etc.) - ````: Long-running process or daemon external to current process - ````: Memory or storage allocation - ````: Python type or class Preposition Prefixes ------------------------------------------------------------------------------- - ``as_``: Returns copy of object in different format or type. Chainable with other methods. - ``from_``: Class method that constructs object from specific format or type. - ``with_``: Returns copy of object with modified attributes. Chainable with other methods. Verb Prefixes by Semantic Cluster ------------------------------------------------------------------------------- **Analysis and Discovery:** - ``assess_``: Examines data to derive insights or patterns. - ``discover_``: Detects or determines value from environment or context. - ``examine_``: Retrieves metadata about resource without accessing full content (file stats, HTTP HEAD). - ``survey_``: Lists or enumerates members of external resource collection. **Component Initialization:** - ``configure_``: Applies settings or parameters to component, preparing it for operation. - ``prepare_``: Fully initializes component, including registration of handlers/extensions. **Computation:** - ``calculate_``: Computes value from one or more inputs using defined algorithm. **Data Operations:** - ``access_``: Returns value via computed or indirect access (property getter, descriptor protocol). For in-process objects only. - ``filter_``: Returns subset of objects matching specified criteria. - ``modify_``: Updates in-process object state. Alternative to ``update_`` for disambiguation. - ``parse_``: Extracts structured data from formatted input (JSON, XML). - ``query_``: Performs structured data retrieval with parameters or filters. - ``retrieve_``: Obtains copy of data from external resource. No release required. - ``transform_``: Changes data structure or format. Synonym: ``convert_``. - ``update_``: Modifies state of external resource. **Exception Handling (Python-specific):** - ``intercept_``: Invokes functions while capturing their exceptions for later handling. Used primarily in concurrent execution contexts where multiple exceptions need collection. **Persistence and Serialization:** - ``restore_``: Deserializes object from persistent storage. - ``save_``: Serializes object to persistent storage. **Presentation and Output:** - ``display_``: Presents data in user-facing format. Synonym: ``present_``. - ``render_