Explore by name
This function I often define in the ipython console, to symplify my work:
def ddir(modul, word=''): for d in dir(modul): if word.lower() in d.lower(): print(d)
I name it simply ddir()
with a doubble d
.
The dir()
function used in the 2nd row is a built-in Python function that takes our modul
as parameter and returns the list of properties and functions as strings.
We can call our ddir()
as
my_string = 'Hey!' ddir(my_string)
and it will list all of the properties and functions of a string.
The way this function becomes useful to me is when I define the 2nd parameter as well:
my_string = 'Hey!' ddir(my_string, 'is')
which, in this case, will list only properties and functions that include string 'is'
:
isalnum isalpha isascii isdecimal isdigit isidentifier islower isnumeric isprintable isspace istitle isupper
This works with all libraries, functions, classes, etc. and it makes it easier to develop the code.
Search also within the docStrings
We can also go a step further and make it search inside docStrings as well:
def doc_dir(modul, word=''): word_lc = word.lower() for d in dir(modul): doc_string = modul.__getattribute__(d).__doc__ or '' if word_lc in d.lower() or word_lc in doc_string.lower(): print('=>', d) print(doc_string) print('-' * 10)
Line 4 looks interesting. What we do here, is that we take a function name (i.e. 'zfill'
) that we get from dir(modul)
as a string and we convert it into an actual function. Then we call its __doc__
to get the docString. In some cases the docString is not defined and the modul.__getattribute__(d).__doc__
will simply return None
. To avoid getting
TypeError: argument of type 'NoneType' is not itterable
when searching for our word
, we need to guarantee that a string is returned. Therefore in this code if 1st part returns None
, the 2nd part makes sure that at least an empty string is returned.
Then in line 5, we check if our word
is in the name or in the docString.
We can simply use it as:
my_string = 'Hey!' doc_dir(my_string, 'lower') => capitalize Return a capitalized version of the string. More specifically, make the first character have upper case and the rest lower case. ---------- => islower Return True if the string is a lowercase string, False otherwise. A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string. ---------- => istitle Return True if the string is a title-cased string, False otherwise. In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones. ---------- => lower Return a copy of the string converted to lowercase. ---------- => swapcase Convert uppercase characters to lowercase and lowercase characters to uppercase. ---------- => title Return a version of the string where each word is titlecased. More specifically, words start with uppercased characters and all remaining cased characters have lower case. ----------