Poky: cow. py Analysis

Source: Internet
Author: User

# Ex: TS = 4: Sw = 4: STS = 4: et
#-*-Tab-width: 4; C-Basic-offset: 4; indent-Tabs-mode: Nil -*-
#
# This is a copy on write dictionary and set which abuses classes to try and be nice and fast.
#
# Copyright (c) 2006 TIM amsell
#
# This program is free software; you can redistribute it and/or modify
# It under the terms of the GNU General Public License version 2
# Published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# But without any warranty; without even the implied warranty
# Merchantability or fitness for a special purpose. See
# GNU General Public License for more details.
#
# You shoshould have written ed a copy of the GNU General Public License along
# With this program; if not, write to the Free Software Foundation, inc .,
#51 Franklin Street, fifth floor, Boston, MA 02110-1301 USA.
#
# Please note:
# Be careful when using mutable types (ie dict and lists)-operations involving these are slow.
# Assign a file to _ warn _ to get warnings about slow operations.
#

From _ future _ import print_function
Import copy
Import types
Immutabletypes = (
Types. nonetype,
Bool,
Complex,
Float,
Int,
Long,
Tuple,
Frozenset,
Basestring
)
# Variable-type suffixes, such as dictionaries.
Mutable = "_ mutable __"
# Cowmeta is a metaclass (Meta class ).
Class cowmeta (type ):
Pass
# Why do we need to define a metadata class in this place. Usage of metadata:
# Only when you want to run code on a derived class. Users do not want to be noticed. To use the metadatabase.
# Here. The Meta class replaces the common built-in methods. Replace the built-in method. This is because you need to operate your dictionary. This operation requires some of its own actions.
# Because built-in methods are called implicitly. Therefore, you must use your own methods to implicitly call your own dictionary methods when using them.
# The previous _ is private. Users are not allowed to call the API.
Class cowdictmeta (cowmeta ):
_ Warn _ = false
_ Hasmutable _ = false
_ Marker _ = tuple ()
# The print function calls this method.
# Why is CLS used here? This can be understood as a class, which indicates the behavior of the class. Of course, this is just a form.
Def _ STR _ (CLS ):
Print ("str ")
# Fixme: I have magic numbers!
Return "<cowdict level: % I current keys: % I>" % (CLS. _ count __, Len (CLS. _ dict _)-3)
# If _ STR _ does not exist, python will switch to _ repr _. Otherwise, no. _ Repr _ is used for interactive mode, such as> X. _ STR _ is used to display data on the terminal in the program. For example, print x
_ Repr _ = _ STR __
# Use a function to create a class.
Def cow (CLS ):
Print ("cow ")
Class C (CLS ):
_ Count _ = Cls. _ count _ + 1
Return C
# The copy method calls this function after the class is instantiated. For example, a = cowdictmeta ()
Copy = cow
# This is called when function () is used.
_ Call _ = cow
# Equivalent. Cls. Key = vaule. That is, put the value in a dictionary.
Def _ setitem _ (CLS, key, value ):
# Use isinstance to determine whether a type is of the same type. The key point is that immutabletypes must be a tuples.
If not isinstance (value, immutabletypes ):
If not isinstance (value, cowmeta): # indicates a variable type. For example, the dictionary type. _ Dict ____ mutable __
Cls. _ hasmutable _ = true
Key + = mutable
Setattr (CLS, key, value)

# Undoubtedly, a variable type value is obtained,
Def _ getmutable _ (CLS, key, readonly = false ):
Nkey = Key + mutable

Try:

# Here we return the value of the key value nkey in Cls. Everyone knows this. The problem arises.

# Return. Cls. _ dict _ [nkey] What is the difference between getattr (CLS, nkey?

# Yes here, and it is very large. Because CLS is passed in by an instance, CLS. _ dict _ is only the dictionary space of the current instance. If getattr (CLS, nkey) indicates that the current instance does not have an nkey, it will be searched through the class mechanism to inherit the class dictionary space. Or B = A. Copy () in this example, the dictionary space of A is searched.

Return Cls. _ dict _ [nkey]
Failed t keyerror:
Pass

Value = getattr (CLS, nkey)
If readonly:
Return Value
# If no variable type key is found in the preceding method, this type will be stored in this class, that is, the dictionary of this class (CLS. _ dict __). And return
If not Cls. _ warn _ is false and not isinstance (value, cowmeta ):
Print ("Warning: doing a copy because % s is a mutable type." % key, file = Cls. _ warn __)
Try:
Value = value. Copy ()#??.
T attributeerror as E:
Value = Copy. Copy (value)
Setattr (CLS, nkey, value)
Return Value

_ Getmarker _ = []
Def _ getreadonly _ (CLS, key, default =__ getmarker __):
Print ("getreadonly ")
"""\
Get a value (even if mutable) which you promise not to change.
"""
Return Cls. _ getitem _ (Key, default, true)

Def _ getitem _ (CLS, key, default =__ getmarker __, readonly = false ):
Print ("getitem ")
Try:

Try:

# Obtain immutable Parameters

Value = getattr (CLS, key)

T attributeerror:

# Variable parameters

Value = Cls. _ getmutable _ (Key, readonly)

# This is for values which have been deleted
If value is Cls. _ marker __:
Raise attributeerror ("Key % s does not exist." % key)

Return Value
T attributeerror as E:
If not default is Cls. _ getmarker __:
Return default

Raise keyerror (STR (e ))
# In fact, the key is not deleted from the dictionary, but it is marked.
Def _ delitem _ (CLS, key ):
Print ("delitem ")
Cls. _ setitem _ (Key, CLS. _ marker __)

# Delete a variable type
Def _ revertitem _ (CLS, key ):
Print ("revertitem ")
If not Cls. _ dict _. has_key (key ):
Key + = mutable
Delattr (CLS, key)

Def _ contains _ (CLS, key ):
Print ("contains ")
Return Cls. has_key (key)

Def has_key (CLS, key ):
# To obtain a read-only type, the uploaded data is a tuples.
Value = Cls. _ getreadonly _ (Key, CLS. _ marker __)
If value is Cls. _ marker __:
Return false
Return true

Def ITER (CLS, type, readonly = false ):
Print ("ITER ")
For key in Dir (CLS ):
If key. startswith ("__"):
Continue

If key. endswith (mutable ):
Key = Key [:-len (mutable)] # if it is a variable type, remove the variable sign.

If type = "keys ":
Yield key

Try:
If readonly:
Value = Cls. _ getreadonly _ (key)
Else:
Value = CLS [Key]
Failed t keyerror:
Continue

If type = "values ":
Yield Value
If type = "items ":
Yield (Key, value)
Raise stopiteration () # Stop iteration when there is no value in the dictionary

# Why is return Cls. ITER ("keys") used ")

# Because iteratable functions must be able to return a value each time,

# If not, it is not an iterative function, and this function must meet two conditions.

#1 there is a next method:

#2 or have the yield Generator

Def iterkeys (CLS ):
Print ("iterkeys ")
Return Cls. ITER ("keys ")
Def itervalues (CLS, readonly = false ):
Print ("itervalues ")
If not Cls. _ warn _ is false and Cls. _ hasmutable _ and readonly is false:
Print ("Warning: If you arn't going to change any of the values call with true.", file = Cls. _ warn __)
Return Cls. ITER ("values", readonly)
Def iteritems (CLS, readonly = false ):
Print ("iteritems ")
If not Cls. _ warn _ is false and Cls. _ hasmutable _ and readonly is false:
Print ("Warning: If you arn't going to change any of the values call with true.", file = Cls. _ warn __)
Return Cls. ITER ("items", readonly)

Class cowsetmeta (cowdictmeta ):
Def _ STR _ (CLS ):
# Fixme: I have magic numbers!
Return "<cowset level: % I current keys: % I>" % (CLS. _ count __, Len (CLS. _ dict _)-3)
_ Repr _ = _ STR __

Def cow (CLS ):
Class C (CLS ):
_ Count _ = Cls. _ count _ + 1
Return C

Def add (CLS, value ):
Cowdictmeta. _ setitem _ (CLS, repr (Hash (value), value)

Def remove (CLS, value ):
Cowdictmeta. _ delitem _ (CLS, repr (Hash (value )))

Def _ in _ (CLS, value ):
Return cowdictmeta. has_key (Repr (Hash (value )))

Def iterkeys (CLS ):
Raise typeerror ("sets don't have keys ")

Def iteritems (CLS ):
Raise typeerror ("sets don't have 'items '")

# These are the actual classes you use!
Class cowdictbase (object ):
_ Metaclass _ = cowdictmeta
_ Count _ = 1

Class cowsetbase (object ):
_ Metaclass _ = cowsetmeta
_ Count _ = 0

If _ name _ = "_ main __":
Import sys
Cowdictbase. _ warn _ = SYS. stderr
A = cowdictbase ()
B = cowdictbase ()
# Print ("A",)
SYS. Exit ()

A ['a'] = 'A'
A ['B'] = 'B'
A ['dict '] = {}

B = A. Copy ()
Print ("B", B)
B ['C'] = 'B'

Print ()

Print ("A",)
For X in A. iteritems ():
Print (X)
Print ("--")
Print ("B", B)
For X in B. iteritems ():
Print (X)
Print ()

B ['dict '] ['a'] =' B'
B ['a'] = 'C'

Print ("A",)
For X in A. iteritems ():
Print (X)
Print ("--")
Print ("B", B)
For X in B. iteritems ():
Print (X)
Print ()

Try:
B ['dict2']
Failed t keyerror as E:
Print ("Okay! ")

A ['set'] = cowsetbase ()
A ['set']. Add ("O1 ")
A ['set']. Add ("O1 ")
A ['set']. Add ("O2 ")

Print ("A",)
For X in a ['set']. itervalues ():
Print (X)
Print ("--")
Print ("B", B)
For X in B ['set']. itervalues ():
Print (X)
Print ()

B ['set']. Add ('o3 ')

Print ("A",)
For X in a ['set']. itervalues ():
Print (X)
Print ("--")
Print ("B", B)
For X in B ['set']. itervalues ():
Print (X)
Print ()

A ['set2'] = set ()
A ['set2']. Add ("O1 ")
A ['set2']. Add ("O1 ")
A ['set2']. Add ("O2 ")

Print ("A",)
For X in A. iteritems ():
Print (X)
Print ("--")
Print ("B", B)
For X in B. iteritems (readonly = true ):
Print (X)
Print ()

Del B ['B']
Try:
Print (B ['B'])
Failed t keyerror:
Print ("Yay! Deleted key raises error ")

If B. has_key ('B '):
Print ("boo! ")
Else:
Print ("Yay-has_key with Delete works! ")

Print ("A",)
For X in A. iteritems ():
Print (X)
Print ("--")
Print ("B", B)
For X in B. iteritems (readonly = true ):
Print (X)
Print ()

B. _ revertitem _ ('B ')

Print ("A",)
For X in A. iteritems ():
Print (X)
Print ("--")
Print ("B", B)
For X in B. iteritems (readonly = true ):
Print (X)
Print ()

B. _ revertitem _ ('dict ')
Print ("A",)
For X in A. iteritems ():
Print (X)
Print ("--")
Print ("B", B)
For X in B. iteritems (readonly = true ):
Print (X)
Print ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.