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

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

问题描述

我正在紧接着在Python3中试验memory_profiler

I am experimenting memory_profiler in Python3 following

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

在此感谢@eyllanesc PyQt5设计器gui并在QPushButton上循环/循环[重复]

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

我刚刚创建了一个带有21个按钮a到z的主窗口;每次按其中一个,我都会打印出它们代表的字母.

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

阅读时:使用Lambda表达式连接pyqt中的插槽我碰到了

提防!一旦您将信号连接到具有self引用的lambda插槽,您的小部件就不会被垃圾收集!这是因为lambda创建了一个闭包,并带有另一个无法收集的小部件引用.

" 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.

因此,self.someUIwidget.someSignal.connect(lambda p:self.someMethod(p))非常邪恶:)"

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

这是我的情节:

同时按下按钮.

我的剧情显示了这种行为吗?还是看起来像直线的直线?

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

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

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 ('\n' , 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('\n\nis_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('\n\nsecret_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('\nresults : ' , ' '.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('\nWelcome to HANGMAN ;-) ')
    print('\nsecret_word_lenght : ' , secret_word_lenght  ) 
    print('\n'+' _ '*secret_word_lenght )
    print('\nyou have ' , max_guesses , ' guesses be carefull choosing')

    while True:
        guess= input('\nmake 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('\nletters_guessed appended : ' , ' '.join(letters_guessed) )
#                max_guesses -= 1
                print(' a che punto sei : ' , ' '.join(get_guessed_word(secret_word, letters_guessed)))
#                print('\nyou have ' , max_guesses , ' guesses be carefull choosing')
                if guess in secret_word:
                    print('GOOD !!!!!!!!!!!!!')
                    print('\nyou still have ' , max_guesses , ' guesses be carefull choosing')
                else:
                    print('ERRORE !!!!!!!!!!!!!!!!!!!!!!')
                    if guess in vowels:
                        max_guesses -= 2
                    else:
                        max_guesses -= 1
                    print('\nnow you have only' , max_guesses , ' guesses be carefull choosing')

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

            print('\nil tuo punteggio è : ' , total_score)

            break
        if max_guesses <= 0:
            print('\nHAI PERSO STUPIDA CAPRA !!!!!!!!!!!!!!!!!!!!!!')
            print('\nla 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('\nparole 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('\nWelcome to HANGMAN ;-) ')
    print('\nsecret_word_lenght : ' , secret_word_lenght  ) 
    print('\n use * for superhelp !!!! ')
    print('\n'+' _ '*secret_word_lenght )
    print('\nyou have ' , max_guesses , ' guesses be carefull choosing')

    while True:
        guess= input('\nmake 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('\nletters_guessed appended : ' , ' '.join(letters_guessed) )
#                max_guesses -= 1
                print(' a che punto sei : ' , ' '.join(get_guessed_word(secret_word, letters_guessed)))
#                print('\nyou have ' , max_guesses , ' guesses be carefull choosing')
                if guess in secret_word:
                    print('GOOD !!!!!!!!!!!!!')
                    print('\nyou still have ' , max_guesses , ' guesses be carefull choosing')
                else:
                    print('ERRORE !!!!!!!!!!!!!!!!!!!!!!')
                    if guess in vowels:
                        max_guesses -= 2
                    else:
                        max_guesses -= 1
                    print('\nnow you have only' , max_guesses , ' guesses be carefull choosing')

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

            print('\nil tuo punteggio è : ' , total_score)

            break
        if max_guesses <= 0:
            print('\nHAI PERSO STUPIDA CAPRA !!!!!!!!!!!!!!!!!!!!!!')
            print('\nla 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文件main_window2.ui

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:

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 

如此处所述:

使用lambda表达式连接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 ?

推荐答案

这篇文章中指出的问题与PyQt5有关,但与lambda函数有关,因为它像其他任何函数一样会创建作用域并存储内存,以测试OP指出的内容我创建了以下示例:

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: None)
      • self.button.clicked.connect(lambda checked, v=list(range(100000)): None)

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

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

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

      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))
      

      要查看此变量的影响,除了提供替代方法之外,我还将消除测试的不必要代码(hangman005.py等)

      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:

      • 不连接:
      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)
      

      • 带有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)
      

      • 使用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)
      

      • 一旦连接
      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.

      结论:每次创建lambda方法时,它都会有一个闭包(在您的情况下为j = i),因此OP建议考虑到此情况,例如在您的情况下使用len(letters) * size_of(i),而该值小于i使其可以忽略不计,但是如果您另外不必要地存储了较重的对象,则将导致问题

      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天全站免登陆