How to use property setter as a callback












3














I'm working with a legacy system for which a Python interface has been added recently.
In my code, I get messages containing ASCII strings for attributes to be set in some wrapper classes.
I would like to use a dictionary to map "data labels" to property setter methods. Each property setter would be used as a "callback" when the corresponding data label is encountered in a message.



Using explicit setters/getters, the essential logic looks like this:



class A():
def __init__(self):
self._x = 1.2

def get_x(self):
return self._x

def set_x(self, value):
self._x = value

myA = A()

myTable = {
'X' : myA.set_x,
}

label, value = get_message()

print(myA.get_x())
# label is 'X', value a float
myTable[label](value)
print(myA.get_x())


This works, but is a bit ugly. I would like to use the @property decorator, but then I don't know how to reference the setter method in the dictionary.
I.e. the following doesn't work.



class B():
def __init__(self):
self._x = 1.2

@property
def x(self):
return self._x

@x.setter
def x(self, value):
self._x = value

myB = B()

myTable = {
'X' : myB.x
}

label, value = get_message()

print(myB.x)
# doesn't work as expected
myTable[label] = value
# no change
print(myB.x)


Of course, the reference to property myB.x in the dictionary definition calls the getter, so a float value is associated to the 'X' key. The myTable[label] = value assignment just replaces this value, it doesn't call the setter.



So, is there a way to get a reference to the property setter to insert in the dictionary and to later invoke as a "callback"?



I dug in reference information and this answer, but can't figure out a solution by myself.



Or, am I getting it wrong and I should follow a different path? (Suggestions welcome).










share|improve this question



























    3














    I'm working with a legacy system for which a Python interface has been added recently.
    In my code, I get messages containing ASCII strings for attributes to be set in some wrapper classes.
    I would like to use a dictionary to map "data labels" to property setter methods. Each property setter would be used as a "callback" when the corresponding data label is encountered in a message.



    Using explicit setters/getters, the essential logic looks like this:



    class A():
    def __init__(self):
    self._x = 1.2

    def get_x(self):
    return self._x

    def set_x(self, value):
    self._x = value

    myA = A()

    myTable = {
    'X' : myA.set_x,
    }

    label, value = get_message()

    print(myA.get_x())
    # label is 'X', value a float
    myTable[label](value)
    print(myA.get_x())


    This works, but is a bit ugly. I would like to use the @property decorator, but then I don't know how to reference the setter method in the dictionary.
    I.e. the following doesn't work.



    class B():
    def __init__(self):
    self._x = 1.2

    @property
    def x(self):
    return self._x

    @x.setter
    def x(self, value):
    self._x = value

    myB = B()

    myTable = {
    'X' : myB.x
    }

    label, value = get_message()

    print(myB.x)
    # doesn't work as expected
    myTable[label] = value
    # no change
    print(myB.x)


    Of course, the reference to property myB.x in the dictionary definition calls the getter, so a float value is associated to the 'X' key. The myTable[label] = value assignment just replaces this value, it doesn't call the setter.



    So, is there a way to get a reference to the property setter to insert in the dictionary and to later invoke as a "callback"?



    I dug in reference information and this answer, but can't figure out a solution by myself.



    Or, am I getting it wrong and I should follow a different path? (Suggestions welcome).










    share|improve this question

























      3












      3








      3







      I'm working with a legacy system for which a Python interface has been added recently.
      In my code, I get messages containing ASCII strings for attributes to be set in some wrapper classes.
      I would like to use a dictionary to map "data labels" to property setter methods. Each property setter would be used as a "callback" when the corresponding data label is encountered in a message.



      Using explicit setters/getters, the essential logic looks like this:



      class A():
      def __init__(self):
      self._x = 1.2

      def get_x(self):
      return self._x

      def set_x(self, value):
      self._x = value

      myA = A()

      myTable = {
      'X' : myA.set_x,
      }

      label, value = get_message()

      print(myA.get_x())
      # label is 'X', value a float
      myTable[label](value)
      print(myA.get_x())


      This works, but is a bit ugly. I would like to use the @property decorator, but then I don't know how to reference the setter method in the dictionary.
      I.e. the following doesn't work.



      class B():
      def __init__(self):
      self._x = 1.2

      @property
      def x(self):
      return self._x

      @x.setter
      def x(self, value):
      self._x = value

      myB = B()

      myTable = {
      'X' : myB.x
      }

      label, value = get_message()

      print(myB.x)
      # doesn't work as expected
      myTable[label] = value
      # no change
      print(myB.x)


      Of course, the reference to property myB.x in the dictionary definition calls the getter, so a float value is associated to the 'X' key. The myTable[label] = value assignment just replaces this value, it doesn't call the setter.



      So, is there a way to get a reference to the property setter to insert in the dictionary and to later invoke as a "callback"?



      I dug in reference information and this answer, but can't figure out a solution by myself.



      Or, am I getting it wrong and I should follow a different path? (Suggestions welcome).










      share|improve this question













      I'm working with a legacy system for which a Python interface has been added recently.
      In my code, I get messages containing ASCII strings for attributes to be set in some wrapper classes.
      I would like to use a dictionary to map "data labels" to property setter methods. Each property setter would be used as a "callback" when the corresponding data label is encountered in a message.



      Using explicit setters/getters, the essential logic looks like this:



      class A():
      def __init__(self):
      self._x = 1.2

      def get_x(self):
      return self._x

      def set_x(self, value):
      self._x = value

      myA = A()

      myTable = {
      'X' : myA.set_x,
      }

      label, value = get_message()

      print(myA.get_x())
      # label is 'X', value a float
      myTable[label](value)
      print(myA.get_x())


      This works, but is a bit ugly. I would like to use the @property decorator, but then I don't know how to reference the setter method in the dictionary.
      I.e. the following doesn't work.



      class B():
      def __init__(self):
      self._x = 1.2

      @property
      def x(self):
      return self._x

      @x.setter
      def x(self, value):
      self._x = value

      myB = B()

      myTable = {
      'X' : myB.x
      }

      label, value = get_message()

      print(myB.x)
      # doesn't work as expected
      myTable[label] = value
      # no change
      print(myB.x)


      Of course, the reference to property myB.x in the dictionary definition calls the getter, so a float value is associated to the 'X' key. The myTable[label] = value assignment just replaces this value, it doesn't call the setter.



      So, is there a way to get a reference to the property setter to insert in the dictionary and to later invoke as a "callback"?



      I dug in reference information and this answer, but can't figure out a solution by myself.



      Or, am I getting it wrong and I should follow a different path? (Suggestions welcome).







      python getter-setter






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 12:57









      arabu

      183




      183
























          1 Answer
          1






          active

          oldest

          votes


















          3














          To access the actual function, you have to access the property directly on the class, so:



          In [1]: class B:
          ...: def __init__(self):
          ...: self._x = 1.2
          ...:
          ...: @property
          ...: def x(self):
          ...: return self._x
          ...:
          ...: @x.setter
          ...: def x(self, value):
          ...: self._x = value
          ...:

          In [2]: B.x.fset
          Out[2]: <function __main__.B.x(self, value)>


          Since functions are descriptors, you can use their __get__ method to bind them and change them into a method:



          In [4]: B.x.fset.__get__(b)(42)

          In [5]: b.x
          Out[5]: 42


          So, something like:



          In [6]: my_table = {'X':B.x.fset.__get__(b)}

          In [7]: my_table['X']('foo')

          In [8]: b.x
          Out[8]: 'foo'





          share|improve this answer





















          • This answers my question, thanks! Now that I see it, calling the property setter via my_table['X']('foo') is basically the same as using explicit setters/getters (my first example), i.e., in my view, a bit cryptic. Is there any way of using my_table['X'] = 'foo'?
            – arabu
            Nov 22 '18 at 6:50






          • 1




            @arabu you'd have to implement your own mapping, override __setitem__
            – juanpa.arrivillaga
            Nov 22 '18 at 16:54













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412553%2fhow-to-use-property-setter-as-a-callback%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          To access the actual function, you have to access the property directly on the class, so:



          In [1]: class B:
          ...: def __init__(self):
          ...: self._x = 1.2
          ...:
          ...: @property
          ...: def x(self):
          ...: return self._x
          ...:
          ...: @x.setter
          ...: def x(self, value):
          ...: self._x = value
          ...:

          In [2]: B.x.fset
          Out[2]: <function __main__.B.x(self, value)>


          Since functions are descriptors, you can use their __get__ method to bind them and change them into a method:



          In [4]: B.x.fset.__get__(b)(42)

          In [5]: b.x
          Out[5]: 42


          So, something like:



          In [6]: my_table = {'X':B.x.fset.__get__(b)}

          In [7]: my_table['X']('foo')

          In [8]: b.x
          Out[8]: 'foo'





          share|improve this answer





















          • This answers my question, thanks! Now that I see it, calling the property setter via my_table['X']('foo') is basically the same as using explicit setters/getters (my first example), i.e., in my view, a bit cryptic. Is there any way of using my_table['X'] = 'foo'?
            – arabu
            Nov 22 '18 at 6:50






          • 1




            @arabu you'd have to implement your own mapping, override __setitem__
            – juanpa.arrivillaga
            Nov 22 '18 at 16:54


















          3














          To access the actual function, you have to access the property directly on the class, so:



          In [1]: class B:
          ...: def __init__(self):
          ...: self._x = 1.2
          ...:
          ...: @property
          ...: def x(self):
          ...: return self._x
          ...:
          ...: @x.setter
          ...: def x(self, value):
          ...: self._x = value
          ...:

          In [2]: B.x.fset
          Out[2]: <function __main__.B.x(self, value)>


          Since functions are descriptors, you can use their __get__ method to bind them and change them into a method:



          In [4]: B.x.fset.__get__(b)(42)

          In [5]: b.x
          Out[5]: 42


          So, something like:



          In [6]: my_table = {'X':B.x.fset.__get__(b)}

          In [7]: my_table['X']('foo')

          In [8]: b.x
          Out[8]: 'foo'





          share|improve this answer





















          • This answers my question, thanks! Now that I see it, calling the property setter via my_table['X']('foo') is basically the same as using explicit setters/getters (my first example), i.e., in my view, a bit cryptic. Is there any way of using my_table['X'] = 'foo'?
            – arabu
            Nov 22 '18 at 6:50






          • 1




            @arabu you'd have to implement your own mapping, override __setitem__
            – juanpa.arrivillaga
            Nov 22 '18 at 16:54
















          3












          3








          3






          To access the actual function, you have to access the property directly on the class, so:



          In [1]: class B:
          ...: def __init__(self):
          ...: self._x = 1.2
          ...:
          ...: @property
          ...: def x(self):
          ...: return self._x
          ...:
          ...: @x.setter
          ...: def x(self, value):
          ...: self._x = value
          ...:

          In [2]: B.x.fset
          Out[2]: <function __main__.B.x(self, value)>


          Since functions are descriptors, you can use their __get__ method to bind them and change them into a method:



          In [4]: B.x.fset.__get__(b)(42)

          In [5]: b.x
          Out[5]: 42


          So, something like:



          In [6]: my_table = {'X':B.x.fset.__get__(b)}

          In [7]: my_table['X']('foo')

          In [8]: b.x
          Out[8]: 'foo'





          share|improve this answer












          To access the actual function, you have to access the property directly on the class, so:



          In [1]: class B:
          ...: def __init__(self):
          ...: self._x = 1.2
          ...:
          ...: @property
          ...: def x(self):
          ...: return self._x
          ...:
          ...: @x.setter
          ...: def x(self, value):
          ...: self._x = value
          ...:

          In [2]: B.x.fset
          Out[2]: <function __main__.B.x(self, value)>


          Since functions are descriptors, you can use their __get__ method to bind them and change them into a method:



          In [4]: B.x.fset.__get__(b)(42)

          In [5]: b.x
          Out[5]: 42


          So, something like:



          In [6]: my_table = {'X':B.x.fset.__get__(b)}

          In [7]: my_table['X']('foo')

          In [8]: b.x
          Out[8]: 'foo'






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 13:03









          juanpa.arrivillaga

          37.2k33470




          37.2k33470












          • This answers my question, thanks! Now that I see it, calling the property setter via my_table['X']('foo') is basically the same as using explicit setters/getters (my first example), i.e., in my view, a bit cryptic. Is there any way of using my_table['X'] = 'foo'?
            – arabu
            Nov 22 '18 at 6:50






          • 1




            @arabu you'd have to implement your own mapping, override __setitem__
            – juanpa.arrivillaga
            Nov 22 '18 at 16:54




















          • This answers my question, thanks! Now that I see it, calling the property setter via my_table['X']('foo') is basically the same as using explicit setters/getters (my first example), i.e., in my view, a bit cryptic. Is there any way of using my_table['X'] = 'foo'?
            – arabu
            Nov 22 '18 at 6:50






          • 1




            @arabu you'd have to implement your own mapping, override __setitem__
            – juanpa.arrivillaga
            Nov 22 '18 at 16:54


















          This answers my question, thanks! Now that I see it, calling the property setter via my_table['X']('foo') is basically the same as using explicit setters/getters (my first example), i.e., in my view, a bit cryptic. Is there any way of using my_table['X'] = 'foo'?
          – arabu
          Nov 22 '18 at 6:50




          This answers my question, thanks! Now that I see it, calling the property setter via my_table['X']('foo') is basically the same as using explicit setters/getters (my first example), i.e., in my view, a bit cryptic. Is there any way of using my_table['X'] = 'foo'?
          – arabu
          Nov 22 '18 at 6:50




          1




          1




          @arabu you'd have to implement your own mapping, override __setitem__
          – juanpa.arrivillaga
          Nov 22 '18 at 16:54






          @arabu you'd have to implement your own mapping, override __setitem__
          – juanpa.arrivillaga
          Nov 22 '18 at 16:54




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412553%2fhow-to-use-property-setter-as-a-callback%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          Refactoring coordinates for Minecraft Pi buildings written in Python