Skip to main content

A collection of small Python utilities for developers.

Project description

nano_dev_utils

A collection of small Python utilities for developers.

Modules

timers.py

This module provides a Timer class for measuring the execution time of code blocks and functions.

Timer Class

  • __init__(self, precision: int = 4, verbose: bool = False): Initializes a Timer instance.

    • precision: The number of decimal places to record and
      display time durations. Defaults to 4.
    • verbose: Optionally displays the function's positional arguments (args) and keyword arguments (kwargs).
      Defaults to False.
  • timeit(self, func: Callable[P, R]) -> Callable[P, R]:
    Decorator that times function execution with automatic unit scaling.

    • When the decorated function is called, this decorator records the start and end times,
      calculates the total execution time, prints the function name and execution
      time (optionally including arguments), and returns the result of the original function.

Example Usage:

import time
from src.nano_dev_utils.timers import Timer

timer = Timer(precision=6, verbose=True)


@timer.timeit
def my_function(a, b=10):
  """A sample function."""
  time.sleep(0.1)
  return a + b


result = my_function(5, b=20)
print(f"Result: {result}")

dynamic_importer.py

This module provides an Importer class for lazy loading and caching module imports.

Importer Class

  • __init__(self): Initializes an Importer instance with an empty dictionary imported_modules to cache imported modules.

  • import_mod_from_lib(self, library: str, module_name: str) -> ModuleType | Any: Lazily imports a module from a specified library and caches it.

    • library (str): The name of the library (e.g., "os", "requests").
    • module_name (str): The name of the module to import within the library (e.g., "path", "get").
    • Returns the imported module. If the module has already been imported, it returns a cached instance.
    • Raises ImportError if the module cannot be found.

Example Usage:

from src.nano_dev_utils.dynamic_importer import Importer

importer = Importer()

os_path = importer.import_mod_from_lib("os", "path")
print(f"Imported os.path: {os_path}")

requests_get = importer.import_mod_from_lib("requests", "get")
print(f"Imported requests.get: {requests_get}")

# Subsequent calls will return the cached module
os_path_again = importer.import_mod_from_lib("os", "path")
print(f"Imported os.path again (cached): {os_path_again}")

release_ports.py

This module provides a PortsRelease class to identify and release processes listening on specified TCP ports.
It supports Windows, Linux, and macOS.

PortsRelease Class

  • __init__(self, default_ports: list[int] | None = None):

  • Initializes a PortsRelease instance.

    • default_ports: A list of default ports to manage. If not provided, it defaults to [6277, 6274].
  • get_pid_by_port(self, port: int) -> int | None: A static method that attempts to find
    a process ID (PID) listening on a given port.

  • It uses platform-specific commands (netstat, ss, lsof).

  • Returns the PID if found, otherwise None.

  • kill_process(self, pid: int) -> bool: A static method that attempts to kill the process with the given pid.

  • It uses platform-specific commands (taskkill, kill -9).

  • Returns True if the process was successfully killed, False otherwise.

  • release_all(self, ports: list[int] | None = None) -> None: Releases all processes listening on the specified ports.

    • ports: A list of ports to release.
    • If None, it uses the default_ports defined during initialization.
    • For each port, it first tries to get the PID and then attempts to kill the process.
    • It logs the actions and any errors encountered. Invalid port numbers in the provided list are skipped.

Example Usage:

import logging
from nano_dev_utils import PortsRelease

# in case you're interested in logging 
logging.basicConfig(filename='port release.log',
                    level=logging.INFO,  # specify here desire level, e.g. DEBUG etc.
                    format='%(asctime)s - %(levelname)s: %(message)s',
                    datefmt='%d-%m-%Y %H:%M:%S')

# Create an instance with default ports
port_releaser = PortsRelease()
port_releaser.release_all()

# Create an instance with custom ports
custom_ports_releaser = PortsRelease(default_ports=[8080, 9000, 6274])
custom_ports_releaser.release_all(ports=[8080, 9000])

# Release only the default ports
port_releaser.release_all()

License

This project is licensed under the MIT License. See LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nano_dev_utils-0.4.1.tar.gz (14.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nano_dev_utils-0.4.1-py3-none-any.whl (7.1 kB view details)

Uploaded Python 3

File details

Details for the file nano_dev_utils-0.4.1.tar.gz.

File metadata

  • Download URL: nano_dev_utils-0.4.1.tar.gz
  • Upload date:
  • Size: 14.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.11

File hashes

Hashes for nano_dev_utils-0.4.1.tar.gz
Algorithm Hash digest
SHA256 2ac374ffe00f33401151c200dd9515bd999d093c0d235943a7cd5c1f44ef9baa
MD5 df6ff3c19f93b2595274eabd074ad89a
BLAKE2b-256 12b72f9682254c2ad93cbb8cffc43ad889eba8fa479a21b6a2e62c519efd3c94

See more details on using hashes here.

File details

Details for the file nano_dev_utils-0.4.1-py3-none-any.whl.

File metadata

  • Download URL: nano_dev_utils-0.4.1-py3-none-any.whl
  • Upload date:
  • Size: 7.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.11

File hashes

Hashes for nano_dev_utils-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2785a450d4d5af75acfe39eecca72e9c3dce3264aa5ed3e6750b2083628dbecb
MD5 8403944891d78d69157d4eeddb9689a6
BLAKE2b-256 7c6829d95e36c1a41f83db557edf2db2675153d4447c3a1926ef1dd973034aa5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page