Commit b1867470 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

9780596001889

0 → 120000
+1 −0
Changes for 9780596001889: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
9780596001889
 No newline at end of file

README.md

0 → 100644
+15 −0
Changes for README.md: 15 added lines, 0 removed lines.
Original line number Diff line number Diff line
## Example files for the title:  
  
# Python in a Nutshell, by Alex Martelli
  
[![Python in a Nutshell, by Alex Martelli](http://akamaicovers.oreilly.com/images/9780596001889/cat.gif)](https://www.safaribooksonline.com/library/view/title/0596001886//)
  
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
  
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
  
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
  
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
  
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.

logo.png

0 → 100644
+2.3 KiB
Loading image diff...
+277 −0
Changes for pythonian-examples/ch04.code: 277 added lines, 0 removed lines.
Original line number Diff line number Diff line
letter = 'c'
print "give me a", letter, "..."           # prints: give me a c ...
answer = 42
print "the answer is:", answer             # prints: the answer is: 42

----------

if x < 0: print "x is negative"
elif x % 2: print "x is positive and odd"
else: print "x is even and non-negative"

----------

if x < 0:
    print "x is negative"
elif x % 2:
    print "x is positive and odd"
else:
    print "x is even and non-negative"

----------

count = 0
while x > 0:
    x = x // 2            # truncating division
    count += 1
print "The approximate log2 is", count

----------

for letter in "ciao":
    print "give me a", letter, "..."

----------

for key, value in d.items():
    if not key or not value: del d[key]    # keep only true keys and values

----------

for x in someseq:
    process(x)
print "Last item processed was", x

----------

result1 = [x+1 for x in some_sequence]

----------

result2 = []
for x in some_sequence:
    result2.append(x+1)

----------

result3 = [x+1 for x in some_sequence if x>23]

----------

result4 = []
for x in some_sequence:
    if x>23:
        result4.append(x+1)

----------

result5 = [x+y for x in alist for y in another]

----------

result6 = []
for x in alist:
    for y in another:
        result6.append(x+y)

----------

while True:                     # this loop can never terminate naturally
    x = get_next()
    y = preprocess(x)
    if not keep_looping(x, y): break
    process(x, y)

----------

for x in some_container:
    if not seems_ok(x): continue
    lowbound, highbound = bounds_to_test()
    if x<lowbound or x>=highbound: continue
    if final_check(x):
        do_processing(x)

----------

for x in some_container:
    if seems_ok(x):
        lowbound, highbound = bounds_to_test()
        if lowbound<=x<highbound:
            if final_check(x):
                do_processing(x)

----------

for x in some_container:
    if is_ok(x): break             # item x is satisfactory, terminate loop
else:
    print "Warning: no satisfactory item was found in container"
    x = None

----------

if condition1(x):
    process1(x)
elif x>23 or condition2(x) and x<5:
    pass                                # nothing to be done in this case
elif condition3(x):
    process3(x)
else:
    process_default(x)

----------

inverse = {sin:asin, cos:acos, tan:atan, log:exp}
for f in inverse.keys(): inverse[inverse[f]] = f

----------

def double(x):
    return x*2

----------

def f(x, y=[]):
    y.append(x)
    return y
print f(23)                # prints: [23]
prinf f(42)                # prints: [23,42]

----------

def f(x, y=None):
    if y is None: y = []
    y.append(x)
    return y
print f(23)                # prints: [23]
prinf f(42)                # prints: [42]

----------

def sum(*numbers):
    result = 0
    for number in numbers: result += number
    return result
print sum(23,42)           # prints: 65

----------

def adict(**kwds): return kwds
print adict(a=23, b=42)    # prints: {'a':23, 'b':42}

----------

def adict(**kwds):
    return kwds

----------

def sum(*numbers):
    '''Accept arbitrary numerical arguments and return their sum.

    The arguments are zero or more numbers.  The result is their sum.'''

    result = 0
    for number in numbers: result += number
    return result

----------

def counter():
    counter.count += 1
    return counter.count
counter.count = 0

----------

def f(x, y):
    x = 23
    y.append(42)
a = 77
b = [99]
f(a, b)
print a, b                # prints: 77 [99, 42]

----------

def divide(divisor, dividend): return dividend // divisor
print divide(12,94)                         # prints: 7
print divide(dividend=94, divisor=12)       # prints: 7

----------

def f(middle, begin='init', end='finis'): return begin+middle+end
print f('tini', end='')                     # prints: inittini

----------

def sum(*numbers):
    result = 0
    for number in numbers: result += number
    return result
print sum(*d.values())

----------

_count = 0
def counter():
    global _count
    _count += 1
    return _count

----------

def percent1(a, b, c):                # works with any version
    def pc(x, total=a+b+c): return (x*100.0) / total
    print "Percentages are ", pc(a), pc(b), pc(c)

----------

def percent2(a, b, c):                # needs 2.2 or "from future import"
    def pc(x): return (x*100.0) / (a+b+c)
    print "Percentages are", pc(a), pc(b), pc(c)

----------

def make_adder_1(augend):             # works with any version
    def add(addend, _augend=augend): return addend+_augend
    return add

----------

def make_adder_2(augend):             # needs 2.2 or "from future import"
    def add(addend): return addend+augend
    return add

----------

aList = [1,2,3,4,5,6,7,8,9]
low = 3
high = 7
filter(lambda x,l=low,h=high: h>x>l, aList)     # returns: [4, 5, 6]

----------

aList = [1,2,3,4,5,6,7,8,9]
low = 3
high = 7
def test(value, l=low, h=high):
    return h>value>l
filter(test, aList)                             # returns: [4, 5, 6]

----------

def updown(N):
    for x in xrange(1,N): yield x
    for x in xrange(N,0,-1): yield x
for i in updown(3): print i                   # prints: 1 2 3 2 1

----------

def frange(start, stop, step=1.0):
    while start < stop:
        yield start
        start += step


+380 −0
Changes for pythonian-examples/ch05.code: 380 added lines, 0 removed lines.
Original line number Diff line number Diff line
class C1:
    x = 23
print C1.x                               # prints: 23

----------

class C2: pass
C2.x = 23
print C2.x                               # prints: 23

----------

C1.y = 45
C1.__dict__['z'] = 67
print C1.x, C1.y, C1.z                   # prints: 23, 45, 67

----------

class C3:
    x = 23
    y = x + 22                         # must use just x, not C3.x

----------

class C4:
    x = 23
    def amethod(self):
        print C4.x                     # must use C4.x, not just x

----------

class C5:
    def hello(self):
        print "Hello"

----------

anInstance = C5()

----------

class C6:
    def __init__(self,n):
        self.x = n

----------

anotherInstance = C6(42)

----------

anInstance.hello()                         # prints: Hello
print anotherInstance.x                    # prints: 42

----------

class C7: pass
z = C7()
z.x = 23
print z.x                                   # prints: 23

----------

z.y = 45
z.__dict__['z'] = 67
print z.x, z.y, z.z                         # prints: 23, 45, 67

----------

class SpecialCase:
    def amethod(self): print "special"
class NormalCase:
    def amethod(self): print "normal"
def appropriateCase(isnormal=1):
    if isnormal: return NormalCase()
    else: return SpecialCase()
aninstance = appropriateCase(isnormal=0)
aninstance.amethod()                        # prints "special", as desired

----------

class B:
    a = 23
    b = 45
    def f(self): print "method f in class B"
    def g(self): print "method g in class B"
class C(B):
    b = 67
    c = 89
    d = 123
    def g(self): print "method g in class C"
    def h(self): print "method h in class C"
x = C()
x.d = 77
x.e = 88

----------

def make_adder_as_closure(augend):
    def add(addend, _augend=augend): return addend+_augend
    return add

----------

def make_adder_as_bound_method(augend):
    class Adder:
        def __init__(self, augend): self.augend = augend
        def add(self, addend): return addend+self.augend
    return Adder(augend).add

----------

def make_adder_as_callable_instance(augend):
    class Adder:
        def __init__(self, augend): self.augend = augend
        def __call__(self, addend): return addend+self.augend
    return Adder(augend)

----------

class Base1:
    def amethod(self): print "Base1"
class Base2(Base1): pass
class Base3:
    def amethod(self): print "Base3"
class Derived(Base2, Base3): pass
aninstance = Derived()
aninstance.amethod()                    # prints: "Base1"

----------

class B:
    a = 23
    b = 45
    def f(self): print "method f in class B"
    def g(self): print "method g in class B"
class C(B):
    b = 67
    c = 89
    d = 123
    def g(self): print "method g in class C"
    def h(self): print "method h in class C"

----------

class Base:
    def greet(self, name): print "Welcome ", name
class Sub(Base):
    def greet(self, name):
        print "Well Met and",
        Base.greet(self, name)
x = Sub()
x.greet('Alex')

----------

class Base:
    def __init__(self):
        self.anattribute = 23
class Derived(Base):
    def __init__(self):
        Base.__init__(self)
        self.anotherattribute = 45

----------

class AClass(object):
    def astatic(): print 'a static method'
    astatic = staticmethod(astatic)
anInstance = AClass()
AClass.astatic()                    # prints: a static method
anInstance.astatic()                # prints: a static method

----------

class ABase(object):
    def aclassmet(cls): print 'a class method for', cls.__name__
    aclassmet = classmethod(aclassmet)
class ADeriv(ABase): pass
bInstance = ABase()
dInstance = ADeriv()
ABase.aclassmet()               # prints: a class method for ABase
bInstance.aclassmet()           # prints: a class method for ABase
ADeriv.aclassmet()              # prints: a class method for ADeriv
dInstance.aclassmet()           # prints: a class method for ADeriv

----------

class C(object):
    def __init__(self): pass
    # rest of class body omitted

----------

x = C.__new__(C, 23)
if isinstance(x, C): C.__init__(x, 23)

----------

class Singleton(object):
    _singletons = {}
    def __new__(cls, *args, **kwds):
        if not cls._singletons.has_key(cls):
            cls._singletons[cls] = object.__new__(cls)
        return cls._singletons[cls]

----------

class Rectangle(object):
    def __init__(self, width, heigth):
        self.width = width
        self.heigth = heigth
    def getArea(self):
        return self.width * self.heigth
    area = property(getArea, doc='area of the rectangle')

----------

attrib = property(fget=None, fset=None, fdel=None, doc=None)

----------

class Rectangle:
    def __init__(self, width, heigth):
        self.width = width
        self.heigth = heigth
    def getArea(self):
        return self.width * self.heigth
    def __getattr__(self, name):
        if name=  ='area': return self.getArea()
        raise AttributeError, name
    def __setattr__(self, name, value):
        if name=  ='area':
            raise AttributeError, "can't bind attribute"
        self.__dict__[name] = value

----------

class OptimizedRectangle(Rectangle):
    __slots__ = 'width', 'heigth'

----------

class listNoAppend(list):
    def __getattribute__(self, name):
        if name =  = 'append': raise AttributeError, name
        return list.__getattribute__(self, name)

----------

class AttributeWatcher:
    def __init__(self):
        # note the caution to avoid triggering __setattr__, and the
        # emulation of Python's name-mangling for a private attribute
        self.__dict__['_AttributeWatcher__mydict']={}
    def __getattr__(self, name):
        # as well as tracing every call, for demonstration purposes we
        # also fake "having" any requested attribute, EXCEPT special
        # methods (__getattr__ is also invoked to ask for them: check by
        # trying a few operations on an AttributeWatcher instance).
        print "getattr", name
        try: return self.__mydict[name]
        except KeyError:
            if name.startswith('__') and name.endswith('__'):
                raise AttributeError, name
            else: return 'fake_'+name
    def __setattr__(self, name, value):
        print "setattr", name, value
        self.__mydict[name] = value
    def __delattr__(self, name):
        print "delattr", name
        try: del self.__mydict[name]
        except KeyError: pass

----------

def fakeGetItem(idx): return idx
class Classic: pass
c = Classic()
c.__getitem__ = fakeGetItem
print c[23]                       # prints: 23
class NewStyle(object): pass
n = NewStyle()
n.__getitem__ = fakeGetItem
print n[23]                       # results in: 
# Traceback (most recent call last):
#   File "<stdin>", line 1, in ?
# TypeError: unindexable object

----------

class A(object):
    def met(self): 
        print 'A.met'
class B(A):
    def met(self): 
        print 'B.met'
        A.met(self)
class C(A):
    def met(self): 
        print 'C.met'
        A.met(self)
class D(B,C):
    def met(self): 
        print 'D.met'
        B.met(self)
        C.met(self)

----------

class A(object):
    def met(self): 
        print 'A.met'
class B(A):
    def met(self): 
        print 'B.met'
        super(B,self).met()
class C(A):
    def met(self): 
        print 'C.met'
        super(C,self).met()
class D(B,C):
    def met(self): 
        print 'D.met'
        super(D,self).met()

----------

class C:
    def __getslice__(self, i, j): print 'getslice', i, j
    def __getitem__(self, index): print 'getitem', index
x = C()
x[12:34]
x[56:78:9]

----------

for z in x:
    if y=  =z: return True
return False

----------

class Classic: pass
class Newstyle(object): pass
print type(Classic)                  # prints: <type 'class'>
print type(Newstyle)                 # prints: <type 'type'>

----------

class MyMeta(type):
    def __str__(cls): return "Beautiful class '%s'"%cls.__name__
class MyClass:
    __metaclass__ = MyMeta
x = MyClass()
print type(x)

----------

class Bunch(object):
    def __init__(self, **fields): self.__dict__ = fields
p = Bunch(x=2.3, y=4.5)
print p                     # prints: <__main__.Bunch object at 0x00AE8B10>

----------

class Point(MetaBunch):
    """ A point has x and y coordinates, defaulting to 0.0, and a color,
        defaulting to 'gray' -- and nothing more, except what Python and
        the metaclass conspire to add, such as __init__ and __repr__
    """
    x = 0.0
    y = 0.0
    color = 'gray'
# example uses of class Point
q = Point()
print q                     # prints: Point()
p = Point(x=1.2, y=3.4)
print p                     # prints: Point(y=3.399999999, x=1.2)
Loading