Last active
September 4, 2019 09:43
-
-
Save arangates/ef16159e064146ae19263e1e09623535 to your computer and use it in GitHub Desktop.
Reference : https://wiki.python.org/moin/Generators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# <------------------------NORMAL FUNCTION --------------------------------> | |
# # Build and return a list | |
# def getKeys(data): | |
# return list(data.keys()) | |
# obj = { 'bar': "hello", 'baz': "world" } | |
# keys_list = getKeys(obj) | |
# <------------------------BEHIND THE SCENE -------------------------------> | |
# # Using the generator pattern (an iterable) | |
# class getKeys(obj): | |
# print(obj.keys()) | |
# def __init__(self, obj): | |
# self.obj = obj | |
# def __iter__(self): | |
# return self | |
# # Python 3 compatibility | |
# def __next__(self): | |
# return self.next() | |
# def next(self): | |
# if self.obj: | |
# return list(obj.keys()) | |
# else: | |
# raise ValueError('Dear Lord,Gimme object') | |
# data = {'bar': "hello", 'baz': "world"} | |
# keys_list = getKeys(data) | |
# print(keys_list) | |
# <------------------------GENERATOR PATTERN -------------------------------> | |
# a generator that yields items instead of returning a list | |
def getKeys(obj): | |
if (type(obj) is dict): | |
yield [obj.keys()] | |
else: | |
raise ValueError('Dear Lord,Gimme object') | |
data = {'bar': "hello", 'baz': "world"} | |
keys_list = getKeys(data) | |
print(list(keys_list)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment