Isort: Sets `py_version = "py3"` in `_Config` class, but only accepts "3"

Created on 4 Jul 2020  路  3Comments  路  Source: PyCQA/isort

I'm calling isort 5.0.2 directly from Python, passing isort.settings._DEFAULT_SETTINGS as keyword arguments to sort_code_string(). It seems that the _Config class from which _DEFAULT_SETTINGS are copied initializes its self.py_version = "py3" while in __post_init__ that value is not accepted.

>>> from isort.settings import _DEFAULT_SETTINGS
>>> from isort.api import sort_code_string
>>> sort_code_string('import sys\nimport os\n', **_DEFAULT_SETTINGS)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "isort/api.py", line 52, in sort_code_string
    config = _config(path=file_path, config=config, **config_kwargs)
  File "isort/api.py", line 329, in _config
    config = Config(**config_kwargs)
  File "isort/settings.py", line 309, in __init__
    super().__init__(sources=tuple(sources), **combined_config)  # type: ignore
  File "<string>", line 64, in __init__
  File "isort/settings.py", line 167, in __post_init__
    f"The python version {py_version} is not supported. "
ValueError: The python version py3 is not supported. You can set a python version with the -py or --python-version flag. The following versions are supported: ('all', '2', '27', '3', '35', '36', '37', '38', '39')
question

All 3 comments

@akaihola, Thanks for reaching out! I would like to understand better what is intended to be done here, so I can improve the documentation (and potentially implementation). Some background: Default settings are automatically included and should never need to be manually done in this way (thus the prefixed _). Anything setting you specify will override what is defined in the defaults. The actual default settings are captured in a isort.settings.DEFAULT_CONFIG, and _DEFAULT_SETTINGS are just the internal memory representation of that objects dictionary.

conceptually:

# given
from isort import api
from isort.settings import DEFAULT_CONFIG
from isort.api import sort_code_string
sort_code_string('import sys\nimport os\n', config=DEFAULT_CONFIG) == sort_code_string('import sys\nimport os\n') == isort.code('import sys\nimport os\n')

Thanks for you answer Timothy!

Actually we now figured out better how isort 5.x handles its configuration, and indeed were able to get rid of dealing with the default settings. Great improvements in this major release of isort!

In case you're interested, what we're developing is the darker utility for applying Black formatting incrementally to changed code only. Since Black doesn't handle ordering of imports, we included calling isort for that.

That looks like an awesome project!

Was this page helpful?
0 / 5 - 0 ratings