On 23/04/2019 07:16, Arup Rakshit wrote: > which way the community encourages more in Python: if isinstance(key, > slice): or if type(key) == slice: ?
I think isinstance is usually preferred although I confess that I usually forget and use type()... But isinstance covers you for subclasses too. > class MyCustomList: > def __init__(self, list = []): > self.list = list > > def __getitem__(self, key): > if isinstance(key, slice): > return self.list[key] > else: > return self.list[key] The if/else test is meaningless since you return self.list[key] in both cases. You would be better off just calling it directly (and maybe wrapping that in a try block?) def __getitem__(self, key): try: return self.list[key] except ....: Assuming you can think of something useful to put in the except clause. Otherwise just let Python raise the exception and leave the user of the class to worry about what to do. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor