1

Problem:

Mypy Error: The mypy error encountered is as follows:

error:Import cycle from Django settings module prevents type inference for 'LANGUAGES' [misc]

I'm encountering challenges with the usage of gettext_lazy in Django 4 settings while utilizing django-stubs. The recent update in Django 4 brought changes to the typing of gettext_lazy, where the old return type was str, and the new type is _StrPromise. The issue arises from the fact that _StrPromise is defined in "django-stubs/utils/functional.pyi," and within this file, there is also an import of django.db.model which imports settings. This creates a circular import.

current module-version:

typing

mypy = "1.7"
django-stubs = "4.2.7"

Django dependencies

Django = "4.2.10"

Seeking advice on a cleaner and more sustainable solution to the circular import issue and mypy error in the context of Django 4 settings with the updated gettext_lazy typing. Any insights or alternative approaches would be greatly appreciated.

possible Solutions:

Several solutions have been considered, but none of them are ideal:

  1. Disable Mypy Typing for Settings: Disabling Mypy typing for settings is a workaround, but it might compromise the benefits of static typing.

  2. Remove gettext_lazy from Settings: Another option is to remove gettext_lazy from settings. However, this contradicts the current recommendations in Django 4 and 5 documentation, which still advocate for the use of gettext_lazy in the LANGUAGE setting.


1 Answer 1

1

Also just encountered this. This is explained in the django-stubs readme.

If you encounter this error in your own code, you can either cast the Promise to str (causing the translation to be evaluated), or use the StrPromise or StrOrPromise types from django-stubs-ext in type hints.

To get the type hints, you need to install the stubs extension:

pip install django-stubs-ext

Then you can import the hints:

from django_stubs_ext import StrPromise


my_lazy_str: StrPromise = gettext_lazy("foobar")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.