Rezha Julio

The Hard Coded Chemist

There is more to copying

An assignment only creates a “binding” (an association) between a name and a “target” (object of some type). A copy is sometimes necessary so you can change the value of one object without changing the other (when two names are pointing to the same object). # Assignment: bind the name y to # the list [1, 2]. y = [1, 2 ] # Create another binding - # bind the name x to the same # object that y is currently bound to. Continue reading

Implementing weak references in Python

Normal Python references to objects increment the object’s reference count thus preventing it from being garbage collected. If a user desires creating weak references, the weakref module can be used: import weakref class Rezha(object): pass To create a weak reference, the ref class is used: # object instance rezha = Rezha() # weak reference to our object r = weakref.ref(rezha) Then, you can call the reference object: print(r) # <weakref at 0x01414E40; to 'Rezha'. Continue reading

Next, Function or Method ?

While in Python 2 it was possible to use both the function next() and the .next() method to iterate over the resulting values of a generator, the later has been removed with the introduction of Python 3. Consider the sample generator: def sample_generator(): yield "a" yield "b" yield "c" In Python 2: a = sample_generator() print(next(a)) # prints 'a' print( # prints 'b' But in Python 3: print(next(a)) # prints 'a' print(a. Continue reading

Generator Expressions

Generator expressions are a high performance and memory efficient generalization of list comprehensions and generators. Imagine we want to sum up all even number ranging from 1 to 100. Using list comprehension: even_sum = sum([x for x in range(1, 100) if x % 2 == 0]) print(even_sum) #2450 This will prove inefficient in the case of a large range because it first creates a list, it iterates over it and then returns the sum. Continue reading

Yield Keyword

The yield keyword is fundamental to the creation of generators. Consider the following generator function: def createGenerator(): print('Initial call') yield '1' print('Second call') yield '2' a = createGenerator() Calling the createGenerator() function will create a generator object stored as a. Note that the code inside the generator function will not be run yet. print(next(a)) # Initial call # 1 The first time the generator object is iterated over (in a loop or with next()), the function code will be run from the start until the first yield. Continue reading
Older posts Newer posts