Python variables naming convention

2019-06-16 04:33发布

So I am trying to switch to PEP8 notation (from a rather personal CamelCase notation) and I was wondering how you guys are tackling the cases where existing functions/variables would be overwritten?

e.g. having something like:

open, high, low, close, sum = row

would already overwrite the "open" and "sum" functions. First, if I wouldn't use a good IDE, I wouldn't even notice that I've just overwritten important basic functions. Second, how would you name the variables instead? In this example I would have used apps hungarian and wouldn't have encountered any potential problem at all.

Thanks!

标签: python pep8
5条回答
你好瞎i
2楼-- · 2019-06-16 04:58

If they are all values from the same domain, you can use a dictionary:

params = ('open', 'high', 'low', 'close', 'sum') # defined once

val = dict(zip(params, row)) # for each row

# val == {'open': 12, 'high': 34, 'low': 56, 'close': 78, 'sum': 90}

Then you can access them directly: val['open']. You can iterate over them val.iteritems() and so on.

查看更多
迷人小祖宗
3楼-- · 2019-06-16 05:03

I would use open_ and sum_.

查看更多
霸刀☆藐视天下
4楼-- · 2019-06-16 05:11

Pep8 recommends using trailing underscore, however there is also mentioned that in possible cases using synonym word for the variable would be better idea.

查看更多
地球回转人心会变
5楼-- · 2019-06-16 05:14

Why not just pick non-conflicting names? Such as opening_price, closing_price and total if that's what they represent. While it's possible to qualify the namespace as in the other replies, surely that shouldn't be needed for local variables. Whatever language you program in it's your job to know the reserved words; there aren't that many of them.

查看更多
混吃等死
6楼-- · 2019-06-16 05:17

In this particular case, I'd use a namedtuple. This would turn those names into qualified ones (data.open, data.low, etc.).

from collections import namedtuple
Data = namedtuple('Data', ['open', 'high', 'low' 'close', 'sum'])

data = Data(*row)

This would eliminate the prospect of name clashes with built-in functions, and likely improve the overall readability along the way.

查看更多
登录 后发表回答