Skip to content

Conversation

@kizrum
Copy link

@kizrum kizrum commented Dec 13, 2018

pycalc

pycalc
@kizrum kizrum changed the title My commit [WIP] Nick Dubovik Dec 13, 2018
import argparse
import sys

OPERATORS = {'+': (2, operator.add), '-': (2, operator.sub),

Choose a reason for hiding this comment

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

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

'!=': (1, operator.ne), '>=': (1, operator.ge),
'==': (1, operator.eq), '?': (4, operator.neg)}

STLO = {'True': True, 'False': False}

Choose a reason for hiding this comment

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

  • название некоторых глобальных переменных не совсем понятны. Что означает STLO?
  • переменная FUNCTION по факту является не функцией, а маппингом нескольких функций на их названия. Лучше будет этой переменной название FUNCTIONS_MAPPING
  • символы всех цифр и букв можно найти в модуле string
import string

string.ascii_letters                                                                                                               
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.digits                                                                                                                      
'0123456789'

STOP = '<+->/!=*^%'

version = "1.2.1"
global module

Choose a reason for hiding this comment

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

Зачем в глоабльной секции кода использовать ключевое слово global?

metavar='MODULE')
parser.add_argument('string', type=str, default='', help='Expression string to evaluate',
metavar='EXPRESSION')
# subparsers = parser.add_subparsers (dest = 'command',

Choose a reason for hiding this comment

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

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

def check_module(module_name):
# Checks if the module can be imported without actually importing it
module_spec = importlib.util.find_spec(module_name)
if module_spec is None:

Choose a reason for hiding this comment

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

В данном случае это бессмысленная конструкция. if можно опустить и просто написать вот так:

return importlib.util.find_spec(module_name)



def check_module(module_name):
# Checks if the module can be imported without actually importing it

Choose a reason for hiding this comment

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

документацию к функциям, классам и т.д. обычно оборачивают в тройные кавычки:

def check_module(module_name):
    """Checks if the module can be imported without actually importing it"""

return module


def sum(module, sst):

Choose a reason for hiding this comment

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

Перекрытие built-in функции sum. Лучше для этой функции придумать более конкретное имя, как минимум не перекрывающее встроенные в Python функции.


def sum(module, sst):
# Reading and token allocation--------------------------------------------------------------------
def parse(sst):

Choose a reason for hiding this comment

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

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

  • pr
  • lev
  • j
  • s
  • sst
  • n
  • i
  • cc
    и так далее
    Желательно, чтобы названия переменных несли какой-то смысл и помогали программисту понимать код.

if sst[j - 1] in '/*%^><=' and sst[j + 1] in '/*%^><=':
raise Exception('Пробел между знаками')
if sst[j - 1] in STNUMBER and sst[j + 1] in STNUMBER:
raise Exception('Пробел')

Choose a reason for hiding this comment

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

Лучше использовать английский язык для текста ошибки (как минимум лучше не использовать два разных языка).

if pr != lev:
raise Exception('Unequal number of brackets')

# conversion to Polish notation------------------------------------------------------------------------------

Choose a reason for hiding this comment

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

Странный комментарий, который не понятно к чему относится и не понятно, что он должен пояснить.

description='A program to calculate complex mathematical expressions with support for custom libraries.',
scripts={"pycalc.py"},
packages=find_packages(),
entry_points={'console_scripts': ['pycalc=pycalc.__main__']}, install_requires=['numpy']

Choose a reason for hiding this comment

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

numpy ???
Зачем в данном решении нужен numpy? :D

Copy link

@AlexeiBuzuma AlexeiBuzuma left a comment

Choose a reason for hiding this comment

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

  • Есть большое количество проблем с именованием переменных.
  • Нужно сделать декомпозицию кода, так как функции очень большие и разобраться в них очень-очень сложно.

@PythonAndGoCommunity PythonAndGoCommunity added the duplicate This issue or pull request already exists label Jan 31, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Code freeze duplicate This issue or pull request already exists

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants