Python copy.update() Examples

The following are code examples for showing how to use copy.update(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: robocup-soccer   Author: kengz   File: utils.py    (MIT License) View Source Project 6 votes vote down vote up
def update(x, **entries):
    """Update a dict; or an object with slots; according to entries.
    >>> update({'a': 1}, a=10, b=20)
    {'a': 10, 'b': 20}
    >>> update(Struct(a=1), a=10, b=20)
    Struct(a=10, b=20)
    """
    if isinstance(x, dict):
        x.update(entries)   
    else:
        x.__dict__.update(entries) 
    return x 

#______________________________________________________________________________
# Functions on Sequences (mostly inspired by Common Lisp)
# NOTE: Sequence functions (count_if, find_if, every, some) take function
# argument first (like reduce, filter, and map). 
Example 2
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 6 votes vote down vote up
def begin_transaction(self, table, wait=False):
        "Locks and copies table while optionally waiting for unlock."
        table = self.__data.where(name=table)
        assert table.first('type') is not _View, 'Views are not supported!'
        lock = table.first('lock')
        if wait:
            lock.acquire()
            with self.__lock:   # Protects Critical Section
                data = table.first('data')
                table.update(copy=copy.deepcopy(data))
        else:
            with self.__lock:
                assert lock.acquire(False), 'Table is locked in a transaction!'
                data = table.first('data')
                table.update(copy=copy.deepcopy(data))
        return data 
Example 3
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 6 votes vote down vote up
def test():
    "Runs several groups of tests of the database engine."
    # Test simple statements in SQL.
    persons = test_basic_sql()
    # Test various ways to select rows.
    test_row_selection(persons)
    # Test the four different types of joins in SQL.
    orders = test_all_joins(persons)
    # Test unstructured ways of joining tables together.
    test_table_addition(persons, orders)
    # Test creation and manipulation of databases.
    test_database_support()
    # Load and run some test on the sample Northwind database.
    northwind = test_northwind()
    # Test different date operations that can be performed.
    test_date_functionality()
    # Test various functions that operate on specified column.
    test_column_functions()
    if northwind:
        # Test ability to select columns with function processing.
        test_generic_column_functions(persons, northwind)
    # Test Database2 instances that support transactions.
    nw2 = test_transactional_database()
    # Allow for interaction at the end of the test.
    globals().update(locals()) 
Example 4
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 6 votes vote down vote up
def test_date_functionality():
    "Tests different date operations that can be performed."
    # Create an orderz table to test the date type.
    orderz = Table(('OrderId', int), ('ProductName', str), ('OrderDate', date))
    orderz.insert(1, 'Geitost', date(2008, 11, 11))
    orderz.insert(2, 'Camembert Pierrot', date(2008, 11, 9))
    orderz.insert(3, 'Mozzarella di Giovanni', date(2008, 11, 11))
    orderz.insert(4, 'Mascarpone Fabioloi', date(2008, 10, 29))
    # Query the table for a specific date.
    orderz.where(ROW.OrderDate == date(2008, 11, 11)).print()
    # Update the orderz table so that times are present with the dates.
    orderz.alter_column('OrderDate', datetime)
    orderz.where(ROW.OrderId == 1) \
                        .update(OrderDate=datetime(2008, 11, 11, 13, 23, 44))
    orderz.where(ROW.OrderId == 2) \
                        .update(OrderDate=datetime(2008, 11, 9, 15, 45, 21))
    orderz.where(ROW.OrderId == 3) \
                        .update(OrderDate=datetime(2008, 11, 11, 11, 12, 1))
    orderz.where(ROW.OrderId == 4) \
                        .update(OrderDate=datetime(2008, 10, 29, 14, 56, 59))
    # Query the table with a datetime object this time.
    orderz.where(ROW.OrderDate == datetime(2008, 11, 11)).print() 
Example 5
Project: python_resources   Author: sai-byui   File: utils.py    (license) View Source Project 6 votes vote down vote up
def update(x, **entries):
    """Update a dict; or an object with slots; according to entries.
    >>> update({'a': 1}, a=10, b=20)
    {'a': 10, 'b': 20}
    >>> update(Struct(a=1), a=10, b=20)
    Struct(a=10, b=20)
    """
    if isinstance(x, dict):
        x.update(entries)   
    else:
        x.__dict__.update(entries) 
    return x 

#______________________________________________________________________________
# Functions on Sequences (mostly inspired by Common Lisp)
# NOTE: Sequence functions (count_if, find_if, every, some) take function
# argument first (like reduce, filter, and map). 
Example 6
Project: robocup-soccer   Author: kengz   File: utils.py    (MIT License) View Source Project 5 votes vote down vote up
def update(self, other):
                for e in other:
                    self.add(e)
                return self 
Example 7
Project: robocup-soccer   Author: kengz   File: utils.py    (MIT License) View Source Project 5 votes vote down vote up
def __copy__(self):
        copy = DefaultDict(self.default)
        copy.update(self)
        return copy 
Example 8
Project: robocup-soccer   Author: kengz   File: utils.py    (MIT License) View Source Project 5 votes vote down vote up
def __init__(self, **entries):
        self.__dict__.update(entries) 
Example 9
Project: robocup-soccer   Author: kengz   File: utils.py    (MIT License) View Source Project 5 votes vote down vote up
def __init__(self, order=min, f=lambda x: x):
        update(self, A=[], order=order, f=f) 
Example 10
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 5 votes vote down vote up
def __extend_data(self):
        "Adds columns to internal table as necessary."
        if ('type', type) not in self.__data.schema:
            self.__data.alter_add('type', type)
            for name, data in rows(self.__data('name', 'data')):
                self.__data.where(name=name).update(type=type(data))
        self.__data.alter_add('lock', _Lock)
        self.__data.alter_add('copy', object) 
Example 11
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 5 votes vote down vote up
def __commit(table):
        "Deletes the reserve copy of a table."
        table.update(copy=object()) 
Example 12
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 5 votes vote down vote up
def __rollback(table):
        "Restores table from copy and deletes the copy."
        table.update(data=table.first('copy'), copy=object())

    ######################################################################## 
Example 13
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 5 votes vote down vote up
def update(self, **assignments):
        "Changes all present rows with given assignments."
        assign = []
        for name, value in assignments.items():
            data_type, index = self.__columns[name]
            assert isinstance(value, data_type), \
            'Wrong datatype: {} ({!r}, {!r})'.format(name, value, data_type)
            assign.append((index, value))
        for row in self.__data_area.values():
            for index, value in assign:
                row[index] = value 
Example 14
Project: python_resources   Author: sai-byui   File: utils.py    (license) View Source Project 5 votes vote down vote up
def update(self, other):
                for e in other:
                    self.add(e)
                return self 
Example 15
Project: python_resources   Author: sai-byui   File: utils.py    (license) View Source Project 5 votes vote down vote up
def __copy__(self):
        copy = DefaultDict(self.default)
        copy.update(self)
        return copy 
Example 16
Project: python_resources   Author: sai-byui   File: utils.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, **entries):
        self.__dict__.update(entries) 
Example 17
Project: python_resources   Author: sai-byui   File: utils.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, order=min, f=lambda x: x):
        update(self, A=[], order=order, f=f) 
Example 18
Project: rensapy   Author: RensaProject   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def __copy__(self):
            copy = defaultdict(self.default)
            copy.update(self)
            return copy 
Example 19
Project: RePhraser   Author: MissLummie   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def __copy__(self):
            copy = defaultdict(self.default)
            copy.update(self)
            return copy 
Example 20
Project: Verideals   Author: Derrreks   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def __copy__(self):
            copy = defaultdict(self.default)
            copy.update(self)
            return copy 
Example 21
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 4 votes vote down vote up
def test_basic_sql():
    "Tests simple statements in SQL."
    # Test create table statement.
    persons = Table(('P_Id', int), ('LastName', str), ('FirstName', str),
                    ('Address', str), ('City', str))
    # Populate the table with rows.
    persons.insert(1, 'Hansen', 'Ola', 'Timoteivn 10', 'Sandnes')
    persons.insert(2, 'Svendson', 'Tove', 'Borgvn 23', 'Sandnes')
    persons.insert(3, 'Pettersen', 'Kari', 'Storgt 20', 'Stavanger')
    persons.print()
    # Test the select statement.
    persons.select('LastName', 'FirstName').print()
    persons.select().print()
    # Test the distinct statement.
    persons.select('City').distinct().print()
    # Test the where clause.
    persons.where(ROW.City == 'Sandnes').print()
    # Test the and operator.
    persons.where((ROW.FirstName == 'Tove') &
                  (ROW.LastName == 'Svendson')).print()
    # Test the or operator.
    persons.where((ROW.FirstName == 'Tove') | (ROW.FirstName == 'Ola')).print()
    # Test both and & or operators.
    persons.where((ROW.LastName == 'Svendson') &
                  ((ROW.FirstName == 'Tove') |
                   (ROW.FirstName == 'Ola'))).print()
    # Test order by statement.
    persons.insert(4, 'Nilsen', 'Tom', 'Vingvn 23', 'Stavanger')
    persons.order_by('LastName').table().print()
    persons.order_by('LastName', True).table().print()
    # Test insert statement.
    persons.insert(5, 'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
    persons.print()
    persons.insert(P_Id=6, LastName='Tjessem', FirstName='Jakob')
    persons.print()
    # Test update statement.
    persons.where((ROW.LastName == 'Tjessem') &
                  (ROW.FirstName == 'Jakob')).update(Address='Nissestien 67',
                                                     City='Sandnes')
    persons.print()
    copy = persons.order_by('P_Id').table()
    copy.update(Address='Nissestien 67', City='Sandnes')
    copy.print()
    # Test delete statement.
    copy = persons.order_by('P_Id').table()
    copy.delete((ROW.LastName == 'Tjessem') &
                (ROW.FirstName == 'Jakob')).print()
    copy.truncate().print()
    return persons 
Example 22
Project: code   Author: ActiveState   File: recipe-577825.py    (MIT License) View Source Project 4 votes vote down vote up
def test_northwind():
    "Loads and runs some test on the sample Northwind database."
    import os, imp
    # Patch the module namespace to recognize this file.
    name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    module = imp.new_module(name)
    vars(module).update(globals())
    sys.modules[name] = module
    # Load a Northwind database for various testing purposes.
    try:
        northwind = Database.load('northwind.db')
    except IOError:
        return
    # Create and test a current product list view.
    northwind.create('Current Product List', lambda db: db.Products.where(
        ROW.Discontinued.NOT).select('ProductID', 'ProductName'))
    northwind['Current Product List'].print()
    # Find all products having an above-average price.
    def above_average_price(db):
        return db.Products.where(ROW.UnitPrice > db.Products.avg('UnitPrice')) \
               .select('ProductName', 'UnitPrice')
    northwind.create('Products Above Average Price', above_average_price)
    northwind['Products Above Average Price'].print()
    # Calculate total sale per category in 1997.
    def category_sales_for_1997(db):
        result = Table(('CategoryName', str),
                       ('CategorySales', decimal.Decimal))
        for table in db['Product Sales For 1997'] \
            .group_by('Categories.CategoryName'):
            name = next(rows(table.select('Categories.CategoryName')))[0]
            total = table.sum_('ProductSales')
            result.insert(name, total)
        return result
    northwind.create('Category Sales For 1997', category_sales_for_1997)
    northwind['Category Sales For 1997'].print()
    # Show just the Beverages Category from the previous view.
    northwind['Category Sales For 1997'].where(
        ROW.CategoryName == 'Beverages').print()
    # Add the Category column to the Current Product List view.
    northwind.create_or_replace('Current Product List', lambda db: \
        db['Products View'].where(ROW.Discontinued.NOT) \
        .select('ProductID', 'ProductName', 'Category'))
    northwind['Current Product List'].print()
    # Drop the Category Sales For 1997 view.
    northwind.drop('Category Sales For 1997')
    return northwind