Skip to content

Instantly share code, notes, and snippets.

@pavdmyt
Last active September 22, 2016 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavdmyt/c568532710e946029b5d70b8ae9265fc to your computer and use it in GitHub Desktop.
Save pavdmyt/c568532710e946029b5d70b8ae9265fc to your computer and use it in GitHub Desktop.
Code snippets
"""
Is analogous to @reify
Borrowed from here: https://github.com/aio-libs/yarl/blob/master/yarl/__init__.py
Topic references:
https://www.reddit.com/r/learnpython/comments/2oqusj/pyramids_reify_descriptor_could_it_be_simplified/
http://www.gghh.name/dibtp/2013/06/18/caching-in-python-with-a-descriptor-and-a-decorator.html
"""
class cached_property:
"""Use as a class method decorator. It operates almost exactly like
the Python `@property` decorator, but it puts the result of the
method it decorates into the instance dict after the first call,
effectively replacing the function it decorates with an instance
variable. It is, in Python parlance, a data descriptor.
"""
def __init__(self, wrapped):
self.wrapped = wrapped
try:
self.__doc__ = wrapped.__doc__
except: # pragma: no cover
self.__doc__ = ""
self.name = wrapped.__name__
def __get__(self, inst, owner, _sentinel=sentinel):
if inst is None:
return self
val = inst._cache.get(self.name, _sentinel)
if val is not _sentinel:
return val
val = self.wrapped(inst)
inst._cache[self.name] = val
return val
def __set__(self, inst, value):
raise AttributeError("cached property is read-only")
import gzip
def gzip_file(file_name):
"""GZIP compress an existing file."""
file_gz = file_name + '.gz'
with open(file_name, 'rb') as f_in, gzip.open(file_gz, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
return file_gz
# -*- coding: utf-8 -*-
"""
Handle keyboard interrupt (Ctrl+C) without tracebacks.
"""
import signal
import sys
import time
def main():
for i in range(10**6):
print(i)
time.sleep(1)
if __name__ == '__main__':
signal.signal(signal.SIGINT, lambda signal, frame: sys.exit(0))
main()
# -*- coding: utf-8 -*-
"""
Singleton implementation via a class decorator.
Source: http://intermediatepythonista.com/metaclasses-abc-class-decorators
"""
def singleton(cls):
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance
@singleton
class Foo(object):
pass
if __name__ == '__main__':
x = Foo()
print(id(x)) # e.g. 4310648144
y = Foo()
print(id(y)) # 4310648144
print(id(x) == id(y)) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment