Lib.hx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package python;
  2. import python.internal.AnonObject;
  3. import python.lib.Dict;
  4. import python.NativeStringTools;
  5. typedef PySys = python.lib.Sys;
  6. class Lib {
  7. public static function print(v:Dynamic):Void {
  8. var str = Std.string(v);
  9. PySys.stdout.buffer.write( NativeStringTools.encode(str, "utf-8"));
  10. PySys.stdout.flush();
  11. }
  12. public static function println(v:Dynamic):Void {
  13. var str = Std.string(v);
  14. PySys.stdout.buffer.write( NativeStringTools.encode('$str\n', "utf-8"));
  15. PySys.stdout.flush();
  16. }
  17. /**
  18. Returns an anonymous Object which holds the same data as the Dictionary `v`.
  19. **/
  20. public static function dictToAnon (v:Dict<String, Dynamic>):Dynamic {
  21. return new AnonObject(v.copy());
  22. }
  23. /**
  24. Returns a flat copy of the underlying Dictionary of `o`.
  25. **/
  26. public static function anonToDict (o:{}):Dict<String, Dynamic> {
  27. return if (python.lib.Builtin.isinstance(o, AnonObject))
  28. {
  29. (Syntax.field(o, "__dict__"):Dict<String,Dynamic>).copy();
  30. }
  31. else null;
  32. }
  33. /**
  34. Returns the underlying Dictionary of the anonymous object `o`.
  35. Modifications to this dictionary are reflected in the anonymous Object too.
  36. **/
  37. public static function anonAsDict (o:{}):Dict<String, Dynamic> {
  38. return if (python.lib.Builtin.isinstance(o, AnonObject))
  39. {
  40. (Syntax.field(o, "__dict__"):Dict<String,Dynamic>);
  41. }
  42. else null;
  43. }
  44. /**
  45. Returns the Dictionary `d` as an anonymous Object.
  46. Modifications to the object are reflected in the Dictionary too.
  47. **/
  48. public static function dictAsAnon (d:Dict<String, Dynamic>):Dynamic {
  49. return new AnonObject(d);
  50. }
  51. public static function toPythonIterable <T>(it:Iterable<T>):python.NativeIterable<T> {
  52. return {
  53. __iter__ : function () {
  54. var it1 = it.iterator();
  55. var self:NativeIterator<T> = null;
  56. self = new NativeIterator({
  57. __next__ : function ():T {
  58. if (it1.hasNext()) {
  59. return it1.next();
  60. } else {
  61. throw new python.lib.Exceptions.StopIteration();
  62. }
  63. },
  64. __iter__ : function () return self
  65. });
  66. return self;
  67. }
  68. }
  69. }
  70. public static inline function toHaxeIterable <T>(it:NativeIterable<T>):HaxeIterable<T> {
  71. return new HaxeIterable(it);
  72. }
  73. public static inline function toHaxeIterator <T>(it:NativeIterator<T>):HaxeIterator<T> {
  74. return new HaxeIterator(it);
  75. }
  76. }