explmod.py

Created by andreanx

Created on June 13, 2020

2.71 KB

explmod(module) to list the module content.


#platforms:
#0: MicroPython / TI-Nspire
#1: MicroPython / NumWorks
#2: MicroPython / G90+E / G35+E II
#3: MicroPython / G35+E/USB / G75/85/95
#4: CircuitPython / TI-Python / 83PCE / Trinket M0
#5: Xcas / HP Prime
#6: KhiCAS / Graph 90+E

def getplatform():
  id=-1
  try:
    import sys
    try:
      if sys.platform=='nspire':id=0
      if sys.platform.startswith('TI-Python') or sys.platform=='Atmel SAMD21':id=4
    except:id=3
  except:
    try:
      import kandinsky
      id=1
    except:
      try:
        if chr(256)==chr(0):id=5+(not ("HP" in version()))
      except:
        id=2
  return id

platform=getplatform()
#lines shown on screen
#plines=[29,12,  7, 9,11,0,0]
plines=[29,16,  7, 9,11,0,0]
#max chars per line
#(error or CR if exceeded)
pcols =[53,99,509,32,32,0,0]

unsafe = ((), (), (), ('sys.argv', 'sys.path'), (), (), ())

if platform>=0:
  curline=0
  _p = print
  nlines=plines[platform]
  ncols=pcols[platform]
  def print(*ls):
    global curline
    st=""
    for s in ls:
      if not(isinstance(s,str)):
        s=str(s)
      st=st+s
    stlines=1+int(len(st)/ncols)
    if curline+stlines>=nlines:
      input("Input to continue:")
      curline=0
    _p(st)
    curline+=stlines

def sstr(obj):
  try:
    s=obj.__name__
  except:
    s=str(obj)
    a=s.find("'")
    b=s.rfind("'")
    if a>=0 and b!=a:
      s=s[a+1:b]
  return s

def isExplorable(obj):
  for k in done:
    try:
      if isinstance(obj, eval(k)):
        t, done[k] = done[k], True
        return not t
    except: pass
  if str(obj).startswith("<module"): return False
  l = ()
  try: l = dir(obj)
  except: pass
  return len(l)

done = {'str':False, 'list':False, 'tuple':False, 'dict':False, 'complex':False, 'set':False, 'frozenset': False}

def explmod(pitm, pitmsl=[], reset=True):
  global curline
  spitm=sstr(pitm)
  if(reset):
    curline=0
    pitmsl=[spitm]
    for k in done: done[k] = False
  hd="."*(len(pitmsl)-1)
  c,c2=0,0
  l = sorted(dir(pitm))
  for i in range(len(l)):
    l[i] = (l[i], getattr(pitm, l[i]))
  try:
    if not isinstanceof(pitm, str):
      for i in range(len(pitm)):
        l.append((spitm+'['+str(i)+']',pitm[i]))
  except: pass
  for itm in l:
    c,c2=c+1,c2+1
    isUnsafe = platform >= 0 and '.'.join(pitmsl + [itm[0]]) in unsafe[platform]
    try:
      if isUnsafe: raise Exception
      print(hd+itm[0]+"="+str(itm[1]))
    except:
      print(hd+itm[0])
    if not isUnsafe and isExplorable(itm[1]) and itm[1] != pitm and itm[0] not in pitmsl:
      pitmsl2=pitmsl.copy()
      pitmsl2.append(itm[0])
      c2=c2+explmod(itm[1], pitmsl2, False)[1]
  if c>0 and reset:
    print(hd+"Total: "+str(c)+" 1st level item(s)")
    if c2>0 and c2!=c:
      print(hd+"       "+str(c2)+" item(s)")
  return [c,c2]