Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mapping_context.py 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """
  2. Checks that only valid values are used in a mapping context.
  3. """
  4. # pylint: disable=missing-docstring,invalid-name,too-few-public-methods,no-self-use,import-error,wrong-import-position
  5. from __future__ import print_function
  6. def test(**kwargs):
  7. print(kwargs)
  8. # dictionary value/comprehension
  9. dict_value = dict(a=1, b=2, c=3)
  10. dict_comp = {chr(x): x for x in range(256)}
  11. test(**dict_value)
  12. test(**dict_comp)
  13. # in order to be used in kwargs custom mapping class should define
  14. # __iter__(), __getitem__(key) and keys().
  15. class CustomMapping(object):
  16. def __init__(self):
  17. self.data = dict(a=1, b=2, c=3, d=4, e=5)
  18. def __getitem__(self, key):
  19. return self.data[key]
  20. def keys(self):
  21. return self.data.keys()
  22. test(**CustomMapping())
  23. test(**CustomMapping) # [not-a-mapping]
  24. class NotMapping(object):
  25. pass
  26. test(**NotMapping()) # [not-a-mapping]
  27. # skip checks if statement is inside mixin/base/abstract class
  28. class SomeMixin(object):
  29. kwargs = None
  30. def get_kwargs(self):
  31. return self.kwargs
  32. def run(self, **kwargs):
  33. print(kwargs)
  34. def dispatch(self):
  35. kws = self.get_kwargs()
  36. self.run(**kws)
  37. class AbstractThing(object):
  38. kwargs = None
  39. def get_kwargs(self):
  40. return self.kwargs
  41. def run(self, **kwargs):
  42. print(kwargs)
  43. def dispatch(self):
  44. kws = self.get_kwargs()
  45. self.run(**kws)
  46. class BaseThing(object):
  47. kwargs = None
  48. def get_kwargs(self):
  49. return self.kwargs
  50. def run(self, **kwargs):
  51. print(kwargs)
  52. def dispatch(self):
  53. kws = self.get_kwargs()
  54. self.run(**kws)
  55. # abstract class
  56. class Thing(object):
  57. def get_kwargs(self):
  58. raise NotImplementedError
  59. def run(self, **kwargs):
  60. print(kwargs)
  61. def dispatch(self):
  62. kwargs = self.get_kwargs()
  63. self.run(**kwargs)
  64. # skip uninferable instances
  65. from some_missing_module import Mapping
  66. class MyClass(Mapping):
  67. pass
  68. test(**MyClass())
  69. class HasDynamicGetattr(object):
  70. def __init__(self):
  71. self._obj = {}
  72. def __getattr__(self, attr):
  73. return getattr(self._obj, attr)
  74. test(**HasDynamicGetattr())