Skip to content

Instantly share code, notes, and snippets.

@Infernio
Last active August 7, 2020 00:28
Show Gist options
  • Save Infernio/2baa914ad6cf4bb4b3b2c170463a6615 to your computer and use it in GitHub Desktop.
Save Infernio/2baa914ad6cf4bb4b3b2c170463a6615 to your computer and use it in GitHub Desktop.
import __builtin__
orig_getattr = __builtin__.getattr
_getattr_sentinel = object()
def getattr_py3(object, name, default=_getattr_sentinel):
if isinstance(name, bytes):
raise TypeError(u'Do not pass bytestrings to getattr!')
if default is not _getattr_sentinel:
return orig_getattr(object, name, default)
else:
return orig_getattr(object, name)
__builtin__.getattr = getattr_py3
orig_setattr = __builtin__.setattr
def setattr_py3(object, name, value):
if isinstance(name, bytes):
raise TypeError(u'Do not pass bytestrings to setattr!')
orig_setattr(object, name, value)
__builtin__.setattr = setattr_py3
# Example:
getattr(object(), b'foo')
# Traceback (most recent call last):
# File ".\py3_hack.py", line 22, in <module>
# getattr(object(), b'foo')
# File ".\py3_hack.py", line 7, in getattr_py3
# raise TypeError(u'Do not pass bytestrings to getattr!')
# TypeError: Do not pass bytestrings to getattr!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment