使用 lambda 表达式连接插槽时的 memory_profiler [英] memory_profiler while using lambda expression to connect slots

查看:18
本文介绍了使用 lambda 表达式连接插槽时的 memory_profiler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Python3 中尝试 memory_profiler

按下按钮时.

我的情节是否显示了这种行为?还是一条看起来不直的直线?

那还有什么替代品呢?给我的:

用于ABCDE"中的字母:getattr(self, letter).clicked.connect(lambda checked, letter=letter: foo(letter))

main.py : hangman_pyqt5-muppy.py

#!/usr/bin/env python3# -*- 编码:utf-8 -*-"""创建于 2020 年 5 月 5 日星期二 19:21:27@作者:彼得罗"""导入系统从 PyQt5 导入 QtWidgets,uic从 PyQt5.QtWidgets 导入 QDesktopWidget进口刽子手005#from pympler导入muppy,总结##########################################from pympler 导入跟踪器#导入资源WORDLIST_FILENAME = "words.txt"wordlist = hangman005.load_words(WORDLIST_FILENAME)定义主():定义中心(自我):qr = self.frameGeometry()cp = QDesktopWidget().availableGeometry().center()qr.moveCenter(cp)self.move(qr.topLeft())类 MainMenu(QtWidgets.QMainWindow):def __init__(self):super(MainMenu, self).__init__()uic.loadUi('main_window2.ui', self)# self.ButtonQ.clicked.connect(self.QPushButtonQPressed)self.centro = 中心(自我)自我中心# self.show()self.hangman()def closeEvent(self, event): #你想要的功能在这里关闭 = QtWidgets.QMessageBox.question(自我,退出","您确定要停止进程吗?",QtWidgets.QMessageBox.Yes |QtWidgets.QMessageBox.No)如果关闭 == QtWidgets.QMessageBox.Yes:事件.accept()别的:事件.ignore()def printo(self, i):打印('oooooooooooooooooooooooo:',我)# all_objects = muppy.get_objects()# sum1 = summary.summarize(all_objects)# 打印出大对象的摘要# summary.print_(sum1) from pimpler import tracker### self.memory_tracker = tracker.SummaryTracker()# self.memory_tracker.print_diff()def 刽子手(自己):letter_guessed=[]最大猜测 = 6secret_word = hangman005.choose_word(wordlist)secret_word_lenght=len(secret_word)secret_word=hangman005.split(secret_word)元音=('a','e','i','o','u')secret_word_print=('_ '*secret_word_length )self.word_to_guess.setText(secret_word_print )字母=hangman005.splitt('ABCDEFGHIJKLMNOPQRSTYVWXXYZ')打印(字母)对于我的字母:打印('llllllllllllll:',我)# button = "self.MainMenu."+i# self.[i].clicked.connect(self.printo(i))# button = getattr(self, i)# button.clicked.connect((lambda : self.printo(i for i in letters) ) )# button.clicked.connect(lambda j=self.printo(i) : j )# button.clicked.connect(lambda : self.printo(i))# button.clicked.connect(lambda: self.printo(i))# button.clicked.connect(lambda j=self.printo(i) : j for i in letters )# getattr(self, i).clicked.connect(lambda 检查, i=i: self.printo(i))# getattr(self, i).clicked.connect(lambda 检查, j=i: self.printo(j))getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))# self.A.clicked.connect(self.printo)# 添加到 python_script_being_profiled.py 中的泄漏代码# 获取对某些类型对象的引用,例如数据框# dataframes = [ao for ao in all_objects if isinstance(ao, pd.DataFrame)]## 对于数据帧中的 d:# 打印(d.columns.values)# 打印 (len(d))应用程序 = QtWidgets.QApplication(sys.argv)# sshFile="coffee.qss"# 使用 open(sshFile,"r") 作为 fh:# app.setStyleSheet(fh.read())窗口=主菜单()窗口.show()app.exec_()#all_objects = muppy.get_objects()#sum1 = summary.summarize(all_objects)#打印出大对象的摘要#summary.print_(sum1)# 获取对某些类型对象的引用,例如dataframe如果 __name__ == '__main__':主要的()

hangman005.py

#!/usr/bin/env python3# -*- 编码:utf-8 -*-"""创建于 2020 年 4 月 29 日星期三 19:36:32@作者:彼得罗"""随机导入导入字符串#WORDLIST_FILENAME = "words.txt"def load_words(WORDLIST_FILENAME):"""返回有效单词的列表.单词是小写字母的字符串.根据单词列表的大小,此功能可能需要一段时间才能完成."""print("正在从文件中加载单词列表...")# inFile: 文件inFile = open(WORDLIST_FILENAME, 'r')# 行:字符串line = inFile.readline()# wordlist:字符串列表wordlist = line.split()print(" ", len(wordlist), "加载的单词.")# 打印(行)# for elem in line:# 打印(元素)# 打印(单词表)# 对于单词列表中的元素:# 打印 ('
' , 元素)返回词表def 选择字(词表):"""wordlist(列表):单词列表(字符串)从 wordlist 中随机返回一个单词"""返回随机选择(单词表)# 帮助代码结束#------------------------------------# 将单词列表加载到变量wordlist中# 以便可以从程序中的任何位置访问它#wordlist = load_words()def splitt(单词):return [char for char in word]def is_word_guessed(secret_word, letters_guessed):'''secret_word:字符串,用户猜测的单词;假设所有字母都是小写letter_guessed:列表(字母),到目前为止已经猜到了哪些字母;假设所有字母都是小写的返回:布尔值,如果 secret_word 的所有字母都在 letters_guessed 中,则为 True;否则为假'''prova =all(letters_guessed 中的 item 用于 secret_word 中的项目)打印('证明:',证明)返回普罗瓦#secret_word='poppoli'#letters_guessed=['p','o','p','o','l','i']#letters_guessed=['p','i','l']#print('

is_word_guessed : ', is_word_guessed(secret_word,letters_guessed))#letters_guessed = []def get_guessed_word(secret_word, letters_guessed):'''secret_word:字符串,用户猜测的单词letter_guessed:列表(字母),到目前为止已经猜到了哪些字母返回:字符串,由字母、下划线 (_) 和空格组成,表示到目前为止,已经猜到了 secret_word 中的哪些字母.'''print('

secret_word_split' , secret_word)打印('letters_guessed',letters_guessed)结果=[]对于范围内的 val(0,len(secret_word)):如果在 letters_guessed 中的 secret_word[val]:结果.append(secret_word[val])别的:结果.append('_')print('
results : ' , ' '.join(results ))返回结果def get_available_letters(letters_guessed):'''secret_word_splitletter_guessed:列表(字母),到目前为止已经猜到了哪些字母返回:字符串(字母),由表示哪些字母没有的字母组成尚未被猜到.'''整个字母='abcdefghijklmnopqrstuvwxyz'整个字母拆分=拆分(整个字母)whole_letters_split = [x for x in entire_letters_split if x not in letters_guessed]返回整个字母拆分def 刽子手(secret_word):'''secret_word:字符串,要猜测的秘密单词.启动 Hangman 的互动游戏.* 在游戏开始时,让用户知道有多少secret_word 包含的字母以及他/她从多少个猜测开始.* 用户应该从 6 次猜测开始* 在每一轮之前,您应该向用户显示猜测的次数他/她已经离开并且用户还没有猜到的字母.* 要求用户每轮提供一个猜测.记得做确保用户输入一封信!* 用户应在每次猜测后立即收到反馈关于他们的猜测是否出现在计算机的单词中.* 每次猜测后,您应该向用户显示到目前为止,部分猜到了单词.secret_word_split遵循问题记录中详述的其他限制.'''letter_guessed=[]最大猜测 = 6secret_word_lenght=len(secret_word)秘密字=分裂(秘密字)元音=('a','e','i','o','u')print('
欢迎来到 HANGMAN ;-) ')print('
secret_word_lenght : ' , secret_word_lenght )print('
'+' _ '*secret_word_lenght )print('
you have ' , max_guesses , ' 猜测要小心选择')而真:guess= input('
做出你的第一选择:')如果猜测不在 get_available_letters(letters_guessed) 中:print('你只能选择in' , ' '.join(get_available_letters(letters_guessed)))继续如果在 get_available_letters(letters_guessed) 中猜测:letter_guessed.append(猜测)# print('
letters_guessed appended : ' , ' '.join(letters_guessed) )# max_guesses -= 1print(' 一个 che punto sei : ' , ' '.join(get_guessed_word(secret_word, letters_guessed)))# print('
you have ' , max_guesses , '猜测要小心选择')如果在 secret_word 中猜测:print('好!!!!!!!!!!!!!')print('
你还有 ' , max_guesses , '猜测要小心选择')别的:print('错误!!!!!!!!!!!!!!!!!!!!!!')如果猜测元音:最大猜测 -= 2别的:最大猜测 -= 1print('
now you have only' , max_guesses , '猜测要小心选择')如果 is_word_guessed(secret_word, letters_guessed) == True:print('
HAI VINTO !!!!!!!!!!!!!!!!!!!!!!')total_score= max_guesses * len(list(set(secret_word)))print('
il tuo punteggio è : ' , total_score)休息如果 max_guesses <= 0:print('
HAI PERSO STUPIDA CAPRA !!!!!!!!!!!!!!!!!!!!!')print('
la parola era : ' , ''.join(secret_word), '你这个白痴!!')休息# 当你完成你的刽子手功能后,向下滚动到底部# 文件并取消注释前两行以进行测试#(提示:你可能想选择你自己的# secret_word 当你在做你自己的测试时)#------------------------------------def match_with_gaps(my_word, other_word):'''my_word:包含_个字符的字符串,当前猜测的秘密单词other_word:字符串,常规英文单词返回:布尔值,如果 my_word 的所有实际字母都与other_word 的对应字母,或者该字母是特殊符号_ ,并且 my_word 和 other_word 的长度相同;否则为假:'''如果 len(my_word) == len(other_word):对于范围内的 val(0,len(my_word)):如果 my_word[val] == '_':# 打印('确定')证明=真elif my_word[val] != '_' 和 my_word[val]==other_word[val]:# 打印('确定')证明=真别的:# 打印('KO')证明=假休息别的:# print('不同的长度')证明=假返回普罗瓦def show_possible_matches(my_word):'''my_word:包含_个字符的字符串,当前猜测的秘密单词返回:什么都没有,但应该打印出单词列表中与 my_word 匹配的每个单词请记住,在刽子手中,当猜到一个字母时,所有位置那个字母出现在秘密单词中的位置被揭示.因此,隐藏的字母(_)不能是单词中的字母之一这已经被揭露了.'''x=0y=0对于范围内的 i(0,len(wordlist)):other_word=splitt(wordlist[i])如果 match_with_gaps(my_word, other_word):打印(单词列表 [i],结束 = '')x += 1别的:y += 1print('
parole trovate : ' , x)print('parole saltate : ' , y)print('parole totali : ' , x+y)print('长度词表:' , len(词表))返回结束 = ''def hangman_with_hints(secret_word):'''secret_word:字符串,要猜测的秘密单词.启动 Hangman 的互动游戏.* 在游戏开始时,让用户知道有多少secret_word 包含的字母以及他/她从多少个猜测开始.* 用户应该从 6 次猜测开始# 在此处填写您的代码并删除通过"经过* 在每一轮之前,你应该 str 向用户显示有多少猜测他/她已经离开并且用户还没有猜到的字母.* 要求用户每轮提供一个猜测.确保检查用户是否猜到了一个字母* 用户应在每次猜测后立即收到反馈关于他们的猜测是否出现在计算机的单词中.* 每次猜测后,您应该向用户显示到目前为止,部分猜到了单词.* 如果猜测是符号 *,打印出 wordlist 中的所有单词匹配当前猜测的单词.遵循问题记录中详述的其他限制.'''#secret_word_lenght=len(secret_word)# print('secret_word_lenght : ' , secret_word_lenght )letter_guessed=[]最大猜测 = 6secret_word_lenght=len(secret_word)秘密字=分裂(秘密字)元音=('a','e','i','o','u')print('
欢迎来到 HANGMAN ;-) ')print('
secret_word_lenght : ' , secret_word_lenght )print('
 使用 * 作为超级帮助!!!!')print('
'+' _ '*secret_word_lenght )print('
you have ' , max_guesses , ' 猜测要小心选择')而真:猜测=输入('
做出你的选择:')如果猜测 == '*' :打印('注意力超级奖金!!!')my_word=(get_guessed_word(secret_word, letters_guessed))show_possible_matches(my_word)继续如果猜测不在 get_available_letters(letters_guessed) 中:print('你只能选择in' , ' '.join(get_available_letters(letters_guessed)))继续如果在 get_available_letters(letters_guessed) 中猜测:letter_guessed.append(猜测)# print('
letters_guessed appended : ' , ' '.join(letters_guessed) )# max_guesses -= 1print(' 一个 che punto sei : ' , ' '.join(get_guessed_word(secret_word, letters_guessed)))# print('
you have ' , max_guesses , '猜测要小心选择')如果在 secret_word 中猜测:print('好!!!!!!!!!!!!!')print('
你还有 ' , max_guesses , '猜测要小心选择')别的:print('错误!!!!!!!!!!!!!!!!!!!!!!')如果猜测元音:最大猜测 -= 2别的:最大猜测 -= 1print('
now you have only' , max_guesses , '猜测要小心选择')如果 is_word_guessed(secret_word, letters_guessed) == True:print('
HAI VINTO !!!!!!!!!!!!!!!!!!!!!!')total_score= max_guesses * len(list(set(secret_word)))print('
il tuo punteggio è : ' , total_score)休息如果 max_guesses <= 0:print('
HAI PERSO STUPIDA CAPRA !!!!!!!!!!!!!!!!!!!!!')print('
la parola era : ' , ''.join(secret_word).upper(), '你这个白痴!!')休息# 当你完成你的 hangman_with_hint 函数后,注释两个相似的# 上面用于运行 hangman 函数的行,然后取消注释# 这两行并运行这个文件来测试!# 提示:您可能想在测试时选择自己的 secret_word.#if __name__ == "__main__":#passui# 要测试第 2 部分,请注释掉上面的 pass 行并# 取消注释以下两行.# secret_word = choose_word(wordlist)# 刽子手(secret_word)################ 要测试第 3 部分,请重新注释上述行并# 取消注释以下两行.# secret_word = choose_word(wordlist)# hangman_with_hints(secret_word)

ui 文件,main_window2.ui

<?xml version="1.0" encoding="UTF-8"?><ui版本="4.0"><class>主窗口</class><widget class="QMainWindow" name="MainWindow"><属性名称="几何"><正确><x>0</x><y>0</y><宽度>863</宽度><身高>687</身高></正确></属性><属性名="windowTitle"><string>HANGMAN</string></属性><属性名称="样式表"><string notr="true"/></属性><widget class="QWidget" name="centralwidget"><widget class="QLabel" name="word_to_guess"><属性名称="几何"><正确><x>250</x><y>60</y><宽度>341</宽度><身高>91</身高></正确></属性><属性名称="字体"><字体><pointsize>18</pointsize><体重>75</体重><粗体>真实</粗体></字体></属性><属性名称="文本"><string>word_to_guess</string></属性><属性名称="对齐"><set>Qt::AlignCenter</set></属性></小部件><widget class="QGroupBox" name="groupBox"><属性名称="几何"><正确><x>20</x><y>170</y><宽度>821</宽度><身高>201</身高></正确></属性><属性名称="样式表"><string notr="true">QPushButton{背景颜色:#9de650;}QPushButton:悬停{背景颜色:绿色;}</字符串></属性><属性名称="标题"><字符串>组框</字符串></属性><widget class="QPushButton" name="A"><属性名称="几何"><正确><x>30</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="自动填充背景"><bool>假</bool></属性><属性名称="文本"><字符串>A</字符串></属性></小部件><widget class="QPushButton" name="B"><属性名称="几何"><正确><x>90</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>B</字符串></属性></小部件><widget class="QPushButton" name="C"><属性名称="几何"><正确><x>150</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>C</字符串></属性></小部件><widget class="QPushButton" name="D"><属性名称="几何"><正确><x>210</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>D</字符串></属性></小部件><widget class="QPushButton" name="E"><属性名称="几何"><正确><x>270</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>E</字符串></属性></小部件><widget class="QPushButton" name="F"><属性名称="几何"><正确><x>330</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>F</字符串></属性></小部件><widget class="QPushButton" name="G"><属性名称="几何"><正确><x>390</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>G</字符串></属性></小部件><widget class="QPushButton" name="H"><属性名称="几何"><正确><x>450</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>H</字符串></属性></小部件><widget class="QPushButton" name="I"><属性名称="几何"><正确><x>510</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>我</字符串></属性></小部件><widget class="QPushButton" name="J"><属性名称="几何"><正确><x>570</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>J</字符串></属性></小部件><widget class="QPushButton" name="K"><属性名称="几何"><正确><x>630</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>K</字符串></属性></小部件><widget class="QPushButton" name="L"><属性名称="几何"><正确><x>690</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>L</字符串></属性></小部件><widget class="QPushButton" name="M"><属性名称="几何"><正确><x>750​​</x><y>50</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>M</字符串></属性></小部件><widget class="QPushButton" name="N"><属性名称="几何"><正确><x>30</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>N</字符串></属性></小部件><widget class="QPushButton" name="O"><属性名称="几何"><正确><x>90</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>O</字符串></属性></小部件><widget class="QPushButton" name="P"><属性名称="几何"><正确><x>150</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>P</字符串></属性></小部件><widget class="QPushButton" name="Q"><属性名称="几何"><正确><x>210</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>Q</字符串></属性></小部件><widget class="QPushButton" name="R"><属性名称="几何"><正确><x>270</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>R</字符串></属性></小部件><widget class="QPushButton" name="S"><属性名称="几何"><正确><x>330</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>S</字符串></属性></小部件><widget class="QPushButton" name="T"><属性名称="几何"><正确><x>390</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>T</字符串></属性></小部件><widget class="QPushButton" name="U"><属性名称="几何"><正确><x>450</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>U</字符串></属性></小部件><widget class="QPushButton" name="V"><属性名称="几何"><正确><x>510</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>V</字符串></属性></小部件><widget class="QPushButton" name="W"><属性名称="几何"><正确><x>570</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>W</字符串></属性></小部件><widget class="QPushButton" name="X"><属性名称="几何"><正确><x>630</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>X</字符串></属性></小部件><widget class="QPushButton" name="Y"><属性名称="几何"><正确><x>690</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>Y</字符串></属性></小部件><widget class="QPushButton" name="Z"><属性名称="几何"><正确><x>750​​</x><y>120</y><宽度>41</宽度><身高>41</身高></正确></属性><属性名称="文本"><字符串>Z</字符串></属性></小部件></小部件></小部件><widget class="QMenuBar" name="menubar"><属性名称="几何"><正确><x>0</x><y>0</y><宽度>863</宽度><身高>29</身高></正确></属性></小部件><widget class="QStatusBar" name="statusbar"><属性名称="sizeGripEnabled"><bool>真</bool></属性></小部件></小部件><资源/><连接/></ui>

words.txt:

 sinew sings singe sinks sinus sioux sires sired siren sisal sissy Sitar sites sited Sixes Sixty Sixty Size Size Sketch skeet skein skews skidskied skier sky skift Skill skim skins skink skipsskirl skitsskits skulk 头骨臭鼬板 slack slags slainslake slams 俚语 slant slaps slash slats slate slavs slave slaws slays sleds smooth sleep sleet sleep slews slice slick slide slier slims slime slimy sling slink slips slots sloes slogs sloop slops slope

如此处所述:

  • self.button.clicked.connect(lambda 检查, v=list(range(100000)): None)

在连接和断开连接时观察到,由于 lambda 维护了 v=list(range(100000)) 的信息,因此消耗的内存增加了.

<小时>

但在您的代码中,闭包仅存储最小的变量j":

getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))

为了了解这个变量的影响,除了提供替代方案之外,我还将消除不必要的测试代码(hangman005.py 等):

  • 无连接:

类 MainMenu(QtWidgets.QMainWindow):def __init__(self):super(MainMenu, self).__init__()uic.loadUi("main_window2.ui", self)self.hangman()def 刽子手(自己):字母 = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"对于我的字母:经过def printo(self, i):print("oooooooooooooooooooooo :", i)

  • 使用 lambda:

类 MainMenu(QtWidgets.QMainWindow):def __init__(self):super(MainMenu, self).__init__()uic.loadUi("main_window2.ui", self)self.hangman()def 刽子手(自己):字母 = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"对于我的字母:getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))def printo(self, i):print("oooooooooooooooooooooo :", i)

  • 使用 functools.partial

类 MainMenu(QtWidgets.QMainWindow):def __init__(self):super(MainMenu, self).__init__()uic.loadUi("main_window2.ui", self)self.hangman()def 刽子手(自己):字母 = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"对于我的字母:getattr(self, i).clicked.connect(部分(self.printo, i))def printo(self, i):print("oooooooooooooooooooooo :", i)

  • 一次连接

类 MainMenu(QtWidgets.QMainWindow):def __init__(self):super(MainMenu, self).__init__()uic.loadUi("main_window2.ui", self)self.hangman()def 刽子手(自己):字母 = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"对于我的字母:getattr(self, i).setProperty("i", i)getattr(self, i).clicked.connect(self.printo)def printo(self):i = self.sender().property("i")print("oooooooooooooooooooooo :", i)

正如我们所见,所有方法之间没有显着差异,因此在您的情况下,没有内存泄漏,或者说内存泄漏非常小.

结论:每次创建 lambda 方法时,它都有一个闭包(在您的情况下为 j = i),因此 OP 建议考虑到这一点,例如在您的情况下 len(letters) * size_of(i) 被消耗,在小 lettersi 使其可以忽略不计,但如果您不必要地存储较重的对象,那么它会出问题

I am experimenting memory_profiler in Python3 following

https://medium.com/zendesk-engineering/hunting-for-memory-leaks-in-python-applications-6824d0518774

thanks to @eyllanesc here PyQt5 designer gui and iterate/loop over QPushButton [duplicate]

I just created a mainwindow with 21 buttons a to z ; each time a press one of them I print the letter they represent.

While reading: Using lambda expression to connect slots in pyqt I came across:

" Beware! As soon as you connect your signal to a lambda slot with a reference to self, your widget will not be garbage-collected! That's because lambda creates a closure with yet another uncollectable reference to the widget.

Thus, self.someUIwidget.someSignal.connect(lambda p: self.someMethod(p)) is very evil :) "

Here my plot:

while pressing buttons.

Does my plot shows this behaviour ?? Or is it a straight line that doent looks straight ?

What is an alternative then? to my:

use for letter in "ABCDE": getattr(self, letter).clicked.connect(lambda checked, letter=letter: foo(letter))

main.py : hangman_pyqt5-muppy.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May  5 19:21:27 2020

@author: Pietro

"""

import sys

from PyQt5 import QtWidgets, uic

from PyQt5.QtWidgets import QDesktopWidget

import hangman005

#from pympler import muppy, summary #########################################
#
#from pympler import tracker

#import resource


WORDLIST_FILENAME = "words.txt"

wordlist = hangman005.load_words(WORDLIST_FILENAME)



def main():


    def center(self):                     
        qr = self.frameGeometry()   
        cp = QDesktopWidget().availableGeometry().center()    
        qr.moveCenter(cp)    
        self.move(qr.topLeft())


    class MainMenu(QtWidgets.QMainWindow):


        def __init__(self):        
            super(MainMenu, self).__init__()            
            uic.loadUi('main_window2.ui', self)                       
#                self.ButtonQ.clicked.connect(self.QPushButtonQPressed)             
            self.centro = center(self)             
            self.centro                      
#            self.show() 
            self.hangman()



        def closeEvent(self, event): #Your desired functionality here         
            close = QtWidgets.QMessageBox.question(self,
                                         "QUIT",
                                         "Are you sure want to stop process?",
                                         QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
            if close == QtWidgets.QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()

        def printo(self, i):
            print('oooooooooooooooooooooo :', i)   
#            all_objects = muppy.get_objects()
#            sum1 = summary.summarize(all_objects)# Prints out a summary of the large objects
#            summary.print_(sum1) from pympler import tracker
#           
#
#            self.memory_tracker = tracker.SummaryTracker()
#            self.memory_tracker.print_diff()

        def hangman(self):
            letters_guessed=[]
            max_guesses = 6
            secret_word = hangman005.choose_word(wordlist)
            secret_word_lenght=len(secret_word)
            secret_word=hangman005.splitt(secret_word)
            vowels=('a','e','i','o','u')
            secret_word_print=('_ '*secret_word_lenght )
            self.word_to_guess.setText(secret_word_print )
            letters=hangman005.splitt('ABCDEFGHIJKLMNOPQRSTYVWXXYZ')
            print(letters )
            for i in letters:
                print('lllllllllllllll : ' ,i)
#                 button = "self.MainMenu."+i
#                 self.[i].clicked.connect(self.printo(i))
#                 button = getattr(self, i)
#                button.clicked.connect((lambda : self.printo(i for i in letters) )    )
#                 button.clicked.connect(lambda j=self.printo(i) : j )
#                 button.clicked.connect(lambda : self.printo(i))
#                button.clicked.connect(lambda: self.printo(i))
#            button.clicked.connect(lambda j=self.printo(i) : j   for i in letters )
#                 getattr(self, i).clicked.connect(lambda checked, i=i: self.printo(i))
#                 getattr(self, i).clicked.connect(lambda checked, j=i: self.printo(j))
                getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))
#            self.A.clicked.connect(self.printo)
# Add to leaky code within python_script_being_profiled.py

                 # Get references to certain types of objects such as dataframe
#                dataframes = [ao for ao in all_objects if isinstance(ao, pd.DataFrame)]
#                
#                for d in dataframes:
#                    print (d.columns.values)
#                    print (len(d))                







    app = QtWidgets.QApplication(sys.argv)

#    sshFile="coffee.qss"
#    with open(sshFile,"r") as fh:
#        app.setStyleSheet(fh.read())

    window=MainMenu()
    window.show()

    app.exec_()

#all_objects = muppy.get_objects()
#sum1 = summary.summarize(all_objects)# Prints out a summary of the large objects
#summary.print_(sum1)# Get references to certain types of objects such as dataframe

if __name__ == '__main__':
    main()

hangman005.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 19:36:32 2020

@author: Pietro
"""



import random
import string



#WORDLIST_FILENAME = "words.txt"


def load_words(WORDLIST_FILENAME):
    """
    Returns a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
#    print(line)
#    for elem in line:
#        print (elem)
#    print(wordlist)
#    for elem in wordlist:
#        print ('
' , elem) 
    return wordlist



def choose_word(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code

# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program

#wordlist = load_words()



def splitt(word): 
    return [char for char in word]   


def is_word_guessed(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing; assumes all letters are
      lowercase
    letters_guessed: list (of letters), which letters have been guessed so far;
      assumes that all letters are lowercase
    returns: boolean, True if all the letters of secret_word are in letters_guessed;
      False otherwise
    '''
    prova =all(item in letters_guessed for item in secret_word )    
    print(' prova : ' , prova )
    return prova 

#secret_word='popoli'
#letters_guessed=['p','o','p','o','l','i']
#letters_guessed=['p','i','l']    
#print('

is_word_guessed : ', is_word_guessed(secret_word,letters_guessed))
#letters_guessed = []


def get_guessed_word(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string, comprised of letters, underscores (_), and spaces that represents
      which letters in secret_word have been guessed so far.
    '''
    print('

secret_word_split' , secret_word)
    print('letters_guessed', letters_guessed )
    results=[]
    for val in range(0,len(secret_word)):
            if secret_word[val] in letters_guessed:
                results.append(secret_word[val])
            else:
                results.append('_')
    print('
results : ' , ' '.join(results ))        
    return results


def get_available_letters(letters_guessed):
    '''secret_word_split
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string (of letters), comprised of letters that represents which letters have not
      yet been guessed.
    '''
    entire_letters='abcdefghijklmnopqrstuvwxyz'
    entire_letters_split=splitt(entire_letters)
    entire_letters_split = [x for x in entire_letters_split if x not in letters_guessed]
    return entire_letters_split




def hangman(secret_word):
    '''
    secret_word: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many 
      letters the secret_word contains and how many guesses s/he starts with.

    * The user should start with 6 guesses

    * Before each round, you should display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.

    * Ask the user to supply one guess per round. Remember to make
      sure that the user puts in a letter!

    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the 
      partially guessed word so far.
    secret_word_split
    Follows the other limitations detailed in the problem write-up.
    '''

    letters_guessed=[]
    max_guesses = 6
    secret_word_lenght=len(secret_word)
    secret_word=splitt(secret_word)
    vowels=('a','e','i','o','u')

    print('
Welcome to HANGMAN ;-) ')
    print('
secret_word_lenght : ' , secret_word_lenght  ) 
    print('
'+' _ '*secret_word_lenght )
    print('
you have ' , max_guesses , ' guesses be carefull choosing')

    while True:
        guess= input('
make your first choice : ' )
        if guess not in get_available_letters(letters_guessed):
                print('You can only choose in' , ' '.join(get_available_letters(letters_guessed)))
                continue
        if guess in get_available_letters(letters_guessed):
                letters_guessed.append(guess)
#                print('
letters_guessed appended : ' , ' '.join(letters_guessed) )
#                max_guesses -= 1
                print(' a che punto sei : ' , ' '.join(get_guessed_word(secret_word, letters_guessed)))
#                print('
you have ' , max_guesses , ' guesses be carefull choosing')
                if guess in secret_word:
                    print('GOOD !!!!!!!!!!!!!')
                    print('
you still have ' , max_guesses , ' guesses be carefull choosing')
                else:
                    print('ERRORE !!!!!!!!!!!!!!!!!!!!!!')
                    if guess in vowels:
                        max_guesses -= 2
                    else:
                        max_guesses -= 1
                    print('
now you have only' , max_guesses , ' guesses be carefull choosing')

        if is_word_guessed(secret_word, letters_guessed) == True:
            print('
HAI VINTO !!!!!!!!!!!!!!!!!!!!!!')
            total_score= max_guesses * len(list(set(secret_word)))

            print('
il tuo punteggio è : ' , total_score)

            break
        if max_guesses <= 0:
            print('
HAI PERSO STUPIDA CAPRA !!!!!!!!!!!!!!!!!!!!!!')
            print('
la parola era : ' , ''.join(secret_word), ' you moron !!')
            break




# When you've completed your hangman function, scroll down to the bottom
# of the file and uncomment the first two lines to test
#(hint: you might want to pick your own
# secret_word while you're doing your own testing)


# -----------------------------------



def match_with_gaps(my_word, other_word):
    '''
    my_word: string with _ characters, current guess of secret word
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the 
        corresponding letters of other_word, or the letter is the special symbol
        _ , and my_word and other_word are of the same length;
        False otherwise: 
    '''

    if len(my_word) == len(other_word):

        for val in range(0,len(my_word)):
            if my_word[val] == '_':
#                print('OK')
                prova=True
            elif my_word[val] != '_' and my_word[val]==other_word[val]:
#                print('OK')
                prova=True
            else:
#                print('KO')
                prova=False
                break
    else:
#        print('DIFFERENT LENGHT')
        prova=False
    return prova


def show_possible_matches(my_word):
    '''
    my_word: string with _ characters, current guess of secret word
    returns: nothing, but should print out every word in wordlist that matches my_word
             Keep in mind that in hangman when a letter is guessed, all the positions
             at which that letter occurs in the secret word are revealed.
             Therefore, the hidden letter(_ ) cannot be one of the letters in the word
             that has already been revealed.

    '''
    x=0
    y=0
    for i in range(0,len(wordlist)):
        other_word=splitt(wordlist[i])
        if match_with_gaps(my_word, other_word):
            print(wordlist[i], end = ' ')
            x += 1
        else:
            y += 1
    print('
parole trovate : ' , x)
    print('parole saltate : ' , y)
    print('parole totali  : ' , x+y)
    print('lenght wordlist :' , len(wordlist))
    return


end = ''
def hangman_with_hints(secret_word):
    '''
    secret_word: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many 
      letters the secret_word contains and how many guesses s/he starts with.

    * The user should start with 6 guesses
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    pass
    * Before each round, you should str display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.

    * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter

    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the 
      partially guessed word so far.

    * If the guess is the symbol *, print out all words in wordlist that
      matches the current guessed word. 

    Follows the other limitations detailed in the problem write-up.
    '''

#    secret_word_lenght=len(secret_word)
#    print('secret_word_lenght : ' , secret_word_lenght  )

    letters_guessed=[]
    max_guesses = 6
    secret_word_lenght=len(secret_word)
    secret_word=splitt(secret_word)
    vowels=('a','e','i','o','u')

    print('
Welcome to HANGMAN ;-) ')
    print('
secret_word_lenght : ' , secret_word_lenght  ) 
    print('
 use * for superhelp !!!! ')
    print('
'+' _ '*secret_word_lenght )
    print('
you have ' , max_guesses , ' guesses be carefull choosing')

    while True:
        guess= input('
make your choice : ' )
        if guess == '*' :
                print('ATTENZIONE SUPER BONUS !!!')
                my_word=(get_guessed_word(secret_word, letters_guessed))
                show_possible_matches(my_word)
                continue
        if guess not in get_available_letters(letters_guessed):
                print('You can only choose in' , ' '.join(get_available_letters(letters_guessed)))
                continue
        if guess in get_available_letters(letters_guessed):
                letters_guessed.append(guess)
#                print('
letters_guessed appended : ' , ' '.join(letters_guessed) )
#                max_guesses -= 1
                print(' a che punto sei : ' , ' '.join(get_guessed_word(secret_word, letters_guessed)))
#                print('
you have ' , max_guesses , ' guesses be carefull choosing')
                if guess in secret_word:
                    print('GOOD !!!!!!!!!!!!!')
                    print('
you still have ' , max_guesses , ' guesses be carefull choosing')
                else:
                    print('ERRORE !!!!!!!!!!!!!!!!!!!!!!')
                    if guess in vowels:
                        max_guesses -= 2
                    else:
                        max_guesses -= 1
                    print('
now you have only' , max_guesses , ' guesses be carefull choosing')

        if is_word_guessed(secret_word, letters_guessed) == True:
            print('
HAI VINTO !!!!!!!!!!!!!!!!!!!!!!')
            total_score= max_guesses * len(list(set(secret_word)))

            print('
il tuo punteggio è : ' , total_score)

            break
        if max_guesses <= 0:
            print('
HAI PERSO STUPIDA CAPRA !!!!!!!!!!!!!!!!!!!!!!')
            print('
la parola era : ' , ''.join(secret_word).upper(), ' you moron !!')
            break

# When you've completed your hangman_with_hint function, comment the two similar
# lines above that were used to run the hangman function, and then uncomment
# these two lines and run this file to test!
# Hint: You might want to pick your own secret_word while you're testing.


#if __name__ == "__main__":
    # passui

    # To test part 2, comment out the pass line above and
    # uncomment the following two lines.

#    secret_word = choose_word(wordlist)
#    hangman(secret_word)

###############

    # To test part 3 re-comment out the above lines and 
    # uncomment the following two lines. 

#    secret_word = choose_word(wordlist)
#    hangman_with_hints(secret_word)

ui file, main_window2.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>863</width>
    <height>687</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>HANGMAN</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLabel" name="word_to_guess">
    <property name="geometry">
     <rect>
      <x>250</x>
      <y>60</y>
      <width>341</width>
      <height>91</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <pointsize>18</pointsize>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
    <property name="text">
     <string>word_to_guess</string>
    </property>
    <property name="alignment">
     <set>Qt::AlignCenter</set>
    </property>
   </widget>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>20</x>
      <y>170</y>
      <width>821</width>
      <height>201</height>
     </rect>
    </property>
    <property name="styleSheet">
     <string notr="true">QPushButton{
    background-color: #9de650;
}


QPushButton:hover{
    background-color: green;
}

</string>
    </property>
    <property name="title">
     <string>GroupBox</string>
    </property>
    <widget class="QPushButton" name="A">
     <property name="geometry">
      <rect>
       <x>30</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="autoFillBackground">
      <bool>false</bool>
     </property>
     <property name="text">
      <string>A</string>
     </property>
    </widget>
    <widget class="QPushButton" name="B">
     <property name="geometry">
      <rect>
       <x>90</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>B</string>
     </property>
    </widget>
    <widget class="QPushButton" name="C">
     <property name="geometry">
      <rect>
       <x>150</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>C</string>
     </property>
    </widget>
    <widget class="QPushButton" name="D">
     <property name="geometry">
      <rect>
       <x>210</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>D</string>
     </property>
    </widget>
    <widget class="QPushButton" name="E">
     <property name="geometry">
      <rect>
       <x>270</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>E</string>
     </property>
    </widget>
    <widget class="QPushButton" name="F">
     <property name="geometry">
      <rect>
       <x>330</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>F</string>
     </property>
    </widget>
    <widget class="QPushButton" name="G">
     <property name="geometry">
      <rect>
       <x>390</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>G</string>
     </property>
    </widget>
    <widget class="QPushButton" name="H">
     <property name="geometry">
      <rect>
       <x>450</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>H</string>
     </property>
    </widget>
    <widget class="QPushButton" name="I">
     <property name="geometry">
      <rect>
       <x>510</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>I</string>
     </property>
    </widget>
    <widget class="QPushButton" name="J">
     <property name="geometry">
      <rect>
       <x>570</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>J</string>
     </property>
    </widget>
    <widget class="QPushButton" name="K">
     <property name="geometry">
      <rect>
       <x>630</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>K</string>
     </property>
    </widget>
    <widget class="QPushButton" name="L">
     <property name="geometry">
      <rect>
       <x>690</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>L</string>
     </property>
    </widget>
    <widget class="QPushButton" name="M">
     <property name="geometry">
      <rect>
       <x>750</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>M</string>
     </property>
    </widget>
    <widget class="QPushButton" name="N">
     <property name="geometry">
      <rect>
       <x>30</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>N</string>
     </property>
    </widget>
    <widget class="QPushButton" name="O">
     <property name="geometry">
      <rect>
       <x>90</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>O</string>
     </property>
    </widget>
    <widget class="QPushButton" name="P">
     <property name="geometry">
      <rect>
       <x>150</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>P</string>
     </property>
    </widget>
    <widget class="QPushButton" name="Q">
     <property name="geometry">
      <rect>
       <x>210</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>Q</string>
     </property>
    </widget>
    <widget class="QPushButton" name="R">
     <property name="geometry">
      <rect>
       <x>270</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>R</string>
     </property>
    </widget>
    <widget class="QPushButton" name="S">
     <property name="geometry">
      <rect>
       <x>330</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>S</string>
     </property>
    </widget>
    <widget class="QPushButton" name="T">
     <property name="geometry">
      <rect>
       <x>390</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>T</string>
     </property>
    </widget>
    <widget class="QPushButton" name="U">
     <property name="geometry">
      <rect>
       <x>450</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>U</string>
     </property>
    </widget>
    <widget class="QPushButton" name="V">
     <property name="geometry">
      <rect>
       <x>510</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>V</string>
     </property>
    </widget>
    <widget class="QPushButton" name="W">
     <property name="geometry">
      <rect>
       <x>570</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>W</string>
     </property>
    </widget>
    <widget class="QPushButton" name="X">
     <property name="geometry">
      <rect>
       <x>630</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>X</string>
     </property>
    </widget>
    <widget class="QPushButton" name="Y">
     <property name="geometry">
      <rect>
       <x>690</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>Y</string>
     </property>
    </widget>
    <widget class="QPushButton" name="Z">
     <property name="geometry">
      <rect>
       <x>750</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>Z</string>
     </property>
    </widget>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>863</width>
     <height>29</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar">
   <property name="sizeGripEnabled">
    <bool>true</bool>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

words.txt :

 sinew sings singe sinks sinus sioux sires sired siren sisal sissy sitar sites sited sixes sixty sixth sizes sized skate skeet skein skews skids skied skier skies skiff skill skims skimp skins skink skips skirl skirt skits skulk skull skunk slabs slack slags slain slake slams slang slant slaps slash slats slate slavs slave slaws slays sleds sleek sleep sleet slept slews slice slick slide slier slims slime slimy sling slink slips slits sloes slogs sloop slops slope 

As described here:

Using lambda expression to connect slots in pyqt

"Using slots with closures is not evil. If you're concerned about object cleanup, just explicitly disconnect any signals connected to slots forming a closure over the object being deleted. "

I dont understand any of it. How could I possibly disconnect the signals ?

解决方案

The problem pointed out in this post does not have to do with PyQt5 but with the lambda functions since, like any function, it creates a scope and stores memory, to test what the OP points out I have created the following example:

from PyQt5 import QtCore, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.counter = 0
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.on_timeout)
        self.timer.start(1000)

        self.button = QtWidgets.QPushButton("Press me")
        self.setCentralWidget(self.button)

    @QtCore.pyqtSlot()
    def on_timeout(self):
        self.counter += 1
        if self.counter % 2 == 0:
            self.connect()
        else:
            self.disconnect()

    def connect(self):
        self.button.setText("Connected")
        self.button.clicked.connect(lambda checked: None)
        # or
        # self.button.clicked.connect(lambda checked, v=list(range(100000)): None)

    def disconnect(self):
        self.button.setText("Disconnected")
        self.button.disconnect()


def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

  • self.button.clicked.connect(lambda checked: None)

  • self.button.clicked.connect(lambda checked, v=list(range(100000)): None)

As observed at the time of connection and disconnection, the memory consumed increases since the lambda maintains the information of v=list(range(100000)).


But in your code the closure stores only the variable "j" which is minimum:

getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))

To see how this variable affects I am going to eliminate the unnecessary code for the test (hangman005.py, etc) in addition to offering alternatives:

  • without connect:

class MainMenu(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainMenu, self).__init__()
        uic.loadUi("main_window2.ui", self)
        self.hangman()

    def hangman(self):
        letters = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"
        for i in letters:
            pass

    def printo(self, i):
        print("oooooooooooooooooooooo :", i)

  • with lambda:

class MainMenu(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainMenu, self).__init__()
        uic.loadUi("main_window2.ui", self)
        self.hangman()

    def hangman(self):
        letters = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"
        for i in letters:
            getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))

    def printo(self, i):
        print("oooooooooooooooooooooo :", i)

  • with functools.partial

class MainMenu(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainMenu, self).__init__()
        uic.loadUi("main_window2.ui", self)
        self.hangman()

    def hangman(self):
        letters = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"
        for i in letters:
            getattr(self, i).clicked.connect(partial(self.printo, i))

    def printo(self, i):
        print("oooooooooooooooooooooo :", i)

  • once connect

class MainMenu(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainMenu, self).__init__()
        uic.loadUi("main_window2.ui", self)
        self.hangman()

    def hangman(self):
        letters = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"
        for i in letters:
            getattr(self, i).setProperty("i", i)
            getattr(self, i).clicked.connect(self.printo)

    def printo(self):
        i = self.sender().property("i")
        print("oooooooooooooooooooooo :", i)

As we can see there is no significant difference between all the methods so in your case there is no memory leak or rather it is very small.

In conclusion: Every time you create a lambda method it has a closure (j = i in your case) so the OP recommends taking that into account, for example in your case len(letters) * size_of(i) are consumed which at Being small letters and i makes it negligible, but if you otherwise store a heavier object unnecessarily then it will cause problems

这篇关于使用 lambda 表达式连接插槽时的 memory_profiler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆