Pages

Friday, May 08, 2020

Python Notes #1

Shuffling List Elements

Try shuffle method in random module.

shuffle() modifies the original sequence. In other words, shuffling happens in place and the function returns None.

To shuffle an immutable sequence -or- to save the shuffled sequence in a different object without disrupting original object holding the sequence, rely on random.sample() which returns a new shuffled list.

eg.,
>>> from random import shuffle, sample
>>> x = [1, 2, 3, 4, 5]
>>> y = shuffle(x)
>>> y
>>> x
[3, 2, 5, 4, 1]
>>> y = sample(x, len(x))
>>> y
[5, 3, 2, 1, 4]
>>> x
[3, 2, 5, 4, 1]

Checking all Imported Modules

Try sys.modules.keys()

eg.,
>>> import sys

>>> sys.modules.keys()
['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 
'errno', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings', 'genericpath', 'stat', 'zipimport', 
'_sysconfigdata', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', '_osx_support', 'codecs', 'readline', 'os.path', '_locale', 'signal', 'traceback', 
'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']

>>> import random

>>> sys.modules.keys()
['__future__', 'copy_reg', 'sre_compile', '_hashlib', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'hashlib',
 'abc', 'posixpath', '_random', '_weakrefset', 'errno', 'binascii', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__',
 '_warnings', 'math', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', '_osx_support', 'codecs', 'readline', 
'os.path', '_locale', 'signal', 'traceback', 'random', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']

Examining all Attributes in a Object

Try object.__dict__

__dict__ attribute contains all the attributes that describe the object. Helpful while debugging. It can be used to alter object's attributes too though I'm not sure if it is a recommended practice.

eg.,
>>> class A:
...     def __init__(self):
...             self.a = 100
...             self.b = 200
... 
>>> a = A()
>>> a.__dict__
{'a': 100, 'b': 200}

When dealing with complex objects, __dict__ may falter with errors such as TypeError: Object of type xxx is not JSON serializable.

No comments:

Post a Comment