Skip to content

Instantly share code, notes, and snippets.

@LukeGary462
Last active July 24, 2020 18:13
Show Gist options
  • Select an option

  • Save LukeGary462/f5752f5d0f06ee4fe4d4f064c1e2a106 to your computer and use it in GitHub Desktop.

Select an option

Save LukeGary462/f5752f5d0f06ee4fe4d4f064c1e2a106 to your computer and use it in GitHub Desktop.
General Python Patterns
######## CUSTOM EXCEPTION ########
class Test(Exception):
def __init__(self, *args):
print(*args)
super().__init__(*args)
>>> raise Test()
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#__main__.Test
#>>> raise Test('foo')
#foo
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#__main__.Test: foo
#>>> raise Test('foo', 'bar')
#foo bar
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#__main__.Test: ('foo', 'bar')
######## get class name from inherited class method ########
class BaseClass:
def get_name(self):
return type(self).__name__
class Derived(BaseClass):
def __init__(self):
super().__init__()
print(self.get_name())
#>>> foo = Derived()
#Derived
#>>>
# list comprehension
L = [1, 2, 3, 4, 5, 6]
X = [x for x in L if x > 3]
print(X)
# [4, 5, 6]
# set comprehension
sentence = "The cat in the hat had two sidekicks, thing one and thing two."
words = sentence.lower().replace('.', '').replace(',', '').split()
unique_words = {word for word in words}
print(unique_words)
# {'and', 'cat', 'had', 'hat', 'in', 'one', 'sidekicks', 'the', 'thing', 'two'}
short_unique_words = {word for word in words if len(word) <= 3}
print(short_unique_words)
#{'and', 'cat', 'had', 'hat', 'in', 'one', 'the', 'two'}
# convert dict to obj with good repr
class DObj(object):
def __init__(self, data: dict):
for _key, _value in data.items():
setattr(self, _key, _value)
def __repr__(self):
return f"<dobj>: {self.__dict__}"
# fast way
class Empty:
pass
e = Empty()
e.__dict__.update(data_dict)
# convert markdown to html, useful for quick good looking html for API stuff
import markdown
src = open('templates/home.md', 'r', encoding='utf-8')
src_txt = src.read()
src.close()
html = markdown.markdown(src_txt)
print(html)
# '<h1>Biomeme QC Store REST API</h1>\n<p>QC Data Storage API</p>\n<h2>Available Endpoints</h2>\n<ul>\n<li><code>/devices/</code> </li>\n<li>GET, POST</li>\n<li><code>/devices/core_id/&lt;str:serial_number&gt;</code></li>\n<li>GET, POST, PUT</li>\n<li>`/devices/&lt;str:mac_address</li>\n</ul>'
with open('test_home.html', 'w', encoding='utf-8', errors='xmlcharrefreplace') as output:
output.write(html)
# regex stuff
def get_numbers_from_line(line: str) -> List[float]:
"""
Gets the numbers from line.
:param line: The line
:type line: str
"""
numerics = \
r"([-+]?[0-9]+[.]?[eE]?[-+]?[0-9]+)?"
regex = re.compile(numerics, re.VERBOSE)
return [float(res) for res in regex.findall(line) if res]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment