Skip to content

Instantly share code, notes, and snippets.

@loneshark99
Last active December 25, 2021 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loneshark99/c95e944a4534b8c5bb54553c984bf919 to your computer and use it in GitHub Desktop.
Save loneshark99/c95e944a4534b8c5bb54553c984bf919 to your computer and use it in GitHub Desktop.
Python Learnings

Python Introspection Module is very useful to inspect object/modules/functions/classes etc at runtime.

Some of the important methods

import inspect
import numpy
 
def test:
 pass
 
inspect.getsourcefile(numpy)
inspect.isfunction(len)
inspect.isclass(len)
inspect.getmembers(numpy)
inspect.isclass(numpy)
inspect.getsource(test)

I always have to find the method params, for that I use the below function

import inspect

def test1(a,b,c='d'):
  pass

inspect.getfullargspec(test1)

Callable Class. This is a very important concept in Python along with the Class Instance, to get a better understanding of the language. Below the Resolver provides caching and makes it easy to expose things as Callable class. The class can be used like a function to get the desired results.

import socket
import inspect

class Resolver:
    
    def __init__(self):
        self._cache = {}

    def __call__(self, host):
        if host not in self._cache:
            self._cache[host] = socket.gethostbyname(host)
        return self._cache[host]   

    def clear(self):
        self._cache.clear()

    def has_host(self, host):
        return host in self._cache

ins = Resolver()
ins("google.com")
ins("github.com")
inspect.isfunction(ins)
callable(ins)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment