3
0
Fork 0

fix: fix 'import-outside-toplevel' for pylint

This commit is contained in:
Lance Edgar 2025-08-31 11:17:24 -05:00
parent a6bb538ce9
commit 8ede2fc406
6 changed files with 42 additions and 33 deletions

View file

@ -4,7 +4,6 @@
disable= disable=
attribute-defined-outside-init, attribute-defined-outside-init,
fixme, fixme,
import-outside-toplevel,
too-many-arguments, too-many-arguments,
too-many-branches, too-many-branches,
too-many-locals, too-many-locals,

View file

@ -25,11 +25,12 @@ WuttJamaican - app handler
""" """
# pylint: disable=too-many-lines # pylint: disable=too-many-lines
import importlib
import logging import logging
import os import os
import sys import sys
import warnings import warnings
import importlib
from importlib.metadata import version
import humanize import humanize
@ -282,9 +283,13 @@ class AppHandler: # pylint: disable=too-many-public-methods
pkgname = modpath.split(".")[0] pkgname = modpath.split(".")[0]
try: try:
from importlib.metadata import packages_distributions from importlib.metadata import ( # pylint: disable=import-outside-toplevel
packages_distributions,
)
except ImportError: # python < 3.10 except ImportError: # python < 3.10
from importlib_metadata import packages_distributions from importlib_metadata import ( # pylint: disable=import-outside-toplevel
packages_distributions,
)
pkgmap = packages_distributions() pkgmap = packages_distributions()
if pkgname in pkgmap: if pkgname in pkgmap:
@ -306,8 +311,6 @@ class AppHandler: # pylint: disable=too-many-public-methods
:returns: Version as string. :returns: Version as string.
""" """
from importlib.metadata import version
if not dist: if not dist:
dist = self.get_distribution(obj=obj) dist = self.get_distribution(obj=obj)
if dist: if dist:
@ -496,7 +499,7 @@ class AppHandler: # pylint: disable=too-many-public-methods
:returns: SQLAlchemy session for the app DB. :returns: SQLAlchemy session for the app DB.
""" """
from .db import Session from .db import Session # pylint: disable=import-outside-toplevel
return Session(**kwargs) return Session(**kwargs)
@ -582,7 +585,7 @@ class AppHandler: # pylint: disable=too-many-public-methods
associated. Simple convenience wrapper around associated. Simple convenience wrapper around
:func:`sqlalchemy:sqlalchemy.orm.object_session()`. :func:`sqlalchemy:sqlalchemy.orm.object_session()`.
""" """
from sqlalchemy import orm from sqlalchemy import orm # pylint: disable=import-outside-toplevel
return orm.object_session(obj) return orm.object_session(obj)
@ -597,7 +600,7 @@ class AppHandler: # pylint: disable=too-many-public-methods
this method will provide a default factory in the form of this method will provide a default factory in the form of
:meth:`make_session`. :meth:`make_session`.
""" """
from .db import short_session from .db import short_session # pylint: disable=import-outside-toplevel
if "factory" not in kwargs and "config" not in kwargs: if "factory" not in kwargs and "config" not in kwargs:
kwargs["factory"] = self.make_session kwargs["factory"] = self.make_session
@ -625,7 +628,7 @@ class AppHandler: # pylint: disable=too-many-public-methods
:returns: Setting value as string, or ``None``. :returns: Setting value as string, or ``None``.
""" """
from .db import get_setting from .db import get_setting # pylint: disable=import-outside-toplevel
return get_setting(session, name) return get_setting(session, name)
@ -1114,7 +1117,6 @@ class AppProvider: # pylint: disable=too-few-public-methods
""" """
def __init__(self, config): def __init__(self, config):
if isinstance(config, AppHandler): if isinstance(config, AppHandler):
warnings.warn( warnings.warn(
"passing app handler to app provider is deprecated; " "passing app handler to app provider is deprecated; "

View file

@ -108,7 +108,7 @@ class AuthHandler(GenericHandler): # pylint: disable=too-many-public-methods
:returns: :class:`~wuttjamaican.db.model.auth.User` instance, :returns: :class:`~wuttjamaican.db.model.auth.User` instance,
or ``None``. or ``None``.
""" """
from sqlalchemy import orm from sqlalchemy import orm # pylint: disable=import-outside-toplevel
model = self.app.model model = self.app.model
@ -170,7 +170,6 @@ class AuthHandler(GenericHandler): # pylint: disable=too-many-public-methods
return role return role
else: # assuming it is a string else: # assuming it is a string
# try to match on Role.uuid # try to match on Role.uuid
try: try:
role = session.get(model.Role, _uuid.UUID(key)) role = session.get(model.Role, _uuid.UUID(key))
@ -226,7 +225,6 @@ class AuthHandler(GenericHandler): # pylint: disable=too-many-public-methods
# nb. these lookups require a db session # nb. these lookups require a db session
if session: if session:
# or maybe it is a uuid # or maybe it is a uuid
if isinstance(obj, _uuid.UUID): if isinstance(obj, _uuid.UUID):
user = session.get(model.User, obj) user = session.get(model.User, obj)
@ -235,7 +233,6 @@ class AuthHandler(GenericHandler): # pylint: disable=too-many-public-methods
# or maybe it is a string # or maybe it is a string
elif isinstance(obj, str): elif isinstance(obj, str):
# try to match on User.uuid # try to match on User.uuid
try: try:
user = session.get(model.User, _uuid.UUID(obj)) user = session.get(model.User, _uuid.UUID(obj))

View file

@ -240,7 +240,10 @@ class WuttaConfig: # pylint: disable=too-many-instance-attributes
# configure main app DB if applicable, or disable usedb flag # configure main app DB if applicable, or disable usedb flag
try: try:
from wuttjamaican.db import Session, get_engines from wuttjamaican.db import ( # pylint: disable=import-outside-toplevel
Session,
get_engines,
)
except ImportError: except ImportError:
if self.usedb: if self.usedb:
log.warning( log.warning(
@ -448,7 +451,6 @@ class WuttaConfig: # pylint: disable=too-many-instance-attributes
# read from defaults + INI files # read from defaults + INI files
value = self.configuration.get(key) value = self.configuration.get(key)
if value is not None: if value is not None:
# nb. if the "value" corresponding to the given key is in # nb. if the "value" corresponding to the given key is in
# fact a subset/dict of more config values, then we must # fact a subset/dict of more config values, then we must
# "ignore" that. so only return the value if it is *not* # "ignore" that. so only return the value if it is *not*
@ -611,7 +613,6 @@ class WuttaConfig: # pylint: disable=too-many-instance-attributes
os.remove(path) os.remove(path)
def _write_logging_config_file(self): def _write_logging_config_file(self):
# load all current values into configparser # load all current values into configparser
parser = configparser.RawConfigParser() parser = configparser.RawConfigParser()
for section, values in self.configuration.items(): for section, values in self.configuration.items():
@ -710,7 +711,10 @@ def generic_default_files(appname):
if sys.platform == "win32": if sys.platform == "win32":
# use pywin32 to fetch official defaults # use pywin32 to fetch official defaults
try: try:
from win32com.shell import shell, shellcon from win32com.shell import ( # pylint: disable=import-outside-toplevel
shell,
shellcon,
)
except ImportError: except ImportError:
return [] return []

View file

@ -240,7 +240,7 @@ class InstallHandler(GenericHandler):
self, dbtype, dbhost, dbport, dbname, dbuser, dbpass self, dbtype, dbhost, dbport, dbname, dbuser, dbpass
): # pylint: disable=empty-docstring ): # pylint: disable=empty-docstring
""" """ """ """
from sqlalchemy.engine import URL from sqlalchemy.engine import URL # pylint: disable=import-outside-toplevel
if dbtype == "mysql": if dbtype == "mysql":
drivername = "mysql+mysqlconnector" drivername = "mysql+mysqlconnector"
@ -258,7 +258,7 @@ class InstallHandler(GenericHandler):
def test_db_connection(self, url): # pylint: disable=empty-docstring def test_db_connection(self, url): # pylint: disable=empty-docstring
""" """ """ """
import sqlalchemy as sa import sqlalchemy as sa # pylint: disable=import-outside-toplevel
engine = sa.create_engine(url) engine = sa.create_engine(url)
@ -442,7 +442,9 @@ class InstallHandler(GenericHandler):
:param db_url: :class:`sqlalchemy:sqlalchemy.engine.URL` :param db_url: :class:`sqlalchemy:sqlalchemy.engine.URL`
instance. instance.
""" """
from alembic.util.messaging import obfuscate_url_pw from alembic.util.messaging import ( # pylint: disable=import-outside-toplevel
obfuscate_url_pw,
)
if not self.prompt_bool("install db schema?", True): if not self.prompt_bool("install db schema?", True):
return False return False
@ -488,7 +490,7 @@ class InstallHandler(GenericHandler):
def require_prompt_toolkit(self, answer=None): # pylint: disable=empty-docstring def require_prompt_toolkit(self, answer=None): # pylint: disable=empty-docstring
""" """ """ """
try: try:
import prompt_toolkit # pylint: disable=unused-import import prompt_toolkit # pylint: disable=unused-import,import-outside-toplevel
except ImportError: except ImportError:
value = answer or input( value = answer or input(
"\nprompt_toolkit is not installed. shall i install it? [Yn] " "\nprompt_toolkit is not installed. shall i install it? [Yn] "
@ -503,7 +505,7 @@ class InstallHandler(GenericHandler):
) )
# nb. this should now succeed # nb. this should now succeed
import prompt_toolkit import prompt_toolkit # pylint: disable=import-outside-toplevel
def rprint(self, *args, **kwargs): def rprint(self, *args, **kwargs):
""" """
@ -513,7 +515,9 @@ class InstallHandler(GenericHandler):
def get_prompt_style(self): # pylint: disable=empty-docstring def get_prompt_style(self): # pylint: disable=empty-docstring
""" """ """ """
from prompt_toolkit.styles import Style from prompt_toolkit.styles import ( # pylint: disable=import-outside-toplevel
Style,
)
# message formatting styles # message formatting styles
return Style.from_dict( return Style.from_dict(
@ -554,7 +558,7 @@ class InstallHandler(GenericHandler):
unless ``is_bool`` was requested in which case ``True`` or unless ``is_bool`` was requested in which case ``True`` or
``False``. ``False``.
""" """
from prompt_toolkit import prompt from prompt_toolkit import prompt # pylint: disable=import-outside-toplevel
# build prompt message # build prompt message
message = [ message = [

View file

@ -101,9 +101,9 @@ def load_entry_points(group, ignore_errors=False):
try: try:
# nb. this package was added in python 3.8 # nb. this package was added in python 3.8
import importlib.metadata as importlib_metadata import importlib.metadata as importlib_metadata # pylint: disable=import-outside-toplevel
except ImportError: except ImportError:
import importlib_metadata import importlib_metadata # pylint: disable=import-outside-toplevel
eps = importlib_metadata.entry_points() eps = importlib_metadata.entry_points()
if not hasattr(eps, "select"): if not hasattr(eps, "select"):
@ -306,9 +306,7 @@ def progress_loop(func, items, factory, message=None):
progress = factory(message, count) progress = factory(message, count)
for i, item in enumerate(items, 1): for i, item in enumerate(items, 1):
func(item, i) func(item, i)
if progress: if progress:
progress.update(i) progress.update(i)
@ -343,12 +341,17 @@ def resource_path(path):
:returns: Absolute file path to the resource. :returns: Absolute file path to the resource.
""" """
if not os.path.isabs(path) and ":" in path: if not os.path.isabs(path) and ":" in path:
try: try:
# nb. these were added in python 3.9 # nb. these were added in python 3.9
from importlib.resources import files, as_file from importlib.resources import ( # pylint: disable=import-outside-toplevel
files,
as_file,
)
except ImportError: # python < 3.9 except ImportError: # python < 3.9
from importlib_resources import files, as_file from importlib_resources import ( # pylint: disable=import-outside-toplevel
files,
as_file,
)
package, filename = path.split(":") package, filename = path.split(":")
ref = files(package) / filename ref = files(package) / filename