📜 ⬆️ ⬇️

Python-way. Bug work


Good day to all! The New Year holidays are over, everyone is well rested. However, even on holidays, work sometimes appears. I, for example, had a chance to delve into someone else's code in Python. The code is good, remarkably documented, but during the reading the feeling that the author read the Python docks and ported the code from a C-like language did not leave. This inspired me to write an article indicating the errors that inevitably arise when switching to Python from C-like languages.

The article is useful to those who recently writes in this language, as well as for those who write small scripts on it, without bothering about the details.

Iteration through the lists


for i in range(len(a)):
    print "  %d   %s" % (i, a[i])

, : , a. xrange, . , enumerate.

for i, item in enumerate(a):
    print "  %d   %s" % (i, item)

enumerate(a) , (<>, <>). .

, . . , , , bool(a). : , bool(a) True, list(a) .


«» : , , , JS (myobject.myelement), :

class mydict(dict):
    def __getattr__(self, key):
        return self[key]
    def __setattr__(self, key, value)
        self[key] = value

.

a = mydict(no = "way", bad = "code")
print a.no
#  "way"


! :

a.update({1:"one", 2:"two"})
a.1
#!      


, , , , , :

def __getattr__(self, key):
    try:
        return self.key
    except:
        return self[key]

, , : self.key self.__getattr__(key).

, .


.
.

def formatName(name):
    if len(name)<40:
        if " " in name:
            if name[0]!="?":
                return name.split(" ")
    return False
	
def formatName(name):
    if len(name)>=40:
        return False
    if " " not in name:
        return False
    if name[0]=="?"
        return False
		
  return name.split(" ")

, :
— . , .
— . .


a=range(10);
for item in a:
    if item<5:
        a.remove(item)
print a 
#  [1, 3, 5, 6, 7, 8, 9]


? , . , . , :

i=0
while i<len(a):
    if i<5:
        del a[i]
    else:
        i += 1

filter(func, a). , func(item) .

filter(lambda x:x>=5, a)
#  [6, 7, 8, 9]
[i for i in a if i>=5]
#  [6, 7, 8, 9],    .
print a
#  a  

. c lambda-.
Python . : , .

')

Source: https://habr.com/ru/post/111588/


All Articles