Python practical code snippets

Source: Internet
Author: User

Python practical code snippets

This article describes how to collect and paste python code snippets, this article collects useful Code such as getting all the subclasses of a class, calculating the running time, simple use of SQLAlchemy, and implementing enumeration similar to Java or C. For more information, see

Obtains all subclasses of a class.

Copy the Code as follows:

Def itersubclasses (cls, _ seen = None ):

"Generator over all subclasses of a given class in depth first order ."""

If not isinstance (cls, type ):

Raise TypeError (_ ('itersubclasses must be called'

'New-style classes, not %. 100r') % cls)

_ Seen = _ seen or set ()

Try:

Subs = cls. _ subclasses __()

Failed t TypeError: # fails only when cls is type

Subs = cls. _ subclasses _ (cls)

For sub in subs:

If sub not in _ seen:

_ Seen. add (sub)

Yield sub

For sub in itersubclasses (sub, _ seen ):

Yield sub

Simple thread cooperation

Copy the Code as follows:

Import threading

Is_done = threading. Event ()

Consumer = threading. Thread (

Target = self. consume_results,

Args = (key, self. task, runner. result_queue, is_done ))

Consumer. start ()

Self. duration = runner. run (

Name, kw. get ("context", {}), kw. get ("args ",{}))

Is_done.set ()

Consumer. join () # The main thread is blocked until the consumer operation ends.

For more information, threading. Event () can also be replaced with threading. Condition (). condition includes running y (), wait (), and policyall (). Explanation:

Copy the Code as follows:

The wait () method releases the lock, and then blocks until it is awakened by a wrong y () or policyall () call for the same condition variable in another thread. once awakened, it re-acquires the lock and returns. it is also possible to specify a timeout.

The specified y () method wakes up one of the threads waiting for the condition variable, if any are waiting. The specified yall () method wakes up all threads waiting for the condition variable.

Note: the specified y () and policyall () methods don't release the lock; this means that the thread or threads awakened will not return from their wait () call immediately, but only when the thread that called Policy () or policyall () finally relinquishes ownership of the lock.

Copy the Code as follows:

# Consume one item

Cv. acquire ()

While not an_item_is_available ():

Cv. wait ()

Get_an_available_item ()

Cv. release ()

# Produce one item

Cv. acquire ()

Make_an_item_available ()

Cv. Y ()

Cv. release ()

Computing Run Time

Copy the Code as follows:

Class Timer (object ):

Def _ enter _ (self ):

Self. error = None

Self. start = time. time ()

Return self

Def _ exit _ (self, type, value, tb ):

Self. finish = time. time ()

If type:

Self. error = (type, value, tb)

Def duration (self ):

Return self. finish-self. start

With Timer () as timer:

Func ()

Return timer. duration ()

Metadata

The parameters received by the _ new _ () method are:

The object of the class to be created;

Class Name;

The set of parent classes inherited by the class;

Class method set;

Copy the Code as follows:

Class ModelMetaclass (type ):

Def _ new _ (cls, name, bases, attrs ):

If name = 'model ':

Return type. _ new _ (cls, name, bases, attrs)

Mappings = dict ()

For k, v in attrs. iteritems ():

If isinstance (v, Field ):

Print ('found mapping: % s ==> % s' % (k, v ))

Mappings [k] = v

For k in mappings. iterkeys ():

Attrs. pop (k)

Attrs ['_ table _'] = name # assume that the table name and class name are consistent.

Attrs ['_ ings _'] = mappings # Save the ing between attributes and columns

Return type. _ new _ (cls, name, bases, attrs)

Class Model (dict ):

_ Metaclass _ = ModelMetaclass

Def _ init _ (self, ** kw ):

Super (Model, self). _ init _ (** kw)

Def _ getattr _ (self, key ):

Try:

Return self [key]

Failed t KeyError:

Raise AttributeError (r "'model' object has no attribute '% S'" % key)

Def _ setattr _ (self, key, value ):

Self [key] = value

Def save (self ):

Fields = []

Params = []

Args = []

For k, v in self. _ mappings _. iteritems ():

Fields. append (v. name)

Params. append ('? ')

Args. append (getattr (self, k, None ))

SQL = 'insert into % s (% s) values (% s) '% (self. _ table __,','. join (fields ),','. join (params ))

Print ('SQL: % s' % SQL)

Print ('args: % s' % str (ARGS ))

Class Field (object ):

Def _ init _ (self, name, column_type ):

Self. name = name

Self. column_type = column_type

Def _ str _ (self ):

Return '<% s: % s>

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.