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 :) "
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 ('\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 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 ?