Incomplete sheet
This sheet is incomplete and could use some attention. Please submit code snippet suggestions as an issue or PR here.
Package
Functions for importing packages or accessing information about packages.
Test
| Action |
Code |
Details |
|
Check if package or top-level module Name exists
|
import importlib.util
importlib.util.find_spec("Name") is not None
|
Can be used to check for submodules, but this loads the parent import! |
|
Check if package or module Pkg is loaded
|
|
|
| Action |
Code |
Details |
|
Get file path from package
|
from importlib import resources
path = str(resources.files('actionsheets.data').joinpath('python.toml'))
|
|
|
Get file paths from package according to pattern, recursively
|
from importlib import resources
from importlib.resources.abc import Traversable
def gather_files(entries: Iterator[Traversable]) -> list[str]:
files_list = []
for entry in entries:
if entry.is_dir():
files_list += gather_files(entry.iterdir())
elif entry.name.endswith('.csv'):
files_list += [entry]
return files_list
data_root = resources.files('actionsheets.data')
paths = gather_files(data_root.iterdir())
|
Code could be simplified |
| Action |
Code |
Details |
|
Version of a given package
|
from importlib.metadata import version
version('actionsheets')
|
|
|
All package metadata, as dict
|
from importlib.metadata import metadata
dict(metadata('actionsheets'))
|
Conceals duplicate metadata entries |
Import
| Action |
Code |
Details |
|
Import package or top-level module
|
|
|
|
Try import package or top-level module
|
try:
import actionsheetsss
except ImportError as e
print(e)
|
|
|
Try import package or top-level module, store result in indicator variable
|
try:
import actionsheets
assert actionsheets
_no_actionsheets = False
except ImportError:
_no_actionsheets = True
|
|
|
Try to import submodule, catch error if not found
|
try:
import actionsheets.paper
except ModuleNotFoundError as e:
print(e)
|
|