config module#
pyramids.base.config
#
Configuration utilities for the pyramids package.
This module exposes helpers to: - Configure application logging with colored console output. - Load package configuration from YAML. - Initialize GDAL/OGR (errors routed to Python logging). - Discover and export environment variables (e.g., GDAL_DRIVER_PATH) across platforms.
Logging is opt-in. Importing pyramids runs Config() with no level, which
attaches a logging.NullHandler to the "pyramids" logger and nothing else — the
root logger is never touched, no handler is installed on it, and nothing is printed.
In that state pyramids' records propagate normally, so logging.basicConfig() (or
any other host configuration) picks them up.
Passing an explicit level (Config(level="INFO")) instead hands the namespace to
pyramids: it installs the coloured console handler, the optional file handler, and
sets propagate = False on the "pyramids" logger so records are not also
emitted by the host's root handlers. Choose one or the other — either configure
logging yourself and leave level unset, or let pyramids own its namespace.
Examples: - Set up logging and route GDAL errors into Python logging
```python
>>> from pyramids.base.config import Config
>>> cfg = Config(level="DEBUG") # doctest: +SKIP
>>> # - Creates a colored console handler and optionally a file handler
>>> # - Installs a GDAL error handler that forwards messages to logging
```
-
Load configuration values from the default config.yaml
See Also: - Config: Main entry point to configure logging and GDAL. - LoggerManager: Internal helper that performs logging configuration. - ColorFormatter: Adds ANSI colors to console logs.
PACKAGE_LOGGER_NAME = 'pyramids'
module-attribute
#
Logger namespace pyramids configures. Never the root logger — a library that adds handlers to root hijacks logging for the whole host application.
ColorFormatter
#
Bases: Formatter
Formatter that adds ANSI colors to the log level name for console output.
This formatter wraps the levelname (e.g., INFO, WARNING) with an ANSI color escape sequence appropriate for the record's level. It is intended for console handlers and leaves the message text untouched.
Examples: - Demonstrate how the formatter colors the levelname
```python
>>> import logging
>>> from pyramids.base.config import ColorFormatter # doctest: +SKIP
>>> logger = logging.getLogger("example.color")
>>> handler = logging.StreamHandler()
>>> handler.setFormatter(ColorFormatter("%(levelname)s - %(message)s"))
>>> logger.addHandler(handler)
>>> logger.setLevel(logging.INFO)
>>> logger.info("hello") # doctest: +SKIP
INFO - hello
```
See Also
- Config.setup_logging: Uses this formatter for console logging.
Source code in src/pyramids/base/config.py
format(record)
#
Format a log record by applying a color to its level name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
LogRecord
|
The log record to format. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted message where the levelname is wrapped in an ANSI color escape sequence suitable for consoles. |
Raises:
| Type | Description |
|---|---|
None
|
This method does not raise exceptions on its own. |
Examples: - Use the formatter with a logger to colorize level names
```python
>>> import logging
>>> from pyramids.base.config import ColorFormatter
>>> handler = logging.StreamHandler()
>>> handler.setFormatter(ColorFormatter('%(levelname)s - %(message)s'))
>>> logger = logging.getLogger('example.color.format')
>>> _ = [logger.removeHandler(h) for h in list(logger.handlers)]
>>> logger.addHandler(handler)
>>> logger.setLevel(logging.WARNING)
>>> logger.warning('warn') # doctest: +SKIP
```
Source code in src/pyramids/base/config.py
LoggerManager
#
Encapsulates logging setup and GDAL error handler installation for Pyramids.
This helper centralizes all logging-related concerns so that the public configuration class can remain small. It configures a colored console handler, an optional file handler, and redirects GDAL errors to the logging subsystem.
Everything it configures lives under the :data:PACKAGE_LOGGER_NAME
("pyramids") namespace. The root logger is never modified: a library that
adds a handler to root, or calls root.setLevel(...), silently reconfigures
logging for the entire host application.
Handler installation is opt-in. With level=None (the default, and what
the package import uses) the manager only attaches a logging.NullHandler
and installs the GDAL error bridge; nothing is printed and no level is
changed. Pass an explicit level to get the coloured console handler.
Examples: - Basic usage to configure logging and register the GDAL error handler
```python
>>> from pyramids.base.config import LoggerManager
>>> _ = LoggerManager(level="INFO") # doctest: +SKIP
>>> # - Creates a console handler with colorized levels
>>> # - Optionally creates a file handler when log_file is provided
>>> # - Installs a GDAL error handler that forwards messages to logging
```
See Also
- ColorFormatter: Used by the console handler for colored levels.
- Config.setup_logging: Public API that delegates to this class.
Source code in src/pyramids/base/config.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | |
__init__(level=None, log_file=None, quiet_third_party=False)
#
Create a LoggerManager and configure logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int | str | None
|
Logging level as an int (e.g., logging.INFO)
or as a case-insensitive string ("DEBUG", "INFO", ...). |
None
|
log_file
|
str | Path | None
|
Optional path to a log file to
also write logs to. Ignored when |
None
|
quiet_third_party
|
bool
|
Pin the loggers in
:data: |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an invalid level string is provided (e.g., "VERBOS"). |
Examples: - Configure logging at DEBUG level and write to a file
```python
>>> from pyramids.base.config import LoggerManager
>>> _ = LoggerManager(level="DEBUG", log_file="pyramids.log") # doctest: +SKIP
```
Source code in src/pyramids/base/config.py
EnvironmentVariables
dataclass
#
Utility helpers to inspect and modify PATH-related environment variables.
This small helper provides convenient accessors for the PATH string and its components, as well as a prepend operation; combine with if_exists() to avoid duplicates.
Examples: - Create the helper and inspect PATH entries
```python
>>> from pyramids.base.config import EnvironmentVariables
>>> env = EnvironmentVariables()
>>> isinstance(env.paths, list)
True
```
See Also
- Plugins: Uses EnvironmentVariables to adjust PATH when GDAL bins are found.
Source code in src/pyramids/base/config.py
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 | |
path
property
#
Return the raw PATH environment variable.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The current value of the PATH environment variable, or an empty string if not set. |
Examples: - Read PATH as a string
```python
>>> from pyramids.base.config import EnvironmentVariables
>>> ev = EnvironmentVariables()
>>> isinstance(ev.path, str)
True
```
paths
property
#
Return PATH components as a list, split by the OS separator.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: A list of absolute/relative directories contained in PATH. |
Examples: - Split PATH into components
```python
>>> from pyramids.base.config import EnvironmentVariables
>>> ev = EnvironmentVariables()
>>> isinstance(ev.paths, list)
True
```
if_exists(path)
#
Check whether a directory exists in PATH.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Directory to look for. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the directory is already present in PATH, False otherwise. |
Examples: - Check for a directory in PATH
```python
>>> from pyramids.base.config import EnvironmentVariables
>>> env = EnvironmentVariables()
>>> env.if_exists("C:/") in (True, False)
True
```
Source code in src/pyramids/base/config.py
prepend(path)
#
Prepend a directory to PATH if not already present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Directory to prepend to PATH. |
required |
Examples:
- Prepend a directory to PATH safely. The example uses a relative, colon-free
name so it prints identically on Windows and POSIX (on POSIX, a drive-style
path like
C:/example/binwould be split at the colon byos.pathsep):
Source code in src/pyramids/base/config.py
Plugins
dataclass
#
Discover and export GDAL-related paths within a Python site-packages tree.
Given a site-packages directory, this helper resolves conventional GDAL locations used by Conda-forge (Library/Lib/gdalplugins, Library/bin, etc.) and can export them into environment variables suitable for GDAL loading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
site_packages_path
|
str | Path
|
Root path to a site-packages directory (e.g., one of values from site.getsitepackages()). |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
plugins_path |
Path | None
|
Expected GDAL plugins directory. |
bin_path |
Path | None
|
Expected DLL bin directory. |
data_path |
Path | None
|
Expected GDAL data directory. |
proj_path |
Path | None
|
Expected PROJ data directory. |
Examples:
- Discover GDAL paths and export to the environment
See Also
- EnvironmentVariables: Used to manage PATH updates.
- Config.dynamic_env_variables: Uses this class to probe for GDAL on Windows.
Source code in src/pyramids/base/config.py
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | |
__post_init__()
#
Initialize derived GDAL-related paths based on site_packages_path.
Source code in src/pyramids/base/config.py
check_path()
#
Probe known locations under site-packages and set GDAL env variables.
This method checks for the presence of the GDAL plugins folder and, if found, sets the following environment variables where appropriate: - GDAL_DRIVER_PATH - Optionally prepends Library/bin to PATH (so GDAL plugin DLLs resolve) - Optionally sets GDAL_DATA and PROJ_LIB if those directories exist
Returns:
| Type | Description |
|---|---|
Path | None
|
pathlib.Path | None: The detected plugins_path if found, otherwise None. |
Examples:
- Probe a site-packages tree and set environment variables
Source code in src/pyramids/base/config.py
Config
#
High-level configuration entry point for logging and GDAL environment.
This class orchestrates: - Loading user/package configuration from YAML. - Configuring Python logging (console with colors, optional file). - Initializing GDAL/OGR and discovering GDAL-related environment variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int | str | None
|
Logging level. |
None
|
log_file
|
str | Path | None
|
Optional path to a file for logs. |
None
|
config_file
|
str
|
YAML filename to read from the package's base folder. Defaults to "config.yaml". |
'config.yaml'
|
Attributes:
| Name | Type | Description |
|---|---|---|
config |
dict
|
Parsed configuration values from YAML. |
logger |
Logger
|
Module logger configured by setup_logging(). |
Examples: - Create a configuration with console logging
```python
>>> from pyramids.base.config import Config # doctest: +SKIP
>>> cfg = Config(level="INFO") # doctest: +SKIP
>>> print(cfg.settings) # doctest: +SKIP
{'gdal': {'GDAL_CACHEMAX': '512',
'GDAL_PAM_ENABLED': 'YES',
'GDAL_VRT_ENABLE_PYTHON': 'YES',
'GDAL_TIFF_INTERNAL_MASK': 'NO'},
'ogr': {'OGR_SRS_PARSER': 'strict'},
'logging': {'level': 'DEBUG',
'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
'file': 'pyramids.log'}}
````
See Also
- LoggerManager: Implements logging configuration details.
- Config.initialize_gdal: Applies GDAL/OGR options and registers drivers.
Source code in src/pyramids/base/config.py
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | |
__init__(level=None, log_file=None, config_file='config.yaml', quiet_third_party=False)
#
Construct a Config, load YAML, configure logging, and initialize GDAL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int | str | None
|
Logging level (e.g., logging.INFO or "DEBUG"). |
None
|
log_file
|
str | Path | None
|
Optional path to a log file. |
None
|
config_file
|
str
|
Name of the YAML configuration file shipped in pyramids/base. Defaults to "config.yaml". |
'config.yaml'
|
quiet_third_party
|
bool
|
Pin fiona / rasterio / shapely / matplotlib / urllib3 / osgeo to WARNING. Off by default — those belong to other libraries, and a host that deliberately raised one of them should keep its setting. |
False
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the YAML file cannot be found. |
YAMLError
|
If parsing the YAML fails. |
Exception
|
Any GDAL-related error if GDAL initialization fails. |
Examples:
- Create a configuration with INFO logging
Source code in src/pyramids/base/config.py
load_config()
#
Load configuration from the package YAML file.
The YAML file is expected to live under pyramids/base/
Returns:
| Type | Description |
|---|---|
|
dict[str, Any]: Parsed configuration values. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the configuration file is not found. |
YAMLError
|
If the YAML cannot be parsed. |
Examples:
- Load settings and verify the result is a dictionary
>>> from pyramids.base.config import Config >>> cfg = Config(config_file="config.yaml") >>> print(cfg.settings) # doctest: +SKIP {'gdal': {'GDAL_CACHEMAX': '512', 'GDAL_PAM_ENABLED': 'YES', 'GDAL_VRT_ENABLE_PYTHON': 'YES', 'GDAL_TIFF_INTERNAL_MASK': 'NO'}, 'ogr': {'OGR_SRS_PARSER': 'strict'}, 'logging': {'level': 'DEBUG', 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s', 'file': 'pyramids.log'}}
Source code in src/pyramids/base/config.py
initialize_gdal()
#
Initialize GDAL/OGR options and register drivers.
This method:
- Enables exceptions in GDAL and OGR.
- Applies options from the loaded YAML under keys gdal and ogr.
- Attempts to detect and export the GDAL_DRIVER_PATH using dynamic_env_variables().
- Calls gdal.AllRegister() to ensure drivers are available.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If GDAL initialization encounters issues (propagated from GDAL). |
Examples:
- Initialize GDAL and then query GDAL_DRIVER_PATH
See Also
- Config.dynamic_env_variables: Locates plugin directories across platforms.
Source code in src/pyramids/base/config.py
set_env_conda()
#
Set GDAL-related environment variables in a Conda environment.
This method looks up the active Conda environment (via CONDA_PREFIX) and configures: - GDAL_DRIVER_PATH (if Library/lib/gdalplugins exists) - PATH (prepends Library/bin so dependent DLLs can be found) - GDAL_DATA and PROJ_LIB (if their directories exist)
Returns:
| Type | Description |
|---|---|
Path | None
|
pathlib.Path | None: The GDAL plugins path if found, else None. |
Examples:
- Configure environment variables when running inside Conda
Source code in src/pyramids/base/config.py
dynamic_env_variables()
#
Locate GDAL plugin directories and export GDAL_DRIVER_PATH.
The search proceeds in this order: - If inside Conda, use set_env_conda(). - On Windows, probe site.getsitepackages() using Plugins helper. - On POSIX, probe common locations like /usr/local/lib/gdalplugins.
Returns:
| Type | Description |
|---|---|
Path | None
|
pathlib.Path | None: The detected GDAL plugins path, or None if not found. |
Examples:
- Attempt to discover plugin directory in the current environment
See Also
- Plugins: Windows helper for site-packages probing.
- Config.set_env_conda: Conda-specific environment configuration.
Source code in src/pyramids/base/config.py
setup_logging(level=None, log_file=None, quiet_third_party=False)
#
Configure the "pyramids" logger by delegating to LoggerManager.
This method preserves the public API while separating responsibilities. It delegates the actual logging configuration to the LoggerManager constructor and then sets self.logger and self._logging_configured for convenience/compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int | str | None
|
Logging level, or |
None
|
log_file
|
str | Path | None
|
Optional log-file path. |
None
|
quiet_third_party
|
bool
|
Pin the noisy third-party loggers to WARNING. Off by default. |
False
|