Python : Difference between type() and isinstance()

In short type checks the object passed to it is object of the exact class or subclass it is passed, however isinstance checks if object passed come under inheritance hierarchy of base class. Hence it is preferred to check isinstance over type.

type() simply returns the type of an object.

Whereas, isinstance(): returns true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.

Example:

class MyString(str):
    pass

my_str = MyString()
if type(my_str) == 'str':
    print 'I hope this prints'
else:
    print 'cannot check subclasses'
if isinstance(my_str, str):
    print 'definitely prints'

Prints:

cannot check subclasses
definitely prints

 

Here’s why isinstance is better than type:

class Vehicle:
    pass

class Truck(Vehicle):
    pass

in this case, a truck object is a Vehicle, but you’ll get this:

isinstance(Vehicle(), Vehicle)  # returns True
type(Vehicle()) == Vehicle      # returns True
isinstance(Truck(), Vehicle)    # returns True
type(Truck()) == Vehicle        # returns False, and this probably won't be what you want.

In other words, isinstance is true for subclasses, too.

 

 

Advertisements

Python : Dictionary comprehension

Before updating a no sql or mongo doc you need to ensure that you are not adding keys which are not part of initial doc then dictionary comprehension is really helpful.

What it means, is you are able to create a dict (json object) dynamically in single line of code using loops, condition, construction every thing together.

Single line comprehension

items_to_update = {key: value for key, value in payload.items() if key in req_items}

 

multi line interpretation

if key in req_items:

….for key, value in payload.items():

…….. dictionary[key]=value

Detailed example of created update doc dic before inserting in mongo db

try:
    req_items = ["property1","property2"]
    items_to_update = {key: value for key, value in payload.items() if key in req_items}
  
    if items_to_update:
        logger.info("Updating device collection with {}".format(items_to_update))
        self.db.update({"filter": filter}, {"$set": items_to_update}, multi=True)
        logger.info("Successfully updated product details")
except PyMongoError as e:
    logger.critical('Pymongo Exception {}'.format(str(e)))
except Exception as e:
    logger.critical('Exception {}'.format(str(e)))

 

asd

Python: A tale of two styles of avoiding or handling errors

There are two distinct approaches to error handling (lots of ifstatements vs. catching exceptions). These approaches are respectively known as Look Before You Leap (LBYL) and Easier to Ask for Forgiveness than Permission. In the LBYL camp, you always check to see if something can be done before doing it. In EAFP, you just do the thing. If it turns out that wasn’t possible, shrug “my bad”, and deal with it.

Idiomatic Python is written in the EAFP style (where reasonable). We can do so because exceptions are cheap in Python.

LBYL vs. EAFP

It’s all well and good that exceptions are widely used in core Python constructs, but why is a different question. After all, for could certainly have been written to not rely on exceptions to mark the end of a sequence. Indeed, exceptions could have been avoided altogether.

But they exist due to the philosophical approach to error checking adopted in Python. Code that doesn’t use exceptions is always checking if it’s OK to do something. In practice, it must ask a number of different questions before it is convinced it’s OK to do something. If it doesn’t ask all of the right questions, bad things happen. Consider the following code:

def print_object(some_object):
    # Check if the object is printable...
    if isinstance(some_object, str):
        print(some_object)
    elif isinstance(some_object, dict):
        print(some_object)
    elif isinstance(some_object, list):
        print(some_object)
    # 97 elifs later...
    else:
        print("unprintable object")

This trivial function is responsible for calling print() on an object. If it can’t be print()-ed, it prints an error message.

Trying to anticipate all error conditions in advance is destined for failure (and is also really ugly). Duck typing is a central idea in Python, but this function will incorrectly print an error for types than can be printed but aren’t explicitly checked.

The function can be rewritten like so:

def print_object(some_object):
    # Check if the object is printable...
    try:
        printable = str(some_object)
        print(printable)
    except TypeError:
        print("unprintable object")

If the object can be coerced to a string, do so and print it. If that attempt raises an exception, print our error string. Same idea, much easier to follow (the lines in the try block could obviously be combined but weren’t to make the example more clear). Also, note that we’re explicitly checking for TypeError, which is what would be raised if the coercion failed. Never use a “bare” except: clause or you’ll end up suppressing real errors you didn’t intend to catch.

But wait, there’s more!

The function above is admittedly contrived (though certainly based on a common anti-pattern). There are a number of other useful ways to use exceptions. Let’s take a look at the use of an else clause when handling exceptions.

In the rewritten version of print_object below, the code in the elseblock is executed only if the code in the try block didn’t throw an exception. It’s conceptually similar to using else with a for loop (which is itself a useful, if not widely known, idiom). It also fixes a bug in the previous version: we caught a TypeError assuming that only the call to str()would generate it. But what if it was actually (somehow) generated from the call to print() and has nothing to do with our string coercion?

def print_object(some_object):
    # Check if the object is printable...
    try:
        printable = str(some_object)
    except TypeError:
        print("unprintable object")
    else:
        print(printable)

Now, the print() line is only called if no exception was raised. If print()raises an exception, this will bubble up the call stack as normal. The elseclause is often overlooked in exception handling but incredibly useful in certain situations. Another use of else is when code in the try block requires some cleanup (and doesn’t have a usable context manager), as in the below example:

def display_username(user_id):
    try:
        db_connection = get_db_connection()
    except DatabaseEatenByGrueError:
        print('Sorry! Database was eaten by a grue.')
    else:
        print(db_connection.get_username(user_id))
        db_connection.cleanup()

How not to confuse your users

A useful pattern when dealing with exceptions is the bare raise. Normally, raise is paired with an exception to be raised. However, if it’s used in exception handling code, raise has a slightly different (but immensely useful) meaning.

def calculate_value(self, foo, bar, baz):
    try:
        result = self._do_calculation(foo, bar, baz)
    except:
        self.user_screwups += 1 
        raise
    return result

Here, we have a member function doing some calculation. We want to keep some statistics on how often the function is misused and throws an exception, but we have no intention of actually handling the exception. Ideally, we want to an exception raised in _do_calculation to be flow back to the user code as normal. If we simply raised a new exception from our except clause, the traceback point to our except clause and mask the real issue (not to mention confusing the user). raise on its own, however, lets the exception propagate normally with its original traceback. In this way, we record the information we want and the user is able to see what actually caused the exception.

Loopback : How to create embedded document or create object type

Here is your Contact model and if you want embed another model called as Address inside it then you need to put relations as embedsOne.
Please note that if you are using mongodb then embeds document will be part of parent document which mean all child documents will not be part of different collections which are linked, rather they will all be part of single parent doc.

“relations”: {
“address”: {
“type”: “embedsOne”,
“model”: “Address”,
“property”: “address”,
“options”: {
“validate”: true,
“forceId”: false
}

Now Contacts.json would look like this

{
“name”: “Contact”,
“base”: “PersistedModel”,
“idInjection”: true,
“options”: {
“validateUpsert”: true
},
“properties”: {
“id”: {
“type”: “string”,
“id”: true,
“defaultFn”: “uuid”
},
“name”: {
“type”: “string”,
“required”: true
},
“phone”: {
“type”: “string”,
“required”: true
},
“email”: {
“type”: “string”
},
“relationship”: {
“type”: “string”
}
},
“validations”: [],
“relations”: {
“address”: {
“type”: “embedsOne”,
“model”: “Address”,
“property”: “address”,
“options”: {
“validate”: true,
“forceId”: false
}
}
},
“acls”: [],
“methods”: {}
}

Please note that default id creator or sub document is “defaultFn”: “uuid” which will add id.

Mycarfax Mobile app to maintain your vehicle service records and more

Mycarfax mobile app which can help you maintain your vehicle by keeping track of service records, inspection records, registration records, repairs, current marked value etc.

web version: https://www.mycarfax.com/garage

Mobile app :https://itunes.apple.com/us/app/mycarfax-car-maintenance-and-service-history/id552472249?mt=8

It also provide you the current value of your vehicle. (if you want to sale it today).

It reminds you of dates when next service, inspection, registration etc is due.

It also notifies you for any recall on your model.

Its simple to sign up with facebook login and pull all records based on on VIN 🙂

I lost my convertible car since I skipped oil change, now I am using this app to keep track and get reminders. ITS FREE.

(Works in US region)