this post was submitted on 21 Nov 2023
10 points (100.0% liked)

Python

6233 readers
1 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

October 2023

November 2023

PastJuly 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
 

Let's say I have the following structure:

my_module/
  __init__.py
  utilities.py

and __init__.py contains

from .utilities import SomeUtilityFunction

Is there a way to prevent or alert developers when they do

from my_module.utilities import SomeUtilityFunction

instead of

from my_module import SomeUtilityFunction

The problem arose when a few modules started using a function that was imported inside a module in which it wasn't used, while also being available on the module's __init__.py, so after linting the file and removing the unused import my tests started failing.

any other advice for situations like this?

you are viewing a single comment's thread
view the rest of the comments
[–] Chais@sh.itjust.works 3 points 10 months ago* (last edited 10 months ago) (1 children)

You could guard it.
__init__.py:

_GUARD_SOME_UTILITY_FUNCTION = True
from .utilities import SomeUtilityFunction

utilities.py:

def SomeUtilityFunction():
    if not _GUARD_SOME_UTILITY_FUNCTION:
        raise SomeException("Helpful error message")

Take this with a grain of salt, as I'm typing this on my phone and haven't actually tried it.

Alternatively there's the import-guard package on PyPI. No idea if it's any good, though. Just something a quick search brought up.

Edit:
Ok, I tried my suggestion and it doesn't work.

[–] sebsch@discuss.tchncs.de 2 points 10 months ago* (last edited 10 months ago) (1 children)

This approach seems quite overkomplex. Instead of having these errors on runtime, stuff like this should sit in linter rules of any kind.

[–] Chais@sh.itjust.works 2 points 10 months ago

It's only useful during development there.