Sc200 python ошибка

Comments

@nbirillo

GirZ0n

added a commit
that referenced
this issue

Aug 4, 2021

@GirZ0n

@GirZ0n
GirZ0n

linked a pull request

Aug 4, 2021

that will
close
this issue

nbirillo

pushed a commit
that referenced
this issue

Aug 9, 2021

@GirZ0n

vyahhi

added a commit
that referenced
this issue

Aug 13, 2021

* wps-light support (#17)

Add wps-light support

* New flake8 plugins support (#18)

Added support for flake8-broken-line, flake8-string-format, flake8-commas (they are WPS dependencies).
Added support for cohesion.

* Radon support (#19)

Added new inspector: Radon. 
Added maintainability index.

* Requirements upgrade (#21)

Updated versions of dependencies
Added django dictionary support
Fixed tests

* xlsx-run-tool (#24)

Added xlsx_tool_run.py – script to run the tool on multiple code samples stored in xlsx file

* Update version to 1.2.0

* Rename output_format to format

* Fix double quotes

* Fix small issues

* Fix small issues

* Fix double quotes

* Fix double quotes

* Inspectors fix (#39)

* Add origin class for maintainability index
* Add WPS518 to ignore due to collision with C0200 by Pylint

* New category (#38)

* Added a new category INFO, in order not to take into account some issues in the evaluation.

* Fixed trailing commas

* Delete create_directory function

* Fix GitHub actions (#44)

* Use the same environment as in the production dockerfile

* Fix Dockerfiles

* Install some dependencies for TeamCity

* Update build

* Add checks from teamcity

* Update build

* Fix indentation

* Fix PR comments

* Delete init files from resources

* Add init in multi file project

* Fix flake8 tests

* Main upd bugs fix (#74)

* Delete evaluation part
* Fix bugs with detekt, pmd and flake8

* Issues fix (#80)

* Fixed issue #70

* Fixed issue #72: now only spellcheck checks brackets

* Fixed issue #73

* Fixed issue #77

* Fixed issue #78

* Fixed issue #71

* Fixed issue #79

* Fixed issue #81

* Added case 36: unpacking

* Added case 37: wildcard import

* Ignoring WPS347 and F405

* Added cases 36 (unpacking) and 37 (wildcard_import). Also removed W0622 (redefining_builtin)

* Removed W0622 (redefining_builtin)

* Issue #87 fix (#90)

* Fixed issue #87

* Added test

* Fixed issues #91 and #92 (#97)

* Delete xlsx

* Remove openpyxl

* Issues fix (#104)

* Fixed #100

* Fixed #102

* Added some more new words

* Added toplevel

* Update flake8 whitelist

* Recovered accidentally deleted words

Co-authored-by: Vlasov Ilya <55441714+GirZ0n@users.noreply.github.com>
Co-authored-by: Daria Diatlova <dari.diatlova@gmail.com>
Co-authored-by: Nikolay Vyahhi <Nikolay.Vyahhi@stepik.org>
Co-authored-by: Ilya Vlasov <ilyavlasov2011@gmail.com>

nbirillo

added a commit
that referenced
this issue

Aug 26, 2021

* Fix GitHub actions (#46)

* Update requirements and dockerfile
* Use Dockerfile in Github Action
* Ignore a part of flake8 issues
* Ignore flake8 inspections
* Separate docker file into two: for prod and for dev
* Delete `
* Fix test_range_of_lines
* Fix pylint and flake8 tests
* Fix pylint tests
* Check styles by flake8
* Fix C408 issue
* Move production Dockerfile
* Fix Dockefile for production
* Set up Eslint in the DockerFile for production
* Delete one case from flake8 tests
* Add pathlib into whitelist
* Delete Path from setup.py
* Ignore pathlib
* Don't count INFO issues
* Fix flake8 tests
* Small fix
* Delete pathlib from the whitelist
* Update docker (#54)
* Use one docker file for prod and dev
* Change base docker image
* Fix requirements-test: delete duplicates, setup versions
* Try to fix dockerfile
* Fix run in subprocess function
* Fix Dockerfile
* Try to fix Dockerfile
* Fix docker image (#58)
* Change eslint installing
* Update build.yaml
* Introduce base docker image and auto-detect eslint path

Co-authored-by: Andrey Balandin <andrvb@gmail.com>
Closes #43, closes #45.

* Add whitelist for flake8-spellcheck (#68)

* Add whitelist for flake8-spellcheck
* Add a test for spellcheck and ignore unnecessary rule
* Fix flake8 config

* Bump version 1.1.0 -> 1.1.1

* Add Python inspections and a script for tool evaluation (#26)

* wps-light support (#17)

Add wps-light support

* New flake8 plugins support (#18)

Added support for flake8-broken-line, flake8-string-format, flake8-commas (they are WPS dependencies).
Added support for cohesion.

* Radon support (#19)

Added new inspector: Radon. 
Added maintainability index.

* Requirements upgrade (#21)

Updated versions of dependencies
Added django dictionary support
Fixed tests

* xlsx-run-tool (#24)

Added xlsx_tool_run.py – script to run the tool on multiple code samples stored in xlsx file

* Update version to 1.2.0

* Rename output_format to format

* Fix double quotes

* Fix small issues

* Fix small issues

* Fix double quotes

* Fix double quotes

* Inspectors fix (#39)

* Add origin class for maintainability index
* Add WPS518 to ignore due to collision with C0200 by Pylint

* New category (#38)

* Added a new category INFO, in order not to take into account some issues in the evaluation.

* Fixed trailing commas

* Delete create_directory function

* Fix GitHub actions (#44)

* Use the same environment as in the production dockerfile

* Fix Dockerfiles

* Install some dependencies for TeamCity

* Update build

* Add checks from teamcity

* Update build

* Fix indentation

* Fix PR comments

* Delete init files from resources

* Add init in multi file project

* Fix flake8 tests

* Main upd bugs fix (#74)

* Delete evaluation part
* Fix bugs with detekt, pmd and flake8

* Issues fix (#80)

* Fixed issue #70

* Fixed issue #72: now only spellcheck checks brackets

* Fixed issue #73

* Fixed issue #77

* Fixed issue #78

* Fixed issue #71

* Fixed issue #79

* Fixed issue #81

* Added case 36: unpacking

* Added case 37: wildcard import

* Ignoring WPS347 and F405

* Added cases 36 (unpacking) and 37 (wildcard_import). Also removed W0622 (redefining_builtin)

* Removed W0622 (redefining_builtin)

* Issue #87 fix (#90)

* Fixed issue #87

* Added test

* Fixed issues #91 and #92 (#97)

* Delete xlsx

* Remove openpyxl

* Issues fix (#104)

* Fixed #100

* Fixed #102

* Added some more new words

* Added toplevel

* Update flake8 whitelist

* Recovered accidentally deleted words

Co-authored-by: Vlasov Ilya <55441714+GirZ0n@users.noreply.github.com>
Co-authored-by: Daria Diatlova <dari.diatlova@gmail.com>
Co-authored-by: Nikolay Vyahhi <Nikolay.Vyahhi@stepik.org>
Co-authored-by: Ilya Vlasov <ilyavlasov2011@gmail.com>

* Fixed typo

* Sort whitelists (Github Actions)

* Fixed tests

* Fixed requirements

* Added numpy

* Removed numpy

* Fixed test

Co-authored-by: Nastya Birillo <anastasia.i.birillo@gmail.com>
Co-authored-by: Nikolay Vyahhi <Nikolay.Vyahhi@stepik.org>
Co-authored-by: Daria Diatlova <dari.diatlova@gmail.com>
Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

nbirillo

added a commit
that referenced
this issue

Aug 26, 2021

* Fix GitHub actions (#46)

* Update requirements and dockerfile
* Use Dockerfile in Github Action
* Ignore a part of flake8 issues
* Ignore flake8 inspections
* Separate docker file into two: for prod and for dev
* Delete `
* Fix test_range_of_lines
* Fix pylint and flake8 tests
* Fix pylint tests
* Check styles by flake8
* Fix C408 issue
* Move production Dockerfile
* Fix Dockefile for production
* Set up Eslint in the DockerFile for production
* Delete one case from flake8 tests
* Add pathlib into whitelist
* Delete Path from setup.py
* Ignore pathlib
* Don't count INFO issues
* Fix flake8 tests
* Small fix
* Delete pathlib from the whitelist
* Update docker (#54)
* Use one docker file for prod and dev
* Change base docker image
* Fix requirements-test: delete duplicates, setup versions
* Try to fix dockerfile
* Fix run in subprocess function
* Fix Dockerfile
* Try to fix Dockerfile
* Fix docker image (#58)
* Change eslint installing
* Update build.yaml
* Introduce base docker image and auto-detect eslint path

Co-authored-by: Andrey Balandin <andrvb@gmail.com>
Closes #43, closes #45.

* Add whitelist for flake8-spellcheck (#68)

* Add whitelist for flake8-spellcheck
* Add a test for spellcheck and ignore unnecessary rule
* Fix flake8 config

* Bump version 1.1.0 -> 1.1.1

* Add Python inspections and a script for tool evaluation (#26)

* wps-light support (#17)

Add wps-light support

* New flake8 plugins support (#18)

Added support for flake8-broken-line, flake8-string-format, flake8-commas (they are WPS dependencies).
Added support for cohesion.

* Radon support (#19)

Added new inspector: Radon. 
Added maintainability index.

* Requirements upgrade (#21)

Updated versions of dependencies
Added django dictionary support
Fixed tests

* xlsx-run-tool (#24)

Added xlsx_tool_run.py – script to run the tool on multiple code samples stored in xlsx file

* Update version to 1.2.0

* Rename output_format to format

* Fix double quotes

* Fix small issues

* Fix small issues

* Fix double quotes

* Fix double quotes

* Inspectors fix (#39)

* Add origin class for maintainability index
* Add WPS518 to ignore due to collision with C0200 by Pylint

* New category (#38)

* Added a new category INFO, in order not to take into account some issues in the evaluation.

* Fixed trailing commas

* Delete create_directory function

* Fix GitHub actions (#44)

* Use the same environment as in the production dockerfile

* Fix Dockerfiles

* Install some dependencies for TeamCity

* Update build

* Add checks from teamcity

* Update build

* Fix indentation

* Fix PR comments

* Delete init files from resources

* Add init in multi file project

* Fix flake8 tests

* Main upd bugs fix (#74)

* Delete evaluation part
* Fix bugs with detekt, pmd and flake8

* Issues fix (#80)

* Fixed issue #70

* Fixed issue #72: now only spellcheck checks brackets

* Fixed issue #73

* Fixed issue #77

* Fixed issue #78

* Fixed issue #71

* Fixed issue #79

* Fixed issue #81

* Added case 36: unpacking

* Added case 37: wildcard import

* Ignoring WPS347 and F405

* Added cases 36 (unpacking) and 37 (wildcard_import). Also removed W0622 (redefining_builtin)

* Removed W0622 (redefining_builtin)

* Issue #87 fix (#90)

* Fixed issue #87

* Added test

* Fixed issues #91 and #92 (#97)

* Delete xlsx

* Remove openpyxl

* Issues fix (#104)

* Fixed #100

* Fixed #102

* Added some more new words

* Added toplevel

* Update flake8 whitelist

* Recovered accidentally deleted words

Co-authored-by: Vlasov Ilya <55441714+GirZ0n@users.noreply.github.com>
Co-authored-by: Daria Diatlova <dari.diatlova@gmail.com>
Co-authored-by: Nikolay Vyahhi <Nikolay.Vyahhi@stepik.org>
Co-authored-by: Ilya Vlasov <ilyavlasov2011@gmail.com>

Co-authored-by: Nikolay Vyahhi <Nikolay.Vyahhi@stepik.org>
Co-authored-by: Vlasov Ilya <55441714+GirZ0n@users.noreply.github.com>
Co-authored-by: Daria Diatlova <dari.diatlova@gmail.com>
Co-authored-by: Ilya Vlasov <ilyavlasov2011@gmail.com>

vyahhi

added a commit
that referenced
this issue

Sep 22, 2021

* wps-light support (#17)

Add wps-light support

* New flake8 plugins support (#18)

Added support for flake8-broken-line, flake8-string-format, flake8-commas (they are WPS dependencies).
Added support for cohesion.

* Radon support (#19)

Added new inspector: Radon. 
Added maintainability index.

* Requirements upgrade (#21)

Updated versions of dependencies
Added django dictionary support
Fixed tests

* xlsx-run-tool (#24)

Added xlsx_tool_run.py – script to run the tool on multiple code samples stored in xlsx file

* Penalty system (#25)

Add penalty system

* Penalty coefficients update (#28)

* Updated penalty coefficients;
* Added new tests;
* Fixed bug with _get_issue_class_to_influence, which caused the dictionary to get issues that should not be penalized.
* Fixed two cases in test_categorize. There were two identical issues in the list of previously made issues.

* Update version to 1.2.0

* Evaluation/code quality (#29)

* Refactor the tool for evaluation: add multithreading, add a possibility to handle CSV arguments
* Add script to filter solutions by language and drop duplicates
* Add script to distribute grades from unique solutions to all solutions
* Add script to find diffs between two graded dataframes
* Add tests and descriptions

* Rename output_format to format

* Fix double quotes

* Fix small issues

* Fix small issues

* Fix double quotes

* Fix double quotes

* Inspectors fix (#39)

* Add origin class for maintainability index
* Add WPS518 to ignore due to collision with C0200 by Pylint

* New category (#38)

* Added a new category INFO, in order not to take into account some issues in the evaluation.

* Dataset labeling utility (#31)

Added a utility for dataset marking

* resolved merge conflicts

* Fixed trailing commas

* Delete create_directory function

* Delete create_directory function

* Update version

* Graph plotter (#41)

Added a script for plots

* updated whitelist to resolve merge conflicts

* Qodana simulation model (#40)

* Add small dataset preparation block, train, and evaluation module to train and run Roberta-model for solving a multilabel classification task

* Qodana stat (#42)

Add a script to convert the data received by the Qodana into the format of the Hyperstyle tool for
analysis and statistics gathering.

* Delete Path from setup.py

* Change exit code

* Update whitelist

* Inspector statistics (#48)

* Calculate statistics for inspectors for four main categories of issues

* Fix GitHub actions (#44)

* Use the same environment as in the production dockerfile

* Fix Dockerfiles

* Install some dependencies for TeamCity

* Update version in Github Actions

* Reorganize dependencies and update dockerfile

* History script (#47)

* Add script that allows you to generate history based on issues from previous solutions

* Fixed incorrect file name (#51)

* Corrected the name of the dataset labeling script in the README

* Distributed the issue categories (#53)

* Distributed the issue categories

* Qodana imitation model resources (#55)

* Add Qodana imitation model resources

* Small Github Actions config update (#56)

* Update build.yml

* Whitelist for flake8-spellcheck (#57)

* Added whitelist

* PMD update (#59)

* Updated PMD to v6.36.0

* Small fix

* Undo f4ab486

* Checkstyle update (#60)

* Checkstyle update

* Categorization update (#61)

* Updated categorization for PMD and Checkstyle

* New tests and documentation (#63)

* Added tests for functions parsing PMD and Checkstyle output.
* Documented methods related to PMD and Checkstyle.

* Merge main into develop (#65)

* Merge main into develop (#65)

* Script for getting raw issues (#66)

* Added Encoder and Decoder for 'raw' issues

* Added test for RawIssueEncoder and RawIssueDecoder

* Added __init__.py

* Added get_raw_issues.py

* Added __init__.py

* Added to_safe_path flag

* Fixed flake8 issue

* Added test for get_raw_issues.py

* Small fix

* Fixed get_output_path test data

* get_language -> get_language_version

* Added ISSUE_TYPE_TO_CLASS and MEASURABLE_ISSUE_TYPE_TO_MEASURE_NAME

* Fixed PR issue

* Added LanguageVersion.JS

* Added LanguageVersion.JS and LanguageVersion.JAVA_15

* Fixed a bug due to which all cyclomatic complexity issues were ignored

* Added bad cyclomatic complexity test

* Fixed test

* Added LineLenIssue

* Removed unnecessary time column

* Update JS tests

* Added README

* Small fixes in README

* Small fix

* Fixed --allow-info-issues description

* Fixed test

* Fixed test

* Fixed PR issue

Co-authored-by: Anastasiia.Birillo <nbirillo@mail.ru>

* Evaluation for the paper (#69)

* Add evaluation for the paper: student dynamics and statistics abut the tool and the tutor tool

* Fix flake8

* Rename statistics

* statistics -> issues_statistics

* Fixed flake8

* Undo some renaming

Co-authored-by: Ilya Vlasov <ilyavlasov2011@gmail.com>

* Script for extracting statistics from raw issues (#76)

* Fixed get_output_path test data

* Moved __get_total_lines to file_system.py

* Added get_total_code_lines_from_file and get_total_code_lines_from_code

* Added get_raw_issues_statistics

* Renamed main_stats -> freq_stats and other_stats -> ratio_stats

* Small fix

* Added new data folders

* Added tests

* Removed duplicates

* Removed unnecessary line

* Now the script returns only one dataframe

* Fixed tests

* Added new tests

* Added logger and small code refactoring

* Added some more logging

* Fixed test

* Fixed test

* Fixed help message

* Update README.md

* statistics -> issues_statistics

* Fixed flake8

* Added from_value function

* Added comment

* Added get_ratio

* Small refactoring: added get_ratio

* Fixed PR issues

* Small fixes

* Added isnull

* typo fix

* Fixed tests

* Added --log-output and fixed null checks

* Added filemode

* typo fix

* Fixed tests

* Fixed tests

* Survey analysis (#84)

* Add scripts for surveys statistics gathering

* Fix flake8

* Issues fix (#88)

* Fixed issue #73

* Fixed #75

* Small fix

* Small fix

* Sorted the whitelist.txt

* Sorted whitelist.txt

* Fixed tests

* Fixed flake8

* Fixed get_raw_issues script (#86)

* Fixed get_output_path test data

* Moved __get_total_lines to file_system.py

* Added get_total_code_lines_from_file and get_total_code_lines_from_code

* Added get_raw_issues_statistics

* Renamed main_stats -> freq_stats and other_stats -> ratio_stats

* Small fix

* Added new data folders

* Added tests

* Removed duplicates

* Removed unnecessary line

* Now the script returns only one dataframe

* Fixed tests

* Added new tests

* Added logger and small code refactoring

* Added some more logging

* Fixed test

* Fixed test

* Fixed help message

* Update README.md

* Added more logging

* statistics -> issues_statistics

* Fixed flake8

* Added from_value function

* Added comment

* Added get_ratio

* Small refactoring: added get_ratio

* Fixed PR issues

* Small fixes

* Added isnull

* typo fix

* Fixed tests

* Added --log-output and fixed null checks

* Added filemode

* typo fix

* Fixed tests

* Fixed tests

* Code refactoring and bug fixing:
- Added checks for columns 'code' and 'lang' for null
- Now if flake8, pylint or WPS terminates with an error, this is logged
- When creating a log file, all parent folders are created if necessary
- Now the new log file overwrites the old one

* Fixed test

* Added new test

* Replaced None with np.nan

* Fixed test

* Removed unnecessary space

* Corrected dict errors and added types for Dict (#98)

* Develop Branch Commit

* Added Types for Dict

* Added Any to typing

* User dynamics (#95)

* Add scripts for surveys statistics gathering

* Fix flake8

* Add dynamics handlers

* Fix flake8

* Sort whitelist

* Fix evaluation run tool script

* Use to_drop_nan arg

* Fix tests

* Fix PR#95 comments

* Fix tests

* `print_review.py` refactoring (#96)

* Code refactoring:
1) Renamed ReviewResult -> GeneralReviewResult.
2) Added ReviewResult from which GeneralReviewResult and FileReviewResult are now inherited.
3) Put common code when printing GeneralReviewResult in different formats in the convert_review_result_to_json_dict function.
4) Also prepared the code for further addition of difficulty levels.
5) Fixed the test: now the json schema is checked more strictly.

* get_influence_json_dict -> get_influence_on_penalty_json_dict

* Fixed the old test and added a new one

* typo fix

* Renamed file

* Fixed quotes

* Added a new test and refactored the old one

* Added typing

* Update README.md

* Undo Update README.md

* Fixed PR issues

* User dynamics visualization (#101)

* Add scripts for surveys statistics gathering

* Fix flake8

* Add dynamics handlers

* Fix flake8

* Sort whitelist

* Fix evaluation run tool script

* Use to_drop_nan arg

* Fix tests

* Fix PR#95 comments

* Fix tests

* Add visualization

* Fix flake8

* Fix plots

* Fix plots

* Delete print

* Raw issues statisitcs plotter (#99)

* Moved to plotters/

* Added line plot and histogram

* Updated whitelist

* Added plotters

* Added script

* Added the ability to draw horizontal lines when plotting box plot

* Added boxplot

* Fixed flake8 issues

* Update README.md

* create_line_plot -> create_line_chart

* Added examples and fixed small errors

* Fixed imports

* Added sys.path

* Difficulty levels (#103)

* Code refactoring:
1) Renamed ReviewResult -> GeneralReviewResult.
2) Added ReviewResult from which GeneralReviewResult and FileReviewResult are now inherited.
3) Put common code when printing GeneralReviewResult in different formats in the convert_review_result_to_json_dict function.
4) Also prepared the code for further addition of difficulty levels.
5) Fixed the test: now the json schema is checked more strictly.

* get_influence_json_dict -> get_influence_on_penalty_json_dict

* Fixed the old test and added a new one

* typo fix

* Renamed file

* Fixed quotes

* Added a new test and refactored the old one

* Added typing

* Added group_issues_by_difficulty

* Added --group-by-difficulty flag

* Added IssueDifficulty

* Added support for difficulty levels

* Small fix

* Fixed tests

* Added IssueDifficulty

* Added difficulty

* Fixed tests

* Fixed tests

* Replaced literals with constants and added group_by_difficulty

* Small fix

* Fixed test and added a new one

* Update README.md

* Undo Update README.md

* Fixed PR issues

* Added tests

* Added history

* Added new tests and updated old ones

* Update README.md

* Fixed flake8

* Small fixes

* Small fix

* Small fix

* Fixed flake8

* Small fix

* Small fix

* Added logger

* Fixed todo message

* Update traces and count percentage (#105)

* Update traces and count percentage

* Fix spellcheck

* Issues fix (#107)

* Update build.yml

1) actions/checkout@v1 -> actions/checkout@v2.
2) Added git.
3) Added automatic sorting of whitelists.

* Update whitelist.txt

* Sort whitelists (Github Actions)

Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

* Raw issues statistics plotter fix (#108)

* Added Extension.HTML

* Added COLORWAY

* Added new words

* Added create_box_trace and create_scatter_trace

* Added --group-stats and colorway

* Added the ability to show several languages on one graph at once

* Sort whitelists (Github Actions)

* Small code refactoring

* Small code refactoring

* Update README.md

* Small fixes

* Updated examples

Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

* Visualization of raw issues statistics for the paper (#110)

* Added Extension.HTML

* Added COLORWAY

* Added new words

* Added create_box_trace and create_scatter_trace

* Added --group-stats and colorway

* Added the ability to show several languages on one graph at once

* Sort whitelists (Github Actions)

* Small code refactoring

* Small code refactoring

* Update README.md

* Small fixes

* Updated examples

* Added script

* Small code refactoring

* Added README and examples

* Removed width

* Changed width

* Changed width

* Fixed PR issues

Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

* Delete evaluation part (#113)

* Delete evaluation

* Update build

* Fix tests

* Rename: review -> hyperstyle

* Add tests

* Delete functions

* Merged `main` into `develop` (#114)

* Fix GitHub actions (#46)

* Update requirements and dockerfile
* Use Dockerfile in Github Action
* Ignore a part of flake8 issues
* Ignore flake8 inspections
* Separate docker file into two: for prod and for dev
* Delete `
* Fix test_range_of_lines
* Fix pylint and flake8 tests
* Fix pylint tests
* Check styles by flake8
* Fix C408 issue
* Move production Dockerfile
* Fix Dockefile for production
* Set up Eslint in the DockerFile for production
* Delete one case from flake8 tests
* Add pathlib into whitelist
* Delete Path from setup.py
* Ignore pathlib
* Don't count INFO issues
* Fix flake8 tests
* Small fix
* Delete pathlib from the whitelist
* Update docker (#54)
* Use one docker file for prod and dev
* Change base docker image
* Fix requirements-test: delete duplicates, setup versions
* Try to fix dockerfile
* Fix run in subprocess function
* Fix Dockerfile
* Try to fix Dockerfile
* Fix docker image (#58)
* Change eslint installing
* Update build.yaml
* Introduce base docker image and auto-detect eslint path

Co-authored-by: Andrey Balandin <andrvb@gmail.com>
Closes #43, closes #45.

* Add whitelist for flake8-spellcheck (#68)

* Add whitelist for flake8-spellcheck
* Add a test for spellcheck and ignore unnecessary rule
* Fix flake8 config

* Bump version 1.1.0 -> 1.1.1

* Add Python inspections and a script for tool evaluation (#26)

* wps-light support (#17)

Add wps-light support

* New flake8 plugins support (#18)

Added support for flake8-broken-line, flake8-string-format, flake8-commas (they are WPS dependencies).
Added support for cohesion.

* Radon support (#19)

Added new inspector: Radon. 
Added maintainability index.

* Requirements upgrade (#21)

Updated versions of dependencies
Added django dictionary support
Fixed tests

* xlsx-run-tool (#24)

Added xlsx_tool_run.py – script to run the tool on multiple code samples stored in xlsx file

* Update version to 1.2.0

* Rename output_format to format

* Fix double quotes

* Fix small issues

* Fix small issues

* Fix double quotes

* Fix double quotes

* Inspectors fix (#39)

* Add origin class for maintainability index
* Add WPS518 to ignore due to collision with C0200 by Pylint

* New category (#38)

* Added a new category INFO, in order not to take into account some issues in the evaluation.

* Fixed trailing commas

* Delete create_directory function

* Fix GitHub actions (#44)

* Use the same environment as in the production dockerfile

* Fix Dockerfiles

* Install some dependencies for TeamCity

* Update build

* Add checks from teamcity

* Update build

* Fix indentation

* Fix PR comments

* Delete init files from resources

* Add init in multi file project

* Fix flake8 tests

* Main upd bugs fix (#74)

* Delete evaluation part
* Fix bugs with detekt, pmd and flake8

* Issues fix (#80)

* Fixed issue #70

* Fixed issue #72: now only spellcheck checks brackets

* Fixed issue #73

* Fixed issue #77

* Fixed issue #78

* Fixed issue #71

* Fixed issue #79

* Fixed issue #81

* Added case 36: unpacking

* Added case 37: wildcard import

* Ignoring WPS347 and F405

* Added cases 36 (unpacking) and 37 (wildcard_import). Also removed W0622 (redefining_builtin)

* Removed W0622 (redefining_builtin)

* Issue #87 fix (#90)

* Fixed issue #87

* Added test

* Fixed issues #91 and #92 (#97)

* Delete xlsx

* Remove openpyxl

* Issues fix (#104)

* Fixed #100

* Fixed #102

* Added some more new words

* Added toplevel

* Update flake8 whitelist

* Recovered accidentally deleted words

Co-authored-by: Vlasov Ilya <55441714+GirZ0n@users.noreply.github.com>
Co-authored-by: Daria Diatlova <dari.diatlova@gmail.com>
Co-authored-by: Nikolay Vyahhi <Nikolay.Vyahhi@stepik.org>
Co-authored-by: Ilya Vlasov <ilyavlasov2011@gmail.com>

* Fixed typo

* Sort whitelists (Github Actions)

* Fixed tests

* Fixed requirements

* Added numpy

* Removed numpy

* Fixed test

Co-authored-by: Nastya Birillo <anastasia.i.birillo@gmail.com>
Co-authored-by: Nikolay Vyahhi <Nikolay.Vyahhi@stepik.org>
Co-authored-by: Daria Diatlova <dari.diatlova@gmail.com>
Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

* Issues fix (#117)

* Fixed #109

* Fixed #112

* Fixed #116

* Updated `README` (#119)

* Added output examples with --group-by-difficulty

* typo fix

* Delete analysis part (#120)

* Pylint categorization update (#121)

* Added some new words

* Added W0511

* Added WPS428

* Added many exceptions

* Sort whitelists (Github Actions)

* Comments fix

Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

* Detekt update (#123)

* Updated detekt

* Added new words

* Sort whitelists (Github Actions)

Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

* Issue fix (#127)

* Fixed #122

* Sort whitelists (Github Actions)

Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

* Delete evaluation resources

* Delete Intellij and spotbugs inspectors (#131)

* Delete intellij inspector

* Delete spotbugs inspector

* Fix teamcity build

* Delete detekt sources (#132)

* Delete intellij inspector

* Delete spoibugs inspector

* Download Detekt in Dockerfile

* Install curl and unzip

* Fix Dockerfile

* Try to delete detekt sources

* Check env variables

* Try to get env variable

* Use my docker image

* Small code refactoring and also download detekt-jar file

* Use my docker image

* Use my docker image

* Delete springlint inspector (#133)

* Delete intellij inspector

* Delete spoibugs inspector

* Download Detekt in Dockerfile

* Install curl and unzip

* Fix Dockerfile

* Try to delete detekt sources

* Check env variables

* Try to get env variable

* Use my docker image

* Small code refactoring and also download detekt-jar file

* Use my docker image

* Use my docker image

* Delete springlint inspector

* Delete checkstyle sources (#134)

* Delete checkstyle sources

* Fix curl command

* Delete pmd sources (#135)

* Delete PMD sources

* Fix flake8 and echo env variables

* Fix pmd tests

* Delete ses evaluation resources

* Add a guideline about tool installation (#137)

Co-authored-by: Vlasov Ilya <55441714+GirZ0n@users.noreply.github.com>
Co-authored-by: Daria Diatlova <dari.diatlova@gmail.com>
Co-authored-by: Nikolay Vyahhi <Nikolay.Vyahhi@stepik.org>
Co-authored-by: Ilya Vlasov <ilyavlasov2011@gmail.com>
Co-authored-by: Nihal Shetty <80703906+nihalshetty-boop@users.noreply.github.com>
Co-authored-by: GirZ0n <GirZ0n@users.noreply.github.com>

Зарегистрируйтесь для доступа к 15+ бесплатным курсам по программированию с тренажером

Ошибки оформления — синтаксис и линтер

Основы Python

Если программа на Python написана синтаксически некорректно, то интерпретатор выводит на экран соответствующее сообщение. Также он указывает на файл и строчку, где произошла ошибка.

Синтаксическая ошибка возникает в том случае, когда код записали с нарушением грамматических правил. В естественных языках грамматика важна, но текст с ошибками обычно можно понять и прочитать. В программировании все строго. Мельчайшее нарушение — и программа даже не запустится. Примером может быть забытая ;, неправильно расставленные скобки и другие детали.

Вот пример кода с синтаксической ошибкой:

print('Hodor)

Если запустить код выше, то мы увидим следующее сообщение:

$ python index.py
File "index.py", line 1
print('Hodor)
^
SyntaxError: EOL while scanning string literal

С одной стороны, ошибки синтаксиса — самые простые, потому что они связаны с грамматическими правилами написания кода, а не со смыслом кода. Их легко исправить: нужно лишь найти нарушение в записи. С другой стороны, интерпретатор не всегда может четко указать на это нарушение. Поэтому бывает, что забытую скобку нужно поставить не туда, куда указывает сообщение об ошибке.

Ошибки линтера

Мы уже научились писать простые программы, и поэтому можно немного поговорить о том, как писать их правильно.

Код нужно оформлять определенным образом, чтобы он был понятным и простым в поддержке. Существуют специальные наборы правил, которые описывают различные аспекты написания кода — их называют стандартами кодирования. В Python стандарт один — PEP8. Он отвечает практически на все вопросы о том, как оформлять ту или иную часть кода. Этот документ содержит все правила, которых нужно придерживаться. Новичкам мы советуем завести привычку заглядывать в стандарт PEP8 и писать код по нему.

Сегодня не нужно помнить все правила из стандарта, потому что существуют специальные программы, которые проверяют код автоматически и сообщают о нарушениях. Такие программы называются линтерами. Они проверяют код на соответствие стандартам. В Python их достаточно много, и наиболее популярный из них — flake8.

Взгляните на пример:

result = 1+ 3

Линтер будет ругаться на нарушение правила: E225 missing whitespace around operator. По стандарту, все операторы всегда должны отделяться пробелами от операндов.

Выше мы увидели правило E225 — это одно из большого количества правил. Другие правила описывают отступы, названия, скобки, математические операции, длину строчек и множество иных аспектов. Каждое отдельное правило кажется неважным и мелким, но вместе они составляют основу хорошего кода. Список всех правил flake8 доступен в этой документации.

Вы уже знакомы с линтером, потому что в практических заданиях платформа Хекслета проверяет ваш код с помощью него. Скоро вы начнете использовать его и за пределами Хекслета, когда будете реализовывать учебные проекты. Вы настроите линтер, и он будет проверять код уже в реальной разработке и сообщать вам о нарушениях.


Аватары экспертов Хекслета

Остались вопросы? Задайте их в разделе «Обсуждение»

Вам ответят команда поддержки Хекслета или другие студенты.

Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.

Синтаксис обработки исключений

Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.

Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError, которые не стоит пытаться обработать.

Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.

Ошибки могут быть разных видов:

  • Синтаксические
  • Недостаточно памяти
  • Ошибки рекурсии
  • Исключения

Разберем их по очереди.

Синтаксические ошибки (SyntaxError)

Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.

Рассмотрим на примере.

a = 8
b = 10
c = a b
File "", line 3
c = a b
^
SyntaxError: invalid syntax

Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.

Недостаточно памяти (OutofMemoryError)

Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory. Она может появиться по нескольким причинам:

  • Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
  • Загрузка файла большого размера;
  • Запуск модели машинного обучения/глубокого обучения и много другое;

Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError, позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.

Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()), не факт, что все процессы восстановятся — в некоторых случаях MemoryError приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.

Ошибка рекурсии (RecursionError)

Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.

Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.

Чтобы воспроизвести эту ошибку, определим функцию recursion, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.

def recursion():
return recursion()
recursion()
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
in 
----> 1 recursion()
in recursion()
1 def recursion():
----> 2     return recursion()
... last 1 frames repeated, from the frame below ...
in recursion()
1 def recursion():
----> 2     return recursion()
RecursionError: maximum recursion depth exceeded

Ошибка отступа (IndentationError)

Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.

Пример:

for i in range(10):
print('Привет Мир!')
  File "", line 2
print('Привет Мир!')
^
IndentationError: expected an indented block

Исключения

Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.

Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:

Ошибка типа (TypeError)

a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
in 
1 a = 2
2 b = 'PythonRu'
----> 3 a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Ошибка деления на ноль (ZeroDivisionError)

10 / 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
in 
----> 1 10 / 0
ZeroDivisionError: division by zero

Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError и ZeroDivisionError. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.

Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.

Теперь рассмотрим встроенные исключения Python.

Встроенные исключения

BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
|    +-- FloatingPointError
|    +-- OverflowError
|    +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
|    +-- ModuleNotFoundError
+-- LookupError
|    +-- IndexError
|    +-- KeyError
+-- MemoryError
+-- NameError
|    +-- UnboundLocalError
+-- OSError
|    +-- BlockingIOError
|    +-- ChildProcessError
|    +-- ConnectionError
|    |    +-- BrokenPipeError
|    |    +-- ConnectionAbortedError
|    |    +-- ConnectionRefusedError
|    |    +-- ConnectionResetError
|    +-- FileExistsError
|    +-- FileNotFoundError
|    +-- InterruptedError
|    +-- IsADirectoryError
|    +-- NotADirectoryError
|    +-- PermissionError
|    +-- ProcessLookupError
|    +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
|    +-- NotImplementedError
|    +-- RecursionError
+-- SyntaxError
|    +-- IndentationError
|         +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
|    +-- UnicodeError
|         +-- UnicodeDecodeError
|         +-- UnicodeEncodeError
|         +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning

Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.

  • Try: он запускает блок кода, в котором ожидается ошибка.
  • Except: здесь определяется тип исключения, который ожидается в блоке try (встроенный или созданный).
  • Else: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).
  • Finally: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.

В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.

Ошибка прерывания с клавиатуры (KeyboardInterrupt)

Исключение KeyboardInterrupt вызывается при попытке остановить программу с помощью сочетания Ctrl + C или Ctrl + Z в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.

В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt. Теперь обработаем исключение KeyboardInterrupt.

try:
inp = input()
print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
print('Исключение KeyboardInterrupt')
else:
print('Исключений не произошло')
Исключение KeyboardInterrupt

Стандартные ошибки (StandardError)

Рассмотрим некоторые базовые ошибки в программировании.

Арифметические ошибки (ArithmeticError)

  • Ошибка деления на ноль (Zero Division);
  • Ошибка переполнения (OverFlow);
  • Ошибка плавающей точки (Floating Point);

Все перечисленные выше исключения относятся к классу Arithmetic и вызываются при ошибках в арифметических операциях.

Деление на ноль (ZeroDivisionError)

Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.

try:  
a = 100 / 0
print(a)
except ZeroDivisionError:  
print("Исключение ZeroDivisionError." )
else:  
print("Успех, нет ошибок!")
Исключение ZeroDivisionError.

Переполнение (OverflowError)

Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.

try:  
import math
print(math.exp(1000))
except OverflowError:  
print("Исключение OverFlow.")
else:  
print("Успех, нет ошибок!")
Исключение OverFlow.

Ошибка утверждения (AssertionError)

Когда инструкция утверждения не верна, вызывается ошибка утверждения.

Рассмотрим пример. Предположим, есть две переменные: a и b. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert, что приведет к вызову исключения Assertion в том случае, если выражение будет ложным.

try:  
a = 100
b = "PythonRu"
assert a == b
except AssertionError:  
print("Исключение AssertionError.")
else:  
print("Успех, нет ошибок!")
Исключение AssertionError.

Ошибка атрибута (AttributeError)

При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes нет атрибута с именем attribute.

class Attributes(obj):
a = 2
print(a)
try:
obj = Attributes()
print(obj.attribute)
except AttributeError:
print("Исключение AttributeError.")
2
Исключение AttributeError.

Ошибка импорта (ModuleNotFoundError)

Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.

import nibabel
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
in 
----> 1 import nibabel
ModuleNotFoundError: No module named 'nibabel'

Ошибка поиска (LookupError)

LockupError выступает базовым классом для исключений, которые происходят, когда key или index используются для связывания или последовательность списка/словаря неверна или не существует.

Здесь есть два вида исключений:

  • Ошибка индекса (IndexError);
  • Ошибка ключа (KeyError);

Ошибка ключа

Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError.

try:  
a = {1:'a', 2:'b', 3:'c'}  
print(a[4])  
except LookupError:  
print("Исключение KeyError.")
else:  
print("Успех, нет ошибок!")
Исключение KeyError.

Ошибка индекса

Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).

try:
a = ['a', 'b', 'c']  
print(a[4])  
except LookupError:  
print("Исключение IndexError, индекс списка вне диапазона.")
else:  
print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.

Ошибка памяти (MemoryError)

Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.

Ошибка имени (NameError)

Ошибка имени возникает, когда локальное или глобальное имя не находится.

В следующем примере переменная ans не определена. Результатом будет ошибка NameError.

try:
print(ans)
except NameError:  
print("NameError: переменная 'ans' не определена")
else:  
print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена

Ошибка выполнения (Runtime Error)

Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.

class BaseClass(object):
"""Опередляем класс"""
def __init__(self):
super(BaseClass, self).__init__()
def do_something(self):
# функция ничего не делает
raise NotImplementedError(self.__class__.__name__ + '.do_something')
class SubClass(BaseClass):
"""Реализует функцию"""
def do_something(self):
# действительно что-то делает
print(self.__class__.__name__ + ' что-то делает!')
SubClass().do_something()
BaseClass().do_something()
SubClass что-то делает!
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
in 
14
15 SubClass().do_something()
---> 16 BaseClass().do_something()
in do_something(self)
5     def do_something(self):
6         # функция ничего не делает
----> 7         raise NotImplementedError(self.__class__.__name__ + '.do_something')
8
9 class SubClass(BaseClass):
NotImplementedError: BaseClass.do_something

Ошибка типа (TypeError)

Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.

В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.

try:
a = 5
b = "PythonRu"
c = a + b
except TypeError:
print('Исключение TypeError')
else:
print('Успех, нет ошибок!')
Исключение TypeError

Ошибка значения (ValueError)

Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.

В этом примере встроенная операция float получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.

try:
print(float('PythonRu'))
except ValueError:
print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'

Пользовательские исключения в Python

В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.

Это можно сделать, создав новый класс, который будет наследовать из класса Exception в Python.

class UnAcceptedValueError(Exception):   
def __init__(self, data):    
self.data = data
def __str__(self):
return repr(self.data)
Total_Marks = int(input("Введите общее количество баллов: "))
try:
Num_of_Sections = int(input("Введите количество разделов: "))
if(Num_of_Sections < 1):
raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
print("Полученная ошибка:", e.data)
Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1

В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.

Недостатки обработки исключений в Python

У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.

Дальше пример, где модуль Python timeit используется для проверки времени исполнения 2 разных инструкций. В stmt1 для обработки ZeroDivisionError используется try-except, а в stmt2if. Затем они выполняются 10000 раз с переменной a=0. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1 с обработкой исключений занимает больше времени чем stmt2, который просто проверяет значение и не делает ничего, если условие не выполнено.

Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.

import timeit
setup="a=0"
stmt1 = '''
try:
b=10/a
except ZeroDivisionError:
pass'''
stmt2 = '''
if a!=0:
b=10/a'''
print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))
time= 0.003897680000136461
time= 0.0002797570000439009

Выводы!

Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.

Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try выискивает исключения, а except их обрабатывает.

Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.

В этой статье вы узнаете о типах ошибок, которые вызываются интерпретатором, если что то в вашей программе идет не так. Все типы ошибок в Python можно разделить на два класса.

  1. Синтаксические ошибки
  2. Логические ошибки

При возникновении, какой либо ошибки, которую программа не может обработать, вызывается тип ошибки указывающая на проблему. Избежать эти ошибки поможет нам обработка исключений в Python.

Такого рода ошибка возникает при неправильном использовании структуры языка. Рассмотрим пример такой ошибки:

for i in range(0,10)

print(i)

Результат:

SyntaxError: invalid syntax

Естественно, мы нарушили структура языка, а именно не поставили двоеточие в конце цикла for.

Логические ошибки в Python

Логические ошибка возникают, если у вас нет синтаксической ошибки. То есть интерпретатор Python, сначала анализирует ваш код на предмет наличия синтаксических ошибок. типы логических ошибок бывают разными, например:

  1. Если мы пытаемся открыть файл для чтения которого не существует, то словим ошибку FileNotFoundError
  2. Попытаемся разделить на ноль, получим ZeroDivisionError
  3. Попытаемся импортировать модуль, которого не существует, получим ImportError

И это только малая часть, Python не разрешит нам уничтожить мир, разделив число на ноль=).  Каждый раз, когда Python видит необработанную ошибку, он пишет нам, что произошла ошибка по той или иной причине. Рассмотрим пример обработки ошибки.

100 / 0

Результат:

Traceback (most recent call last):

File "<string>", line 301, in runcode

File "<interactive input>", line 1, in <module>

ZeroDivisionError: division by zero

&nbsp;

open("filenot.txt")

Результат:

Traceback (most recent call last):

File "<string>", line 301, in runcode

File "<interactive input>", line 1, in <module>

FileNotFoundError: [Errno 2]

No such file or directory: 'filenot.txt'

Исключения Python

В Python есть довольно большое количество встроенных исключений, которые вызываются при возникновении соответствующих им ошибок. Ниже представлена таблица со списками исключений.

Исключения Причина
AssertionError Вызывается при сбое assert оператора.
AttributeError Возникает, когда не удается присвоить атрибут или ссылку.
EOFError Вызывается, когда input()функция достигает состояния конца файла.
FloatingPointError Вызывается при сбое операции с числами имеющими десятичное значение.
GeneratorExit при close()вызове метода генератора.
ImportError Вызывается, когда импортированный модуль не найден.
IndexError когда индекс последовательности находится вне диапазона.
KeyError Возникает, когда ключ не найден в словаре.
KeyboardInterrupt При нажатии на клавишу прерывания
MemoryError Вызывается, когда в операции заканчивается память.
NameError Вызывается, когда переменная не найдена в локальной или глобальной области видимости.
NotImplementedError При работе с абстрактными методами
OSError Когда программа вызывает связанную с ОС ошибку
OverflowError Возникает, когда результат арифметической операции слишком велик
ReferenceError Вызывается, когда слабый ссылочный прокси-сервер используется для доступа к собранному мусором референту.
RuntimeError Возникает, когда ошибка не попадает ни под какую другую категорию.
StopIteration Вызывается функцией next(), которая говорит, что больше нет элементов
SyntaxError Синтаксическая ошибка
IndentationError При нарушении отступа
TabError При нарушении отступов
SystemError Ошибка с интепретатором
SystemExit Функция sys.exit()
TypeError Ошибка с типами данных
UnboundLocalError Вызывается, когда делается ссылка на локальную переменную в функции или методе, но ни одно значение не было привязано к этой переменной.
UnicodeError Ошибка кодировки
UnicodeEncodeError Ошибка кодировки
UnicodeDecodeError Ошибка декодирования
UnicodeTranslateError Ошибка кодировки
ValueError Когда функция получает аргумент с неправильным значением
ZeroDivisionError При делении на ноль

В Python, мы так же сами можем создать свои исключения, поэтому внимательно читайте документацию сторонних модулей, которые вы используете. Подробнее об этом в разделе пользовательские исключения Python.

В одной из предыдущих статей, мы с вами уже затрагивали тему обработки ошибок, с помощью try…except…finally, подробнее о них, в статье обработка исключений

michaelaquilina / flake8-spellcheck
Goto Github
PK

View Code? Open in Web Editor
NEW

71.0
4.0
28.0
1.37 MB

❄️ Spellcheck variables, classnames, comments, docstrings etc

License: MIT License

Python 98.49%

Shell 1.51%

python

linter

spellcheck

flake8-spellcheck’s Introduction

=================
Flake8 Spellcheck
=================

|CircleCI| |Black| |PyPi|

Flake8 Plugin that spellchecks variables, functions, classes and other bits of your python code.

You can whitelist words that are specific to your project simply by adding them to ``whitelist.txt``
in the root of your project directory. Each word you add  should be separated by a newline.

Spelling is assumed to be in en_US.

This plugin supports python 3.8+

Codes
-----

* SC100 - Spelling error in comments
* SC200 - Spelling error in name (e.g. variable, function, class)

Enable Django support
---------------------

You can enable support for a Django dictionary by adding the following to your
flake8 configuration (e.g. your ``.flake8`` file):

.. code-block:: ini

    [flake8]
    dictionaries = en_US,python,technical,django

Enable pandas support
---------------------

You can enable support for pandas DataFrames by adding the following to your
flake8 configuration (e.g. your ``.flake8`` file):

.. code-block:: ini

    [flake8]
    dictionaries = en_US,python,technical,pandas

Specify Targets
---------------

Both ``comments`` and ``names`` (variable names, function names...) are spellchecked by default.
You can specify what targets to spellcheck in your flake8 configuration (e.g. in your ``.flake8`` file):

.. code-block:: ini

   [flake8]
   spellcheck-targets = comments

The above configuration would only spellcheck comments

.. code-block:: ini

   [flake8]
   spellcheck-targets = names

The above configuration would only spellcheck names

Ignore Rules
------------

.. code-block:: ini

   [flake8]
   ignore = SC100, SC200

Contributing
------------

If you have found word(s) which are listed as a spelling error but are actually correct terms used
in python or in technical implementations (e.g. http), then you can very easily contribute by
adding those word(s) to the appropriate dictionaries:

* `python dictionary <flake8_spellcheck/python.txt>`_
* `technical dictionary <flake8_spellcheck/technical.txt>`_
* `django dictionary <flake8_spellcheck/django.txt>`_
* `pandas dictionary <flake8_spellcheck/pandas.txt>`_

Before you submit a PR, it is recommended to run ``check-sorting.sh`` in the root of this repository,
to verify that all the dictionary files are still sorted correctly. Sorting is enforced by CI, so
you'll need to make sure the files are sorted before your PR can be merged.

Development
-----------

* Install `poetry <https://github.com/python-poetry>`__
* Run ``poetry install``
* Run ``poetry run pre-commit install --install-hooks``

You can run tests with ``poetry run pytest``.


.. |CircleCI| image:: https://circleci.com/gh/MichaelAquilina/flake8-spellcheck.svg?style=svg
   :target: https://circleci.com/gh/MichaelAquilina/flake8-spellcheck

.. |PyPi| image:: https://badge.fury.io/py/flake8-spellcheck.svg
   :target: https://badge.fury.io/py/flake8-spellcheck

.. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
   :target: https://github.com/psf/black

flake8-spellcheck’s People

flake8-spellcheck’s Issues

Support docstrings

Parse «whitelist» option from config

Empty comment causes exception

Running this plugin on code with comments that are just # noqa gives me:

  File "/usr/local/lib/python3.8/site-packages/flake8_spellcheck/__init__.py", line 170, in _parse_token
    and token_info.string.lstrip("#").split()[0] != "noqa:"
IndexError: list index out of range

Release new version for 0.25.0

I am trying to use the pandas.txt dictionary but I just realised that it hasn’t been released yet to PyPI. Can we get a new release for this please?

Can’t work with python2.7

My Python version is 2.7, flake8 version is 3.5.0 (flake8-future-import: 0.4.5, mccabe: 0.6.1, pycodestyle: 2.3.1, pyflakes: 1.6.0) CPython 2.7.17 on Darwin
after i install flake8-spellcheck-0.9.1, it can’t work anymore.

(mywork) loganlideMacBook-Pro:test $ flake8 test.py Traceback (most recent call last): File "/Users/timeless/.vitualenvs/mywork/bin/flake8", line 8, in <module> sys.exit(main()) File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/main/cli.py", line 16, in main app.run(argv) File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/main/application.py", line 396, in run self._run(argv) File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/main/application.py", line 383, in _run self.initialize(argv) File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/main/application.py", line 365, in initialize self.find_plugins() File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/main/application.py", line 191, in find_plugins self.check_plugins.load_plugins() File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/plugins/manager.py", line 423, in load_plugins plugins = list(self.manager.map(load_plugin)) File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/plugins/manager.py", line 311, in map yield func(self.plugins[name], *args, **kwargs) File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/plugins/manager.py", line 421, in load_plugin return plugin.load_plugin() File "/Users/timeless/.vitualenvs/mywork/lib/python2.7/site-packages/flake8/plugins/manager.py", line 186, in load_plugin raise failed_to_load flake8.exceptions.FailedToLoadPlugin: Flake8 failed to load plugin "SC" due to invalid syntax (__init__.py, line 153).

Can you help me solve this problem?
Thank you!

Words that have numbers on the end fail.

I have a similar issue to #61 which currently makes the plugin unusable. The below happens despite using all of the dictionaries.

data.py:28:41: SC200 Possibly misspelt word: 'dict1'
data.py:58:36: SC200 Possibly misspelt word: 'file1'

An approach that notices the trailing numbers, checks if the word is valid and then allows the whole word to pass seems straight forward and unlikely to introduce failures. xyz1 is not a valid word. file1 clear is «file one».

I am happy to post a PR if that approach is acceptable.

I am using 0.25.0 installed from pypi.

Is there a way to have the `whitelist.txt` used for all subdirectories?

If I put a whitelist.txt in the root of the project, then change to a subdir and run flake8, then the root project’s whitelist.txt is not honored.

Is there a way to enable a single whitelist.txt for a project?

Segmentation error in comments

First of all, I like the plug-ins you developed.
But I found:

SC100 Possibly misspelt word: »attempts»
SC100 Possibly misspelt word: ‘login»
SC100 Possibly misspelt word: ‘

The reason for these results is that I temporarily commented out some normal Python statements.
Just like:

logger.debug(‘Incrementing login attempts’, extra={‘data’: {’email’: email, ‘ip_address’: ip_address}})

Could you fix this bug?
Thank you!

add possibility to specify white list addition within python files

Hello
thank you for this great package. It sometimes feels not very convenient to add all word in a single whitelist file and
we may want to ignore some world only in some files.
It would be great if we could specify a per-file whitelist as well through a comment in each python file
similarly, to the «ignore» option in the cSpell visual studio plugin

It’s a segmentation error when dealing with quotation marks

In dictionary, class’s -> classs
Cause typo ‘classs’ pass check.
Please fix this problem when you have time :)

# __init__.py lines of 118 # Hacky way of getting dictionary with symbols stripped self.no_symbols = set(w.replace("'", "") for w in self.words)

Spellcheck error for common python modules

I do get an error for common python modules and their functions.

Example:

import sqlite3
from shutil import copyfile

generate text file with all unkown words

Thank you very much for this great plugin.
it would be great to have an option to dump all the unknown words to a single text file that can then be edited to update the whitelist file

IndexError caused by lines containing only «#» characters

Hi Michael,

I’ve found that an IndexError exception is raised, at line 173 of the flake8_spellcheck/__init__.py file, whenever a commend consisting only of «#» characters is found (e.g., «#######»). This issue is similar to issue #34.

I replaced line 171 with

and token_info.string.lstrip("#").strip() != ''

and it seems to have solved this issue while being compatible with your solution to #34.

I’ll submit a merge request soon so you can test it further and see if it can be included in some future release.

Cheers,
Paulo.

Inclusive renaming for —whitelist and whitelist.txt

As the spellcheck «whitelist.txt» file is generally a dictionary of allowed terminology within the codebase, could allowdict.txt, allowterm.txt or allowlist.txt be used instead of whitelist naming?

For non-breaking changes, whitelist.txt could remain as a backwards-compatible default and be used in the code but not in the documentation. A double-default would be required to fall back to the older version. Terminology used within the project documentation could be the renamed file.

If this is something the projects authors are interested in I could take a crack at making this change.

In either case, as an improvement to the documentation, the readme could note the way to change the default whitelist.txt file using —whitelist parameters.

Feature: specify multiple additional allowlist

Eg, to split between more generic lists (that can be reused) and more project-specific lists.

Improvements in word splitting

Just wondering if there is any reason why camel case words aren’t always split when checking spelling.

In particular if there are camelcase words in a comment then they flag with SC100
But also if there is some terribly named variable like TestData_apple then SC200 will flag ‘TestData’ as a spelling error whereas I would have expected ‘Test’ and ‘Data’ to have been checked separately by flake8-spellcheck

The other word splitting choice I am curious about is «words» that have digits in them. I have an electronics library with a fairly ridiculous whitelist containing things like 100n, 10m, 10n5, 1n, 1k, 200m, 250V, 250VAC, 33R4, 470R, 6V3, etc, etc which is a bit cumbersome.

Edit: Another odd word splitting thing.
If I have pd.Timestamp('2017-06-01T12')) then everything is fine, however if I have # pd.Timestamp('2017-06-01T12')) then I get a misspelt word of ‘2017. I understand single quotes are really apostrophes (I have argued within my team for double quoted strings with no luck) so splitting up words on single quotes isn’t possible, but it is a bit annoying having to put things like ‘2017 in my whitelist.

Whitelist names from the standard lib?

Hi, thank you so much for this plugin, I’m looking forward to have only existing words as names inside the code (and have an automatic way of forbidding abbreviations).

Currently however, it is nearly impossible to properly use it, at it throws errors at many of the standard library or third party names, e.g. pathlib, joinpath, asdict not mentioning names defined in packages such as numpy, opencv, pillow.

Would there be a way to spellcheck only variables defined in the module to check? Or at least provide a way to whitelist the complete standard library…

Thanks in advance!

Don’t check noqa comments

The comment # noqa: followed by a Flake8 error is used for ignoring a specific error on a specific line. Comments beginning with # noqa: should be ignored so I don’t have to add every noqa pragma by hand to my allow list.

Black version is no longer specified anywhere.

The switch to poetry dropped the locking to a specific version of black. The target_version in pyproject.toml says «py37».

Pre-commit addition is heavy

I tried to update to the new main this morning.
poetry run pre-commit install --install-hooks fails for me

[INFO] This may take a few minutes...
An unexpected error has occurred: CalledProcessError: command: ('go', 'install', './...')
return code: 1
expected return code: 0
stdout:
    Executable `go` not found

Why do I need go? What is that giving the project that is helpful?

README: installation steps are missing

Please add pip install flake8-spellcheck so people can copy/paste easily the command

Allow whitelist in pyproject.toml

Would it be possible to support adding the whitelist as a configuration option inside pyproject.toml as an alternative to the whitelist.txt file?

I don’t want to adopt this plugin if it means increasing the amount of config files in my project.

Ignore punctuation?

Is there a way to ignore punctuation?

If I have a line in a python file like this:

# Tip: Can run try it out using: 'pyinfra @docker/python python.py'

It complains about these:

./examples/python.py:3:1: SC100 Possibly misspelt word: ''pyinfra'
./examples/python.py:3:8: SC100 Possibly misspelt word: 'py''

Note the trailing quote on each.

hasattr is missing in python.txt

Recognise Python’s magic methods

Python code which defines «magic methods» (a.k.a. «dunder methods») can lead to a lot of errors from flake8-spellcheck

For example, each of the following methods will raise errors, because eq, gt, radd, etc are not valid English words

class Fred:
    def __eq__(self, other): pass
    def __gt__(self, other): pass
    def __radd__(self, other): pass
    def __aiter__(self, other): pass
    def __matmul__(self, other): pass
    def __instancecheck__(self, other): pass

the code for ignoring noqa still has issues

while fighting with mypy, i discovered that the idiomatic way to disable mypy and flake8 for a line is # type: ignore # noqa: SC100, which causes an issue since the comment only recognizes comments that start with «noqa:»

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

import cmath


def sqrt():
    try:
        num = int(input("Enter the number : "))
        if num >= 0:
            main(num)
        else:
            complex_num(num)
    except:
        print("OOPS..!!Something went wrong, try again")
        sqrt()
    return


def main(num):
    square_root = num**(1/2)
    print("The square Root of ", num, " is ", square_root)
    return


def complex_num(num):
    ans = cmath.sqrt(num)
    print("The Square root if ", num, " is ", ans)
    return

sqrt()

Предыдущие исправят проблемы PEP8. После вашего импорта вам нужно иметь 2 новые строки перед началом кода. Кроме того, между каждым def foo() вам также должно быть 2.

В вашем случае у вас было 0 после импорта, и у вас была 1 новая линия между каждой функцией. Часть PEP8 вам нужно иметь новую строку после окончания вашего кода. К сожалению, я не знаю, как это показать, когда я вставляю код здесь.

Обратите внимание на именование, это часть PEP8. Я изменил complex на complex_num, чтобы предотвратить путаницу со встроенным complex.

В конце концов, они только предупреждают, их можно игнорировать при необходимости.

Понравилась статья? Поделить с друзьями:
  • Sby motor ошибка
  • Sbrfcom dll ошибка 99
  • Sbis3plugin exe ошибка приложения
  • Sc startservice ошибка 1058
  • Sbersign ошибка загрузки ключа