Reading Time: 25 minutes
Page #9
Using builtin function issubclass()
The builtin function issubclass(subClass, superClass) returns True if the class subClass is a subclass of the class superClass, else it returns False.
Help on built - in function issubclass in module builtins: |
Return whether class C is a subclass (i.e., a derived class ) of class B. |
When using a tuple as the second argument issubclass (X, (A, B, ...)), |
is a shortcut for issubclass (X, A) or issubclass (X, B) or ... (etc.). |
>>> class Person( object ): pass |
>>> class Man(Person): pass |
>>> class Woman(Person): pass |
>>> issubclass (Man, Person) |
>>> issubclass (Man, object ) |
>>> issubclass (Woman, Man) |
If you are uncertain about the exact parent class of a subclass, you can insert all the likely classes in the form of a tuple. The issubclass() function will return True if the class specified is a subclass of either of the specified classes.
>>> issubclass ( Man, (Person, Woman) ) |
>>> issubclass ( Person, (Man, Woman) ) |
Keep in mind that all builtin-classes, data types, user-defined classes inherit from the class called object.
Using a buffer while manipulating files
A buffer stores a chunk of data from the Operating System's file stream until it is consumed, at which point more data is brought into the buffer. The reason that is good practice to use buffers is that interacting with the raw stream might have high latency i.e. considerable time is taken to fetch data from it and also to write to it. Let's take an example.
Let's say you want to read 100 characters from a file every 2 minutes over a network. Instead of trying to read from the raw file stream every 2 minutes, it is better to load a portion of the file into a buffer in memory, and then consume it when the time is right. Then, next portion of the file will be loaded in the buffer and so on.
The following code snippet reads a file containing 196 bytes, with a buffer of 20 bytes, and writes to a file, 20 bytes at a time.
inputFile = open ( 'fileToBeReadFrom.txt' , 'r' ) |
outputFile = open ( 'fileToBeWrittenInto.txt' , 'a' ) |
buffer = inputFile.read(buffersize) |
print ( str (counter) + " " ) |
buffer = inputFile.read(buffersize) |
To learn more about buffers, check out this link.
Reloading a module
There are occasions when you have changed the code of a module, and you want the changes to reflect without having to relaunch the interpreter or restart the server. Python doesn't support this by default. However, the reload() function of importlib standard library helps you to do just that.
>>> importlib. reload (foo) |
<module 'foo' from 'complete_path_to_foo.py' > |
from importlib import reload |
Logging using logging module
The standard library logging helps you to log events of different severities to a file or the standard output in interpreter. This is particularly helpful in large applications where you would like to record events as they occur for future reference. Expand the following snippet for an example of logging. To know more about the logging module, I suggest you view this article.
03 | >>> logging.basicConfig(level = 10 , format = '%(asctime)s %(levelname)s %(message)s' ) |
05 | >>> logging.debug( 'A debugging message here.' ) |
06 | 2017 - 02 - 18 04 : 40 : 38 , 420 DEBUG A debugging message here. |
07 | >>> logging.info( 'An informative message here.' ) |
08 | 2017 - 02 - 18 04 : 40 : 41 , 274 INFO An informative message here. |
09 | >>> logging.warning( 'A warning message here.' ) |
10 | 2017 - 02 - 18 04 : 40 : 42 , 773 WARNING A warning message here. |
Making a variable global: global keyword
There will be instances where you are declaring an object inside a confined piece of code, and you will need the object outside it as well. You can use the global keyword for this.
Traceback (most recent call last): |
NameError: name 'name' is not defined |
Creating random objects of subclasses of a superclass
Using the random module and Generators, we can have Python make random objects of subclasses of a superclass.
>>> class Wheat(Crop): pass |
>>> class Corn(Crop): pass |
>>> class Tomato(Crop): pass |
>>> def cropGenerator(numberOfInstancesToCreate): |
crops = Crop.__subclasses__() |
for number in range (numberOfInstancesToCreate): |
yield random.choice(crops)() |
>>> cropGeneratorObject = cropGenerator( 5 ) |
>>> for cropObject in cropGeneratorObject: |
<__main__.Corn object at 0x02E7E950 > |
<__main__.Corn object at 0x02E65BB0 > |
<__main__.Wheat object at 0x02B09EB0 > |
<__main__.Tomato object at 0x02E65BB0 > |
<__main__.Corn object at 0x02B09EB0 > |
Removing duplicate items from lists
A simple way to remove duplicate items from a list is to cast it to a set, and then back to a list using the constructors of builtin set and list classes.
>>> aList = [ 1 , 2 , 3 , 1 , 2 , 3 , 4 , 5 ] |
Implementing Caesar Cipher in Python
Julius Caesar was a Roman dictator who came up with a clever way of passing confidential information to his generals without having to worry about it falling into the wrong hands. He shifted each letter in the message by a fixed shift value i.e. if the shift value was 3, a became d, f became i and so on. He would leave the numbers and other characters untouched. His generals would only need the shift value to decode their emperor's message. Later on, this cryptography technique came to be known as Caesar Cipher.
You can implement Caesar Cipher in Python using the builtin ord(), chr() functions, a for loop, a couple of if-else constructs.
The ord() function returns the Unicode value of the character supplied to it. It is inverse of builtin chr() function which returns the character in the Unicode character set, denoted by the number provided to it.
Expand the following code snippet for the script. You can run it online here.
08 | message = input ( "Enter the message you want to encrypt: " ) |
09 | shiftValue = int ( input ( "Enter the places you want the characters to be shifted by: " )) |
21 | for character in message: |
22 | if character > = "a" and character < = "z" : |
23 | position = ord (character) - ord ( "a" ) |
24 | position = (position + shiftValue) % 26 |
25 | newCharacter = chr (position + ord ( "a" )) |
26 | newMessage = newMessage + newCharacter |
27 | elif character > = "A" and character < = "Z" : |
28 | position = ord (character) - ord ( "A" ) |
29 | position = (position + shiftValue) % 26 |
30 | newCharacter = chr (position + ord ( "A" )) |
31 | newMessage = newMessage + newCharacter |
33 | newMessage = newMessage + character |
36 | print ( "\nHere is the encypted message: \n\n" + newMessage) |
High-level file operations using shutil module
The standard library module shutil facilitates basic operations on files and directories. You can copy files and directories, move them, remove them, pretty much everything you would like to do with them. Following is a list of frequently used functions of the shutil module:
shutil.copy(source,destination) |
shutil.copymode(source,destination) |
shutil.copystat(source, destination) |
shutil.copy2(source, destination) |
shutil.move(source, destination) |
shutil.copytree(source, destination) |
Regular Assignment, Shallow copy & Deep Copy
There are three ways to copy objects in Python: assignment, shallow copy & deep copy.
- Regular assignment points the new variable towards the original object. Let's use the builtin id() function prove this. The id() function returns the object's memory address.
objThree = [objOne, objTwo] |
print ( id (objThree) = = id (objFour) ) |
print ( id (objThree[ 0 ]) = = id (objFour[ 0 ]) ) |
- Shallow copy
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Python Documentation
objFour = copy.copy(objThree) |
print ( id (objThree) = = id (objFour) ) |
print ( id (objThree[ 0 ]) = = id (objFour[ 0 ]) ) |
- Deep Copy
objFour = copy.deepcopy(objThree) |
print ( id (objThree) = = id (objFour) ) |
print ( id (objThree[ 0 ]) = = id (objFour[ 0 ]) ) |
See also: 50+ Know-How(s) Every Pythonista Must Know