Every documentation and answer I could find, says that in order to check if the program is "frozen" (an exe for example), we can use getattr(sys, 'frozen', False)
in the following way:
import sys
if getattr(sys, 'frozen', False):
print('program is frozen exe')
else:
print('program is a .py script')
Where False
is returned by default if the frozen
attribute doesn't exist instead of throwing an AttributeError. An example from the console:
>>> getattr(sys, 'frozen')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'sys' has no attribute 'frozen'
>>> getattr(sys, 'frozen', False)
False
>>> hasattr(sys, 'frozen')
False
This is all fine, but there is a shorter version of this that does the same job, unless I'm missing something:
hasattr(sys, 'frozen')
Which simply returns True
or False
without the need to specify a default. Despite this being shorter and possibly more readable, every documentation and answer online uses getattr
instead. I'm sure there's a clever difference I might be overlooking, which is why I'm asking this question.
Example sources that refer to getattr
:
- Determining application path in a Python EXE generated by pyInstaller
- Pyinstaller documentation (Even uses
hasattr
on something else) - Cx_Freeze documentation