diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..12d9a20 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,4 @@ +# These are supported funding model platforms + +github: progrmoiz + diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 4c41aad..2272a81 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -8,11 +8,11 @@ In the interest of fostering an open and welcoming environment, we as contributo Examples of behavior that contributes to creating a positive environment include: -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members +* Using welcoming and inclusive language. +* Being respectful of differing viewpoints and experiences. +* Gracefully accepting constructive criticism. +* Focusing on what is best for the community. +* Showing empathy towards other community members. Examples of unacceptable behavior by participants include: @@ -28,19 +28,20 @@ Project maintainers are responsible for clarifying the standards of acceptable b Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. -## Scope +##Our Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. -## Enforcement +##Our Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at progrmoiz@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. -## Attribution +##Our Attribution -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]. [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ +Read carefully diff --git a/README.md b/README.md index de8931d..aa9ea9c 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,9 @@ # ![Python Snippets](./logo.png "Python Snippets") - -:snake: Python snippets of examples, to learn things and to make task easier. +These Snippets can make your life a lot easier than expected, use it wisely. --- -## Snippets +## Snippets TO LEARN - [string_import.py](string_import.py) example to show import module from string - [classtools.py](classtools.py) assorted class utilities and tools @@ -24,6 +23,9 @@ - [listinherited.py](listinherited.py) Mix-in class that provides a formatted print() or str() (Use dir() to collect both instance attr and names inherited from its classes) - [listinherited2.py](listinherited2.py) Same as listinherited.py, but more formatted - [listtree.py](listtree.py) Trace the entire class and all its object's attrs at and above self +- [mapattrs.py](mapattrs.py) Map all attributes on or inherited by an +instance to the instance or class from which they are inherited. + --- diff --git a/classtools.py b/classtools.py index f3d8a79..5ee0436 100644 --- a/classtools.py +++ b/classtools.py @@ -32,5 +32,4 @@ class SubTest(TopTest): pass X, Y = TopTest(), SubTest() - print(X) - print(Y) + print(X,"\n",y) diff --git a/computedproperty.py b/computedproperty.py new file mode 100644 index 0000000..84d58b2 --- /dev/null +++ b/computedproperty.py @@ -0,0 +1,38 @@ +ng computed property and setting + + +class operators(object): + def __getattr__(self, name): + if name == 'age': + return 40 + else: + raise AttributeError(name) + + def __setattr__(self, name, value): + print('set: %s %s' % (name, value)) + if name == 'age': + self.__dict__['_age'] = value + else: + self.__dict__[name] = value + + +# OR BETTER WAY + + +class properties(object): + def getage(self): + return 40 + + def setage(self, value): + self._age = value + + age = property(getage, setage, None, None) + + +if __name__ == '__main__': + x, y = operators(), properties() + for ins in (x, y): + print(ins.age) + ins.age = 20 + print(ins._age) + diff --git a/listtree.py b/listtree.py index b1874b4..48507b1 100644 --- a/listtree.py +++ b/listtree.py @@ -51,22 +51,17 @@ def __str__(self): def tester(listerclass, sept=False): - class Super: - - def __init__(self): + def __init__(self): self.data1 = 'spam' - - def ham(self): + def ham(self): pass class Sub(Super, listerclass): - def __init__(self): Super.__init__(self) self.data2 = 'eggs' self.data3 = 42 - def spam(self): pass diff --git a/mapattrs.py b/mapattrs.py new file mode 100644 index 0000000..919323c --- /dev/null +++ b/mapattrs.py @@ -0,0 +1,106 @@ +""" +File: mapattrs.py (3.x + 2.x) + +Main tool: mapattrs() map all attributes on or inherited by an +instance t othe instance or class from which they are inherited. + +Assumes dir() give all attributes of an instance. To simulate +inheritance, uses eitehr the class's MRO tuple, which gives the +search order for new-style classes (and all in 3.x), or a recursive +traversal to infer the DFLR order of classic classes in 2.x + +Also here: inheritance() gives version-neutral class ordering; +assorted dictionary tools using 3.x/2.7 comprehensions. +""" + +import pprint + + +def trace(X, label='', end='\n'): + print(label + pprint.pformat(X) + end) # Print nicely + + +def filterdictvals(D, V): + """ + dict D with entries for valeus V removed. + filterdictvals(dict(a=1, b=2, c=1), 1) => {'b': 2} + """ + return {K: V2 for (K, V2) in D.items() if V2 != V} + + +def invertdict(D): + """ + dict D with values changed to keys (grouped by values). + Values must all be hashable to work as dict/set keys. + invertdict(dict(a=1, b=2, c=1)) => {1: ['a', 'c'], 2: 'b'} + """ + def keysof(V): + return sorted(K for K in D.keys() if D[K] == V) + return {V: keysof(V) for V in set(D.values())} + + +def dflr(cls): + """ + Classics depth-first left-to-right order of class tree at cls. + Cycles not possible: Python disallows on __bases__ changes. + """ + here = [cls] + for sup in cls.__bases: + here += dflr(sup) + return here + + +def inheritance(instance): + """ + Inheritance order sequnce: new-style (MRO) or classic (DFLR) + """ + if (hasattr(instance.__class__, '__mro__')): + return (instance,) + instance.__class__.__mro__ + else: + return [instance] + dflr(instance.__class__) + + +def mapattrs(instance, withobject=False, bysource=False): + """ + dict with keys giving all inherited attributes of instance, + with values giving the object that each is inherited from. + withobject: False=remove object built-in class attributes + bysource: True=group result by objects instead of attributes. + Supports classes with slot that preclude __dict__ in instance. + """ + attr2obj = {} + inherits = inheritance(instance) + for attr in dir(instance): + for obj in inherits: + if hasattr(obj, '__dict__') and attr in obj.__dict__: + attr2obj[attr] = obj + break + + if not withobject: + attr2obj = filterdictvals(attr2obj, object) + + return attr2obj if not bysource else invertdict(attr2obj) + + +if __name__ == '__main__': + print('Classics classes in 2.x, new-style in 3.x') + class A: attr1 = 1 + class B(A): attr2 = 2 + class C(A): attr1 = 3 + class D(B, C): pass + I = D() + print("Py=>%s" % I.attr1) + trace(inheritance(I), 'INH\n') + trace(mapattrs(I), 'ATTRS\n') + trace(mapattrs(I, bysource=True), 'OBJS\n') + + print('New-style classes in 2.x and 3.x') + class A(object): attr1 = 1 + class B(A): attr2 = 2 + class C(A): attr1 = 3 + class D(B, C): pass + I = D() + print("Py=>%s" % I.attr1) + trace(inheritance(I), 'INH\n') + trace(mapattrs(I), 'ATTRS\n') + trace(mapattrs(I, bysource=True), 'OBJS\n') diff --git a/mydir.py b/mydir.py index 26f70f8..0ddd9ae 100644 --- a/mydir.py +++ b/mydir.py @@ -1,6 +1,6 @@ #!python """ -mydir.py: a module that lists the namespaces of other module +mydir.py: a module that list the namespaces of other modules """ from __future__ import print_function @@ -25,7 +25,7 @@ def listing(module, verbose=True): if verbose: print(sepline) - print(module.__name__, 'has %d names' % count) + print(module.__name__, 'has following %d names' % count) print(sepline) if __name__ == '__main__': diff --git a/state_retention.py b/state_retention.py new file mode 100644 index 0000000..f5755b4 --- /dev/null +++ b/state_retention.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +from __future__ import print_function + + +# nonlocal 3.x +def tester(start): + state = start + + def nested(label): + nonlocal state + print(label, state) + state += 1 + return nested + + +# nested global 2.x, 3.x +def tester1(start): + global gstate + gstate = start + + def nested(label): + global gstate + print(label, gstate) + gstate += 1 + return nested + + +# with mutables +def tester2(start): + state = [start] + + def nested(label): + print(label, state[0]) + state[0] += 1 + return nested + + +# function attr +def tester3(start): + + def nested(label): + print(label, nested.state) + nested.state += 1 + nested.state = 0 + return nested + + +# class +class tester4(object): + + def __init__(self, start): + self.state = start + + def __call__(self, label): + print(label, self.state) + self.state += 1 + + +if __name__ == '__main__': + for test in (tester, tester1, tester2, tester3, tester4): + f = test(0) + f('name: %s, state:' % test.__name__) + f('name: %s, state:' % test.__name__) + f('name: %s, state:' % test.__name__) + f('name: %s, state:' % test.__name__) + print() + print('done') diff --git a/string_import.py b/string_import.py index b70439d..fdd3d87 100644 --- a/string_import.py +++ b/string_import.py @@ -1,12 +1,12 @@ # you can use builtin __import__ function -modname = 'string' +modname = 'strings' string = __import__(modname) -print(string) +print(strings) # Python official prefferred way import importlib -modname = 'string' -string = importlib.import_module(modname) -print(string) +modname = 'strings' +strings = importlib.import_module(modname) +print(strings) diff --git a/timer.py b/timer.py index d2be915..07f8c39 100644 --- a/timer.py +++ b/timer.py @@ -43,7 +43,7 @@ def bestof(reps, func, *pargs, **kargs): def bestoftotal(reps1, reps2, func, *pargs, **kargs): """ - Best of totals: + It will give best of total: (best of reps1 runs of (total of reps2 runs of func)) """ return bestof(reps1, total, reps2, func, *pargs, **kargs)