Skip to content

Instantly share code, notes, and snippets.

@abhisekp
Last active April 19, 2017 21:20
Show Gist options
  • Save abhisekp/159ce0deb495f94eb3f3e103cc3bda18 to your computer and use it in GitHub Desktop.
Save abhisekp/159ce0deb495f94eb3f3e103cc3bda18 to your computer and use it in GitHub Desktop.
Python Concepts — http://j.mp/py-concepts

Q: How to write a custom error and capture it?

A: Sub-class the Exception or any particular exception classes e.g. TypeError or ValueError or AttributeError, etc. And simply use the custom error class to raise or except (capture) an exception.

# -*- coding: utf-8 -*-
# custom_error.py

from textwrap import dedent

class InvalidNameError(ValueError): 
    def __init__(self, name):
        super().__init__(dedent("""
            InvalidNameError: 
                `%s` must be a `string`.
                Got type `%s`.
            """ % (repr(name), type(name).__name__)
        ))

def name_person(name):
    if not isinstance(name, str):
        raise InvalidNameError(name)
    return name.upper()

# ==== - ==== - ==== #

try:
    name = name_person('Gerund Truple')
    print('Name: %s' % name)  # 'GERUND TRUPLE'
    
    name = name_person({'name': 'Monty Cristo'})
except InvalidNameError as err:
    print(err)

OUTPUT

---------- <blank line> ----------
Name: GERUND TRUPLE

InvalidNameError: 
    `{'name': 'Monty Cristo'}` must be a `string`.
    Got type `dict`.
---------- <blank line> ----------

🚀 Run Code

Q: How to dedent multiline strings?

A: Use the dedent method from textwrap module.

# -*- coding: utf-8 -*-
# dedent.py

from textwrap import dedent

print(dedent(
    """
    This is a multiline string
    with proper dedentation
    """
))

OUTPUT

---------- <blank line> ----------
This is a multiline string
with proper dedentation
---------- <blank line> ----------

🚀 Run Code

Q: How to convert a dictionary to a string?

A: Sub-class the dict class, override the __str__ method and use the sub-class for you dictionary needs :)

# -*- coding: utf-8 -*-
# dict2str.py

class PersonName(dict):
    def __init__(self, name):
        super().__init__(name)
        self.first_name = name.get('first_name', '')
        self.middle_name = name.get('middle_name', '')
        self.last_name = name.get('last_name', '')

    def __str__(self):
        return ' '.join(filter(bool, [
            self.get('first_name'), 
            self.get('middle_name'), 
            self.get('last_name'),
        ]))

# ==== - ==== - ==== #

tommy = PersonName({
    'first_name': 'Tommy',
})

print('[' + str(tommy) + ']')

OUTPUT

[Tommy]

🚀 Run Code

Q: How to create a getter or setter property in a class?

A: Use @property and @<property_name>.setter decorators. (for newer Python versions)
OR
Use <property_name> = get( <getter_func>, <setter_func> ) (for older Python versions)

# -*- coding: utf-8 -*-
# getter_setter.py

class Student:
    def __init__(self, name, age = 0):
        self.name = name
        self.age = age
    
    @property
    def name(self):
        return self._name.lower()
        
    @name.setter
    def name(self, _name):
        self._name = _name.upper()
        return self
        
    def get_age(self):
        return self._age * 100
        
    def set_age(self, _age):
        self._age = _age
        
    # <property_name> = get( <getter_func>, <setter_func> ) format
    age = property(get_age, set_age)
      
# ==== - ==== - ==== #

tommy = Student('Tommy Hilfrangler', age=42)
print('name: ' + tommy.name)
print('_name: ' + tommy._name)

tommy.name = 'Jack Johenson'
print('name: ' + tommy.name)
print('_name: ' + tommy._name)
print('age: ' + str(tommy.age))
print('_age: ' + str(tommy._age))

OUTPUT

name: tommy hilfrangler
_name: Tommy Hilfrangler
name: jack johenson
_name: JACK JOHENSON
age: 4200
_age: 42

🚀 Run Code

Q: How to do multiple inheritance?

A: Python doesn't exactly allow "multiple" inheritance but it does allows "multi-level" inheritance.

# -*- coding: utf-8 -*-
# multiple-inheritance.py

class Human:
    def __init__(self, name):
        self.name = name
        self.type = 'Human'
        self._speed = 0
    def move(self):
        self._speed += 20
    def get_speed(self):
        return self._speed

class Robot:
    def __init__(self, name):
        self.name = name
        self.type = 'Robot'
        self._speed = 0
    def move(self):
        self._speed += 3000

class Student(Human):
    def get_marks(self):
        return {
            'english': 70,
        }
    
class RoboticStudent(Robot, Student):
    def __init__(self, name):
        super().__init__(name)
        self.type = 'Robotic Student'

# ==== - ==== - ==== #

small_wonder = RoboticStudent('Vicky')
small_wonder.move()
# Speed of Vicky [Robotic Student]: 3000 kmph
print('Speed of %s [%s]: %d kmph' % (
    small_wonder.name, small_wonder.type, small_wonder.get_speed()
))

# Marks in English of Vicky [Robotic Student] is 70
print(
    'Marks in English of %s [%s] is %s' % 
    (small_wonder.name, small_wonder.type, small_wonder.get_marks()['english'])
)

tommy = Student('Tommy')
tommy.move()
# Speed of Tommy [Human]: 20 kmph
print('Speed of %s [%s]: %d kmph' % (tommy.name, tommy.type, tommy.get_speed()))

OUTPUT

Speed of Vicky [Robotic Student]: 3000 kmph
Marks in English of Vicky [Robotic Student] is 70
Speed of Tommy [Human]: 20 kmph

🚀 Run Code

Q: How do you compare a particular value with two or more other values?

A: In an if condition, if you want to compare a particular value with two or more values, you may write it as in the CASE 2.

# -*- coding: utf-8 -*-
# condition.py

x = ''

## CASE 1
if (type(x) is not str) and (type(x) is not int):
    print('x must be either type of "string" or "integer"')
else:
    print('Awesome!')

# -----------

## CASE 2
if type(x) not in [str, int]:
    print('x must be either type of "string" or "integer"')
else:
    print('Awesome!')

🚀 Run Code

Q: How to use string interpolation?

A: Use formatted string. (only works in >= Python 3.6)

# -*- coding: utf-8 -*-
# string_interpolation.py

first_name = 'Tommy'
last_name = 'Hilfringler'

print(f"{first_name} {last_name}")

OUTPUT

Tommy Hilfringler

Q: How to write ternary operators?

A: Use the following syntax to write ternary operator.
my_var = <value_if_true> if <condition> else <value_if_false>

# -*- coding: utf-8 -*-
# ternary.py

SWITCH_ENABLED = False

voltage = 110 if SWITCH_ENABLED else 0

print('Voltage = ' + str(voltage))

OUTPUT

Voltage = 0

🚀 Run Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment