test_fglobals.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python
  2. #
  3. # Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
  4. # Copyright (c) 2021-2024 The Uncertainty Quantification Foundation.
  5. # License: 3-clause BSD. The full license text is available at:
  6. # - https://github.com/uqfoundation/dill/blob/master/LICENSE
  7. import dill
  8. dill.settings['recurse'] = True
  9. def get_fun_with_strftime():
  10. def fun_with_strftime():
  11. import datetime
  12. return datetime.datetime.strptime("04-01-1943", "%d-%m-%Y").strftime(
  13. "%Y-%m-%d %H:%M:%S"
  14. )
  15. return fun_with_strftime
  16. def get_fun_with_strftime2():
  17. import datetime
  18. return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  19. def test_doc_dill_issue_219():
  20. back_fn = dill.loads(dill.dumps(get_fun_with_strftime()))
  21. assert back_fn() == "1943-01-04 00:00:00"
  22. dupl = dill.loads(dill.dumps(get_fun_with_strftime2))
  23. assert dupl() == get_fun_with_strftime2()
  24. def get_fun_with_internal_import():
  25. def fun_with_import():
  26. import re
  27. return re.compile("$")
  28. return fun_with_import
  29. def test_method_with_internal_import_should_work():
  30. import re
  31. back_fn = dill.loads(dill.dumps(get_fun_with_internal_import()))
  32. import inspect
  33. if hasattr(inspect, 'getclosurevars'):
  34. vars = inspect.getclosurevars(back_fn)
  35. assert vars.globals == {}
  36. assert vars.nonlocals == {}
  37. assert back_fn() == re.compile("$")
  38. assert "__builtins__" in back_fn.__globals__
  39. if __name__ == "__main__":
  40. import sys
  41. if (sys.version_info[:3] != (3,10,0) or sys.version_info[3] != 'alpha'):
  42. test_doc_dill_issue_219()
  43. test_method_with_internal_import_should_work()