Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored master branch #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

sourcery-ai[bot]
Copy link

@sourcery-ai sourcery-ai bot commented Aug 2, 2022

Branch master refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the master branch, then run:

git fetch origin sourcery/master
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai sourcery-ai bot requested a review from rtk-rnjn August 2, 2022 18:12
Copy link
Author

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Due to GitHub API limits, only the first 60 comments can be shown.

if parts[-1] == '__init__':
suffix = parts[-2]
else:
suffix = parts[-1]

suffix = parts[-2] if parts[-1] == '__init__' else parts[-1]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_export_symbols refactored with the following changes:

Comment on lines -75 to +74
if not any(arg in sys.argv for arg in ['clean', 'check']) and 'SKIP_CYTHON' not in os.environ:
if (
all(arg not in sys.argv for arg in ['clean', 'check'])
and 'SKIP_CYTHON' not in os.environ
):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 75-75 refactored with the following changes:

Comment on lines -23 to +29
MAX_LINE_LENGTH = int(re.search(r'max_line_length = (\d+)', (EXAMPLES_DIR / '.editorconfig').read_text()).group(1))
MAX_LINE_LENGTH = int(
re.search(
r'max_line_length = (\d+)',
(EXAMPLES_DIR / '.editorconfig').read_text(),
)[1]
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 23-23 refactored with the following changes:

Comment on lines -90 to +97
m = re.search(r'^( *)print\(', lines[line_no - back])
if m:
indent = m.group(1)
if m := re.search(r'^( *)print\(', lines[line_no - back]):
indent = m[1]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_print_statement refactored with the following changes:

Comment on lines -104 to +109
file_contents = []
for f in DOCS_DIR.glob('**/*.md'):
file_contents.append(f.read_text())
file_contents = [f.read_text() for f in DOCS_DIR.glob('**/*.md')]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function all_md_contents refactored with the following changes:

if isinstance(v, str):
return v.split('|')
return v
return v.split('|') if isinstance(v, str) else v
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DemoModel.split_str refactored with the following changes:

assert each_item is False, '"each_item" and "whole" conflict, remove "whole"'
assert not each_item, '"each_item" and "whole" conflict, remove "whole"'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function validator refactored with the following changes:

ref = f_cls.__func__.__module__ + '.' + f_cls.__func__.__qualname__
ref = f'{f_cls.__func__.__module__}.{f_cls.__func__.__qualname__}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _prepare_validator refactored with the following changes:

if validators:
return {v.func.__name__: v for v in validators}
else:
return None
return {v.func.__name__: v for v in validators} if validators else None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ValidatorGroup.get_validators refactored with the following changes:

Comment on lines -168 to +170
unused_validators = set(
if unused_validators := set(
chain.from_iterable(
(v.func.__name__ for v in self.validators[f] if v.check_fields)
for f in (self.validators.keys() - self.used_validators)
)
)
if unused_validators:
):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ValidatorGroup.check_for_unused refactored with the following changes:

Comment on lines -185 to +181
validator_config = getattr(value, VALIDATOR_CONFIG_KEY, None)
if validator_config:
if validator_config := getattr(value, VALIDATOR_CONFIG_KEY, None):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function extract_validators refactored with the following changes:

Comment on lines -279 to +274
elif args == set():
elif not args:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _generic_validator_cls refactored with the following changes:

Comment on lines -312 to +307
elif args == set():
elif not args:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _generic_validator_basic refactored with the following changes:

Comment on lines -93 to +102
if self._rgba.alpha is None:
rgb = cast(Tuple[int, int, int], self.as_rgb_tuple())
try:
return COLORS_BY_VALUE[rgb]
except KeyError as e:
if fallback:
return self.as_hex()
else:
raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
else:
if self._rgba.alpha is not None:
return self.as_hex()
rgb = cast(Tuple[int, int, int], self.as_rgb_tuple())
try:
return COLORS_BY_VALUE[rgb]
except KeyError as e:
if fallback:
return self.as_hex()
else:
raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Color.as_named refactored with the following changes:

Comment on lines -117 to +116
return '#' + as_hex
return f'#{as_hex}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Color.as_hex refactored with the following changes:

def __call__(self, settings: BaseSettings) -> Dict[str, Any]: # noqa C901
def __call__(self, settings: BaseSettings) -> Dict[str, Any]: # noqa C901
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EnvSettingsSource.__call__ refactored with the following changes:

This removes the following comments ( why? ):

# field is complex but no value found so far, try explode_env_vars

Comment on lines -303 to +305
if not case_sensitive:
return {k.lower(): v for k, v in file_vars.items()}
else:
return file_vars
return (
file_vars
if case_sensitive
else {k.lower(): v for k, v in file_vars.items()}
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function read_env_file refactored with the following changes:

if isinstance(self._loc, tuple):
return self._loc
else:
return (self._loc,)
return self._loc if isinstance(self._loc, tuple) else (self._loc, )
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ErrorWrapper.loc_tuple refactored with the following changes:

Comment on lines -92 to +89
ctx = error.get('ctx')
if ctx:
if ctx := error.get('ctx'):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _display_error_type_and_ctx refactored with the following changes:

Comment on lines -105 to +101
if loc:
error_loc = loc + error.loc_tuple()
else:
error_loc = error.loc_tuple()

error_loc = loc + error.loc_tuple() if loc else error.loc_tuple()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function flatten_errors refactored with the following changes:

Comment on lines -124 to +116
if msg_template:
msg = msg_template.format(**ctx)
else:
msg = str(exc)

msg = msg_template.format(**ctx) if msg_template else str(exc)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function error_dict refactored with the following changes:

Comment on lines -162 to +150
return base_name + '.' + code
return f'{base_name}.{code}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _get_exc_type refactored with the following changes:

# Create self validators
get_validators = getattr(self.type_, '__get_validators__', None)
if get_validators:
if get_validators := getattr(self.type_, '__get_validators__', None):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ModelField._type_analysis refactored with the following changes:

This removes the following comments ( why? ):

# Equality check as almost everything inherits form Iterable, including str
# check for Iterable and CollectionsIterable, as it could receive one even when declared with the other
# Create self validators
# priority to most common mapping: dict

Comment on lines -971 to +974
if errors:
return v, errors
else:
return tuple(result), None
return (v, errors) if errors else (tuple(result), None)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ModelField._validate_tuple refactored with the following changes:

if original_cls == dict or original_cls == Dict:
if original_cls in [dict, Dict]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ModelField._get_mapping_value refactored with the following changes:

if isinstance(obj, GetterDict):
return obj
return cls.__config__.getter_dict(obj)
return obj if isinstance(obj, GetterDict) else cls.__config__.getter_dict(obj)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BaseModel._decompose_class refactored with the following changes:

Comment on lines -717 to +726
if to_dict:
v_dict = v.dict(
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
include=include,
exclude=exclude,
exclude_none=exclude_none,
)
if ROOT_KEY in v_dict:
return v_dict[ROOT_KEY]
return v_dict
else:
if not to_dict:
return v.copy(include=include, exclude=exclude)

v_dict = v.dict(
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
include=include,
exclude=exclude,
exclude_none=exclude_none,
)
return v_dict[ROOT_KEY] if ROOT_KEY in v_dict else v_dict
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BaseModel._get_value refactored with the following changes:

Comment on lines -862 to +861
if include is None and exclude is None and exclude_unset is False:
if include is None and exclude is None and not exclude_unset:
return None

keys: AbstractSet[str]
if exclude_unset:
keys = self.__fields_set__.copy()
else:
keys = self.__dict__.keys()

keys = self.__fields_set__.copy() if exclude_unset else self.__dict__.keys()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BaseModel._calculate_keys refactored with the following changes:

Comment on lines -91 to +98
if sym and isinstance(sym.node, TypeInfo): # pragma: no branch
# No branching may occur if the mypy cache has not been cleared
if any(get_fullname(base) == BASEMODEL_FULLNAME for base in sym.node.mro):
return self._pydantic_model_class_maker_callback
if (
sym
and isinstance(sym.node, TypeInfo)
and any(
get_fullname(base) == BASEMODEL_FULLNAME for base in sym.node.mro
)
):
return self._pydantic_model_class_maker_callback
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PydanticPlugin.get_base_class_hook refactored with the following changes:

This removes the following comments ( why? ):

# No branching may occur if the mypy cache has not been cleared
# pragma: no branch

Comment on lines -98 to +102
if fullname.endswith('.from_orm'):
return from_orm_callback
return None
return from_orm_callback if fullname.endswith('.from_orm') else None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PydanticPlugin.get_method_hook refactored with the following changes:

@sourcery-ai
Copy link
Author

sourcery-ai bot commented Aug 2, 2022

Sourcery Code Quality Report

✅  Merging this PR will increase code quality in the affected files by 0.15%.

Quality metrics Before After Change
Complexity 5.48 ⭐ 5.32 ⭐ -0.16 👍
Method Length 68.50 🙂 68.38 🙂 -0.12 👍
Working memory 6.74 🙂 6.73 🙂 -0.01 👍
Quality 72.54% 🙂 72.69% 🙂 0.15% 👍
Other metrics Before After Change
Lines 22497 22387 -110
Changed files Quality Before Quality After Quality Change
setup.py 63.31% 🙂 62.98% 🙂 -0.33% 👎
docs/build/exec_examples.py 40.98% 😞 40.36% 😞 -0.62% 👎
docs/examples/models_custom_root_access.py 98.72% ⭐ 98.86% ⭐ 0.14% 👍
docs/examples/models_orm_mode_data_binding.py 90.59% ⭐ 92.16% ⭐ 1.57% 👍
docs/examples/types_boolean.py 90.56% ⭐ 90.89% ⭐ 0.33% 👍
docs/examples/types_custom_type.py 93.24% ⭐ 92.63% ⭐ -0.61% 👎
docs/examples/types_infinite_generator_validate_first.py 89.25% ⭐ 89.23% ⭐ -0.02% 👎
docs/examples/types_literal1.py 93.06% ⭐ 93.39% ⭐ 0.33% 👍
docs/examples/types_literal2.py 75.17% ⭐ 75.45% ⭐ 0.28% 👍
docs/examples/types_strict.py 69.58% 🙂 69.85% 🙂 0.27% 👍
docs/examples/validators_pre_item.py 91.12% ⭐ 90.93% ⭐ -0.19% 👎
pydantic/class_validators.py 69.49% 🙂 69.46% 🙂 -0.03% 👎
pydantic/color.py 70.09% 🙂 72.19% 🙂 2.10% 👍
pydantic/dataclasses.py 58.68% 🙂 57.84% 🙂 -0.84% 👎
pydantic/datetime_parse.py 67.28% 🙂 67.41% 🙂 0.13% 👍
pydantic/decorator.py 44.69% 😞 44.83% 😞 0.14% 👍
pydantic/env_settings.py 57.98% 🙂 57.49% 🙂 -0.49% 👎
pydantic/error_wrappers.py 81.31% ⭐ 81.31% ⭐ 0.00%
pydantic/fields.py 45.86% 😞 46.32% 😞 0.46% 👍
pydantic/generics.py 51.13% 🙂 51.52% 🙂 0.39% 👍
pydantic/json.py 82.41% ⭐ 82.98% ⭐ 0.57% 👍
pydantic/main.py 41.75% 😞 41.48% 😞 -0.27% 👎
pydantic/mypy.py 60.39% 🙂 59.86% 🙂 -0.53% 👎
pydantic/networks.py 72.42% 🙂 72.38% 🙂 -0.04% 👎
pydantic/schema.py 41.49% 😞 42.17% 😞 0.68% 👍
pydantic/types.py 83.40% ⭐ 83.65% ⭐ 0.25% 👍
pydantic/typing.py 76.55% ⭐ 76.08% ⭐ -0.47% 👎
pydantic/utils.py 73.87% 🙂 73.42% 🙂 -0.45% 👎
pydantic/validators.py 80.32% ⭐ 80.33% ⭐ 0.01% 👍
pydantic/version.py 72.78% 🙂 72.67% 🙂 -0.11% 👎
tests/test_aliases.py 82.48% ⭐ 82.46% ⭐ -0.02% 👎
tests/test_edge_cases.py 78.67% ⭐ 78.70% ⭐ 0.03% 👍
tests/test_generics.py 79.13% ⭐ 79.13% ⭐ 0.00%
tests/test_json.py 80.26% ⭐ 80.10% ⭐ -0.16% 👎
tests/test_main.py 82.81% ⭐ 82.81% ⭐ 0.00%
tests/test_orm_mode.py 75.48% ⭐ 75.76% ⭐ 0.28% 👍
tests/test_schema.py 77.42% ⭐ 77.43% ⭐ 0.01% 👍
tests/test_types.py 81.87% ⭐ 82.02% ⭐ 0.15% 👍
tests/test_validators.py 81.72% ⭐ 81.75% ⭐ 0.03% 👍
tests/test_validators_dataclass.py 82.49% ⭐ 82.43% ⭐ -0.06% 👎
tests/mypy/modules/fail1.py 89.49% ⭐ 89.33% ⭐ -0.16% 👎
tests/mypy/modules/plugin_fail.py 58.76% 🙂 58.75% 🙂 -0.01% 👎

Here are some functions in these files that still need a tune-up:

File Function Complexity Length Working Memory Quality Recommendation
pydantic/main.py ModelMetaclass.__new__ 61 ⛔ 806 ⛔ 2.54% ⛔ Refactor to reduce nesting. Try splitting into smaller methods
pydantic/schema.py get_annotation_with_constraints 65 ⛔ 456 ⛔ 3.13% ⛔ Refactor to reduce nesting. Try splitting into smaller methods
docs/build/exec_examples.py exec_examples 56 ⛔ 552 ⛔ 3.80% ⛔ Refactor to reduce nesting. Try splitting into smaller methods
pydantic/fields.py ModelField._type_analysis 72 ⛔ 972 ⛔ 19 ⛔ 5.66% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
pydantic/main.py validate_model 55 ⛔ 350 ⛔ 19 ⛔ 9.31% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions

Legend and Explanation

The emojis denote the absolute quality of the code:

  • ⭐ excellent
  • 🙂 good
  • 😞 poor
  • ⛔ very poor

The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request.


Please see our documentation here for details on how these metrics are calculated.

We are actively working on this report - lots more documentation and extra metrics to come!

Help us improve this quality report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

0 participants