Missing Functions on TB:1

The Missing Functions – (those not covered in Big Daddy’s toolbox)
Big Daddy’s General Python Toolbox is designed to be a reminder reference for early to intermediate programmers. A number of lesser used functions were not included – some due to space constraints. Here we account for those that we can to fill that gap.

__import__() – python.org advises against use – very advanced function

*note: in the line below “source” is purposely misspelled as “sorce” so Wordprss won’t freak out
classmethod()subject open to attributed contribution, email john@johnoakey.com
memoryview() – we can not fathom why anyone would need it
object() – a base for all classes but difficult to understand any practical application
property() – advanced beyond the scope of this website
staticmethod() – a function decorator – nothing to worry a pretty little head about
super() – if you are reading this, Georgia Tech may have a scholarship for waiting for you. However, see below.
vars()see below
exec()
Attribute group of commandssee below
The following are treated as a group:
delattr()
setattr()
getattr()
hasattr()

A few notes:

bytearray([sorce[, encoding[, errors]]])   – an array of bytes 0<=x<=256
bytearray “does” three entirely different things depending on how it is initialized: string, integer or iterable as source

string – requires encoding (‘utf-8’ is default and ‘ascii’ is the other one you have heard of), string is converted to bytes
integer – array initialized with “integer” number of nulls
iterable – must be integers which are initial content

about 1 zillion methods! Just a few that might be more helpful:
bytearray.count(sub[, start[, end]]) – Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

bytearray.find(sub[, start[, end]])
bytearray.replace(old, new[, count])¶
bytearray.rfind(sub[, start[, end]])
bytearray.center(width[, fillbyte])¶
bytearray.ljust(width[, fillbyte])
bytearray.lstrip([chars])
bytearray.rjust(width[, fillbyte])
bytearray.split(sep=None, maxsplit=-1)
bytearray.isalnum()
bytearray.isalpha()
bytearray.isdigit()
bytearray.splitlines(keepends=False)

 

complex([real[,imag]]) – Since you can’t take the square root of a complex number, somebody with way too much time on their hands invented a way to conceptually represent the idea with the form a+bi where a and b are real numbers and i (for imaginary) is the quantity representing the square root of a negatime number. Complex requires you use “j” in the following. The function does two things.
First, it returns a complex number if the only parameter is a number or a string:
complex (123456)
or
complex(‘123456’)
…both yield: (123456+0j)
Second, if given two parameters, a real part and then an imaginary part, it returns a complex number:
complex(3,9j)
…will yield: (-6+0j)
Nobody really needs this, but it is a subject open to attributed contribution, email john@johnoakey.com

Attribute group of commands : delattr(), setattr(), getattr().dir()
This is one of those “a demo is worth a thousand words” thing. Let’s create a class called “Fish” and a couple of instances of our new class that will have a few “attributes” we can work with:

class Fish:
    def __init__(self,species,waters):
        self.species = species
        self.waters = waters
        Fish.catchtype=’sport’
Als_Fish=Fish(“Bass”,”fresh”)
Bobs_Fish=Fish(“Trout”,’salt’)

Find all the attributes of our object with the dir() command:

print(“Als_Fish has the following attributes which we fin with the ‘dir()’ command. \n”)
print(dir(Als_Fish))

Specifically get the ‘catchtype’ value for the Fish class instance called Als_Fish with the ‘getattr’ command:

print(“We use getattr to get the ‘catchtype’ attribute value for Als_Fish. We retrieve: “,end=” “)
AlsType = getattr(Als_Fish, ‘catchtype’)
print(AlsType)

…change it with the ‘setattr’ command

print(“We can change it using the ‘setattr()’ command.”)
setattr(Als_Fish, ‘catchtype’, ‘Dinner’)

…..and get it again to make sure it changed.

print(“…and we reacquire the ‘catchtype’ to see if it is changed. Now it is: “)
print(getattr(Als_Fish, ‘catchtype’))
print(‘Yum!’)

Here is the whole example demo for you to copy and paste:

class Fish:
    def __init__(self,species,waters):
        self.species = species
        self.waters = waters
        Fish.catchtype='sport'
Als_Fish=Fish("Bass","fresh")
Bobs_Fish=Fish("Trout",'salt')

print("Als_Fish has the following attributes which we fin with the 'dir()' command. \n")
print(dir(Als_Fish))

print("We use getattr to get the 'catchtype' attribute value for Als_Fish. We retrieve: ",end=" ")
AlsType = getattr(Als_Fish, 'catchtype')
print(AlsType)

print("We can change it using the 'setattr()' command.")
setattr(Als_Fish, 'catchtype', 'Dinner')

print("...and we reacquire the 'catchtype' to see if it is changed.  Now it is: ")
print(getattr(Als_Fish, 'catchtype'))
print('Yum!')

locals() – returns a dictionary of local symbols and variables. For example when print(locals()) is run as the last line of the program above, it returns:
{‘Als_Fish’: , ‘__name__’: ‘__main__’, ‘__spec__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘__file__’: ‘D:\\Program Files (x86)\\Python\\TempTest\\attributes.py’, ‘AlsType’: ‘sport’, ‘__doc__’: None, ‘Fish’: <class ‘__main__.Fish’>, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘__package__’: None, ‘Bobs_Fish’: }

Super – Yields a “proxy object that delegates method calls to a parent or sibling class of type.” The Python docs for 3.6 contain a link to  https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ , an article by Raymond Hettinger.  Guys this smart should not be allowed out by themselves. Here is an example that demos the common use for super() along with calling a couple of window manager commands:

import tkinter as tk
class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()

# create the application
myapp = App()

#
# here are method calls to the window manager class
#
myapp.master.title("My Do-Nothing Application")
myapp.master.maxsize(1000, 400)

# start the program
myapp.mainloop()

Vars() – returns the __dict__ attribute of any object that has one. Like locals() but updateable.

Zip(iterables) – Thinking of a table, zip() takes the values in column objects and merges them into row objects or records. Stated another way, zip() takes multiple lists and merges them into a list of tuples containing position correlated objects.

Men=['Bob','Ted','Bill','Fred']
Women=['Carol','Alice','Becky','Dallas']
Couples=zip(Men,Women)
mylist=(list(Couples))
print (mylist)

…yields
[(‘Bob’, ‘Carol’), (‘Ted’, ‘Alice’), (‘Bill’, ‘Becky’), (‘Fred’, ‘Dallas’)]

.zfill(width)    zfill was on earlier TB:1 reference sheets but got bumped off to add more important stuff. It produces a copy of the string left filled with ASCII ‘0’ digits to make a string of length width. A leading sign prefix (‘+’/’-‘) is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(str).