Site Sponsors:
Pythonic Content Generation & Yield-based Enumeration 
Very few jewels in Python's crown sparkle so brilliantly as the gem of Content Management.

Using 'with'


While ever-confusing to those who know another programming language, those interested in demonstrating genuine Pythonic mastery simply love to make their classes operate like they can "with files!"
        with open("/Projects.txt", "r") as fh:
line = fh.readline()
while len(line) is not 0:
row = line.split('|')
if len(row) is 2:
self._add(row[0], row[1])
line = fh.readline()

While tricky enough to get working properly, the key to using Python's 'with' keyword is understanding the meta-methods (or "magic methods") that are invoked beind the scenes:
    def  __enter__(self):
with open(self.projectFile, "r") as fh:
lines = fh.readlines()
for line in lines:
row = line.split('|')
if len(row) is 2:
self._add(row[0], row[1])
return self

def __exit__(self, type, value, tb):
self.files.clear()
return False


Using 'yield'


Of course once we have generated our content, what could be more Pythonic than to use Pythons 'yield' capability to serve-up your managed 'info?
    def enumerate(self):
for result in self.files:
yield result[0], result[1]


Real-World Example


The objective was to load file content every time its representational class was used:
""" Context manager designed to serve-up the script titles + file names
as present in an external text-file definition:

Projects.txt Example:

Common Header File | C:/Users/Randall/Desktop/ProdSet/NewGnuActivities/Module3000/Cpp3000d01s01p01/SloType/01_era_hpp
The File Header | C:/Users/Randall/Desktop/ProdSet/NewGnuActivities/Module3000/Cpp3000d01s01p01/SloType/02_file_hpp
The File Implementation | C:/Users/Randall/Desktop/ProdSet/NewGnuActivities/Module3000/Cpp3000d01s01p01/SloType/03_file_cpp
The Test Driver | C:/Users/Randall/Desktop/ProdSet/NewGnuActivities/Module3000/Cpp3000d01s01p01/SloType/04_main_cpp
The Make File | C:/Users/Randall/Desktop/ProdSet/NewGnuActivities/Module3000/Cpp3000d01s01p01/SloType/05_makefile
"""

class ProjectReader:

""" Project file content must be in the above format. """
def __init__(self, projectFile):
self.projectFile = projectFile
self.files = []

""" Internal array is emptied & filled on-demand. Needs to be private. """
def _add(self, title, file_name):
row = [title.strip(), file_name.strip()]
self.files.append(row)

""" Reload the project file each and every time we are asked to manage the File's content """
def __enter__(self):
with open(self.projectFile, "r") as fh:
lines = fh.readlines()
for line in lines:
row = line.split('|')
if len(row) is 2:
self._add(row[0], row[1])
return self

""" Enumerate through the Project File's content. """
def enumerate(self):
for result in self.files:
yield result[0], result[1]

""" Be sure to clean-up after any content-managed activity """
def __exit__(self, type, value, tb):
self.files.clear()
return False # Exceptions okay



if __name__ == "__main__":
with ProjectReader("./Projects.txt") as inst:
for title, file in inst.enumerate():
print (title, file, sep=' = ')

I hope you will find the example useful! -If this type of mastery is what you are looking for, then you can learn more on-line today.



[ view entry ] ( 217 views )   |  permalink  |  related link

<<First <Back | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | Next> Last>>