Skip to content

Instantly share code, notes, and snippets.

@duncangh
Created September 20, 2019 02:36
Show Gist options
  • Save duncangh/d1ca0edca2f47c677c3cf6a780579046 to your computer and use it in GitHub Desktop.
Save duncangh/d1ca0edca2f47c677c3cf6a780579046 to your computer and use it in GitHub Desktop.
Explore the attributes and methods on a foreign object in python
def reduce_namespace_to_public_only(namespace_directory : list) -> list:
"""
returns: list of public attribute and or method names
"""
_is_public_facing = lambda x: not x.startswith('_')
public_namespace_only : list = sorted(
filter(_is_public_facing, namespace_directory)
)
return set(public_namespace_only)
def main_object_namespace_exploration(foreign_object):
foreign_object_namespace_directory : list = foreign_object.__dir__()
foreign_object_attribute_namespace : list = sorted(foreign_object.__dict__.keys())
# filter down to just public namespace
# filter attribute only namespace list to only public
foreign_object_public_namespace = reduce_namespace_to_public_only(namespace_directory=foreign_object_namespace_directory)
foreign_object_public_attributes = reduce_namespace_to_public_only(namespace_directory=foreign_object_attribute_namespace)
# partition PUBLIC ONLY namespace to ATTRIBUTES and METHODS
# set difference between
# symmetric set difference.
# __dir__ returns everything both methods and attributes
# __dict__ returns only attributes
foreign_object_public_methods = foreign_object_public_namespace ^ foreign_object_public_attributes
foreign_object_public_attributes = foreign_object_public_attributes
return foreign_object_public_methods, foreign_object_public_attributes
# DEMO
class A:
def __init__():
self.attribute_a = 1
self._private_attribute_b = False
def _private_method(self):
return "GTFO"
def public_method(self):
return "hello world"
foreign_object_a = A()
main_object_namespace_exploration(foreign_object_a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment