Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# Exports 

2 

3__all__ = ( 

4 "python_to_js", 

5) 

6 

7# Functions 

8 

9 

10def python_to_js(value): 

11 """Convert the given value to the most appropriate JavaScript output." 

12 

13 :param value: The Python value to be converted to JavaScript. 

14 :type value: bool | dict | float | int | list | str | tuple 

15 

16 :rtype: str 

17 :raise: ValueError 

18 

19 """ 

20 if type(value) is bool: 

21 if value is True: 

22 return "true" 

23 

24 return "false" 

25 elif type(value) is dict: 

26 

27 keys = list() 

28 for key in value.keys(): 

29 keys.append(key) 

30 

31 a = list() 

32 for key in keys: 

33 _value = value[key] 

34 

35 if type(_value) is dict: 

36 output = '%s: {' % key 

37 output += python_to_js(value[key]) 

38 output += "}" 

39 else: 

40 output = '%s: %s' % (key, python_to_js(_value)) 

41 

42 a.append(output) 

43 

44 return ", ".join(a) 

45 elif type(value) is float: 

46 return str(value) 

47 elif type(value) is int: 

48 return str(value) 

49 elif type(value) in (list, tuple): 

50 return str(value) 

51 elif type(value) is str: 

52 return '"%s"' % value 

53 else: 

54 raise ValueError("Unsupported value for Python to JS conversion: %s" % type(value))