python standalone function return object instance that called it










1














I have a very strange problem.



I need to return a class object to call a function that is supposed to return the class object that called it. I know, I know. Just think of it as a contrived exercise, though for me it is a very real need.



def baz():
# return the object instance that calls me.

class Foo():
def bar(self, func):
return func() # should return the Foo object but how???

new_foo = Foo()
new_foo_instance = new_foo.bar(baz)


is it possible to write anything in baz() that will return the object that called it?



EDIT:



to answer the comments:



I have tried to use inspect, but with no success, I even looked at the entire stack but I cannot find an entry that matches the new_foo object:



new_foo looks like this when I printed it out: <__main__.Foo object at 0x0000029AAFC4C780>



when I printed out the entire stack that entry was not found within it:



def baz():
print(inspect.stack())
return inspect.stack() #[1][3]

>>> [FrameInfo(frame=<frame object at 0x0000029AADB49648>, filename='return_caller.py', lineno=5, function='baz', code_context=[' print(inspect.stack())n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8F0DE8>, filename='return_caller.py', lineno=11, function='bar', code_context=[' return func() # should return the Foo object but how???n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8AC588>, filename='return_caller.py', lineno=19, function='<module>', code_context=['new_foo_instance = new_foo.bar(baz)n'], index=0)]


So I am not trying to get it to return a new instance of Foo, but actually the exact same instance as new_foo.










share|improve this question























  • Have a look at stackoverflow.com/questions/900392/… if it helps. Let me know in comment if you face any issue.
    – hygull
    Nov 10 '18 at 7:37










  • When you call new_foo.bar(baz) what do you expect to return. Is it new Foo instance?
    – Abdul Niyas P M
    Nov 10 '18 at 7:42










  • @AbdulNiyasPM @hygull same instance as new_foo I've edited the question for clearification
    – Legit Stack
    Nov 10 '18 at 7:50






  • 1




    @Legit Stack If that is the case can't you call the function(baz in this case) with self?(ie, return func(self)
    – Abdul Niyas P M
    Nov 10 '18 at 7:52











  • @AbdulNiyasPM oh, yes, I think that modification to bar would work
    – Legit Stack
    Nov 10 '18 at 7:56















1














I have a very strange problem.



I need to return a class object to call a function that is supposed to return the class object that called it. I know, I know. Just think of it as a contrived exercise, though for me it is a very real need.



def baz():
# return the object instance that calls me.

class Foo():
def bar(self, func):
return func() # should return the Foo object but how???

new_foo = Foo()
new_foo_instance = new_foo.bar(baz)


is it possible to write anything in baz() that will return the object that called it?



EDIT:



to answer the comments:



I have tried to use inspect, but with no success, I even looked at the entire stack but I cannot find an entry that matches the new_foo object:



new_foo looks like this when I printed it out: <__main__.Foo object at 0x0000029AAFC4C780>



when I printed out the entire stack that entry was not found within it:



def baz():
print(inspect.stack())
return inspect.stack() #[1][3]

>>> [FrameInfo(frame=<frame object at 0x0000029AADB49648>, filename='return_caller.py', lineno=5, function='baz', code_context=[' print(inspect.stack())n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8F0DE8>, filename='return_caller.py', lineno=11, function='bar', code_context=[' return func() # should return the Foo object but how???n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8AC588>, filename='return_caller.py', lineno=19, function='<module>', code_context=['new_foo_instance = new_foo.bar(baz)n'], index=0)]


So I am not trying to get it to return a new instance of Foo, but actually the exact same instance as new_foo.










share|improve this question























  • Have a look at stackoverflow.com/questions/900392/… if it helps. Let me know in comment if you face any issue.
    – hygull
    Nov 10 '18 at 7:37










  • When you call new_foo.bar(baz) what do you expect to return. Is it new Foo instance?
    – Abdul Niyas P M
    Nov 10 '18 at 7:42










  • @AbdulNiyasPM @hygull same instance as new_foo I've edited the question for clearification
    – Legit Stack
    Nov 10 '18 at 7:50






  • 1




    @Legit Stack If that is the case can't you call the function(baz in this case) with self?(ie, return func(self)
    – Abdul Niyas P M
    Nov 10 '18 at 7:52











  • @AbdulNiyasPM oh, yes, I think that modification to bar would work
    – Legit Stack
    Nov 10 '18 at 7:56













1












1








1







I have a very strange problem.



I need to return a class object to call a function that is supposed to return the class object that called it. I know, I know. Just think of it as a contrived exercise, though for me it is a very real need.



def baz():
# return the object instance that calls me.

class Foo():
def bar(self, func):
return func() # should return the Foo object but how???

new_foo = Foo()
new_foo_instance = new_foo.bar(baz)


is it possible to write anything in baz() that will return the object that called it?



EDIT:



to answer the comments:



I have tried to use inspect, but with no success, I even looked at the entire stack but I cannot find an entry that matches the new_foo object:



new_foo looks like this when I printed it out: <__main__.Foo object at 0x0000029AAFC4C780>



when I printed out the entire stack that entry was not found within it:



def baz():
print(inspect.stack())
return inspect.stack() #[1][3]

>>> [FrameInfo(frame=<frame object at 0x0000029AADB49648>, filename='return_caller.py', lineno=5, function='baz', code_context=[' print(inspect.stack())n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8F0DE8>, filename='return_caller.py', lineno=11, function='bar', code_context=[' return func() # should return the Foo object but how???n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8AC588>, filename='return_caller.py', lineno=19, function='<module>', code_context=['new_foo_instance = new_foo.bar(baz)n'], index=0)]


So I am not trying to get it to return a new instance of Foo, but actually the exact same instance as new_foo.










share|improve this question















I have a very strange problem.



I need to return a class object to call a function that is supposed to return the class object that called it. I know, I know. Just think of it as a contrived exercise, though for me it is a very real need.



def baz():
# return the object instance that calls me.

class Foo():
def bar(self, func):
return func() # should return the Foo object but how???

new_foo = Foo()
new_foo_instance = new_foo.bar(baz)


is it possible to write anything in baz() that will return the object that called it?



EDIT:



to answer the comments:



I have tried to use inspect, but with no success, I even looked at the entire stack but I cannot find an entry that matches the new_foo object:



new_foo looks like this when I printed it out: <__main__.Foo object at 0x0000029AAFC4C780>



when I printed out the entire stack that entry was not found within it:



def baz():
print(inspect.stack())
return inspect.stack() #[1][3]

>>> [FrameInfo(frame=<frame object at 0x0000029AADB49648>, filename='return_caller.py', lineno=5, function='baz', code_context=[' print(inspect.stack())n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8F0DE8>, filename='return_caller.py', lineno=11, function='bar', code_context=[' return func() # should return the Foo object but how???n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8AC588>, filename='return_caller.py', lineno=19, function='<module>', code_context=['new_foo_instance = new_foo.bar(baz)n'], index=0)]


So I am not trying to get it to return a new instance of Foo, but actually the exact same instance as new_foo.







python metaprogramming






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 '18 at 7:49

























asked Nov 10 '18 at 7:33









Legit Stack

670619




670619











  • Have a look at stackoverflow.com/questions/900392/… if it helps. Let me know in comment if you face any issue.
    – hygull
    Nov 10 '18 at 7:37










  • When you call new_foo.bar(baz) what do you expect to return. Is it new Foo instance?
    – Abdul Niyas P M
    Nov 10 '18 at 7:42










  • @AbdulNiyasPM @hygull same instance as new_foo I've edited the question for clearification
    – Legit Stack
    Nov 10 '18 at 7:50






  • 1




    @Legit Stack If that is the case can't you call the function(baz in this case) with self?(ie, return func(self)
    – Abdul Niyas P M
    Nov 10 '18 at 7:52











  • @AbdulNiyasPM oh, yes, I think that modification to bar would work
    – Legit Stack
    Nov 10 '18 at 7:56
















  • Have a look at stackoverflow.com/questions/900392/… if it helps. Let me know in comment if you face any issue.
    – hygull
    Nov 10 '18 at 7:37










  • When you call new_foo.bar(baz) what do you expect to return. Is it new Foo instance?
    – Abdul Niyas P M
    Nov 10 '18 at 7:42










  • @AbdulNiyasPM @hygull same instance as new_foo I've edited the question for clearification
    – Legit Stack
    Nov 10 '18 at 7:50






  • 1




    @Legit Stack If that is the case can't you call the function(baz in this case) with self?(ie, return func(self)
    – Abdul Niyas P M
    Nov 10 '18 at 7:52











  • @AbdulNiyasPM oh, yes, I think that modification to bar would work
    – Legit Stack
    Nov 10 '18 at 7:56















Have a look at stackoverflow.com/questions/900392/… if it helps. Let me know in comment if you face any issue.
– hygull
Nov 10 '18 at 7:37




Have a look at stackoverflow.com/questions/900392/… if it helps. Let me know in comment if you face any issue.
– hygull
Nov 10 '18 at 7:37












When you call new_foo.bar(baz) what do you expect to return. Is it new Foo instance?
– Abdul Niyas P M
Nov 10 '18 at 7:42




When you call new_foo.bar(baz) what do you expect to return. Is it new Foo instance?
– Abdul Niyas P M
Nov 10 '18 at 7:42












@AbdulNiyasPM @hygull same instance as new_foo I've edited the question for clearification
– Legit Stack
Nov 10 '18 at 7:50




@AbdulNiyasPM @hygull same instance as new_foo I've edited the question for clearification
– Legit Stack
Nov 10 '18 at 7:50




1




1




@Legit Stack If that is the case can't you call the function(baz in this case) with self?(ie, return func(self)
– Abdul Niyas P M
Nov 10 '18 at 7:52





@Legit Stack If that is the case can't you call the function(baz in this case) with self?(ie, return func(self)
– Abdul Niyas P M
Nov 10 '18 at 7:52













@AbdulNiyasPM oh, yes, I think that modification to bar would work
– Legit Stack
Nov 10 '18 at 7:56




@AbdulNiyasPM oh, yes, I think that modification to bar would work
– Legit Stack
Nov 10 '18 at 7:56












2 Answers
2






active

oldest

votes


















3














Use inspect:



import inspect

def baz():
frame_infos = inspect.stack() # A list of FrameInfo.
frame = frame_infos[1].frame # The frame of the caller.
locs = frame.f_locals # The caller's locals dict.
return locs['self']

class Foo():
def bar(self, func):
return func()

f1 = Foo()
f2 = f1.bar(baz)
print(f1)
print(f2)
print(f2 is f1) # True


Or cheat:



def baz():
return getattr(baz, 'self', None)

class Foo():
def bar(self, func):
func.self = self # Functions can be a place to store global information.
return func()





share|improve this answer






























    1














    The above answer is perfect and this is another way to fulfill your need.



    import sys 
    import inspect

    def baz():
    """
    Return the object instance whose method calls me
    """
    for item in dir(sys.modules[__name__]):
    elem = eval(item)

    if inspect.isclass(elem):
    foo_instance = elem()
    break

    return foo_instance

    class Foo():
    """
    Foo class
    """
    def bar(self, func):
    return func() # should return the Foo object but how???

    # Instantiation and calling
    new_foo = Foo()
    new_foo_instance = new_foo.bar(baz)

    print(new_foo_instance) # <__main__.Foo object at 0x0000015C5A2F59E8>
    print(type(new_foo_instance)) # <class '__main__.Fo


    # E:UsersRishikeshProjectsPython3try>python Get_caller_object_final.py
    # <__main__.Foo object at 0x0000015C5A2F59E8>
    # <class '__main__.Foo'>


    References »

    • How can I get a list of all classes within current module in Python?

    • Python: get only classes defined in imported module with dir()?





    share|improve this answer






















      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%2f53236931%2fpython-standalone-function-return-object-instance-that-called-it%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      Use inspect:



      import inspect

      def baz():
      frame_infos = inspect.stack() # A list of FrameInfo.
      frame = frame_infos[1].frame # The frame of the caller.
      locs = frame.f_locals # The caller's locals dict.
      return locs['self']

      class Foo():
      def bar(self, func):
      return func()

      f1 = Foo()
      f2 = f1.bar(baz)
      print(f1)
      print(f2)
      print(f2 is f1) # True


      Or cheat:



      def baz():
      return getattr(baz, 'self', None)

      class Foo():
      def bar(self, func):
      func.self = self # Functions can be a place to store global information.
      return func()





      share|improve this answer



























        3














        Use inspect:



        import inspect

        def baz():
        frame_infos = inspect.stack() # A list of FrameInfo.
        frame = frame_infos[1].frame # The frame of the caller.
        locs = frame.f_locals # The caller's locals dict.
        return locs['self']

        class Foo():
        def bar(self, func):
        return func()

        f1 = Foo()
        f2 = f1.bar(baz)
        print(f1)
        print(f2)
        print(f2 is f1) # True


        Or cheat:



        def baz():
        return getattr(baz, 'self', None)

        class Foo():
        def bar(self, func):
        func.self = self # Functions can be a place to store global information.
        return func()





        share|improve this answer

























          3












          3








          3






          Use inspect:



          import inspect

          def baz():
          frame_infos = inspect.stack() # A list of FrameInfo.
          frame = frame_infos[1].frame # The frame of the caller.
          locs = frame.f_locals # The caller's locals dict.
          return locs['self']

          class Foo():
          def bar(self, func):
          return func()

          f1 = Foo()
          f2 = f1.bar(baz)
          print(f1)
          print(f2)
          print(f2 is f1) # True


          Or cheat:



          def baz():
          return getattr(baz, 'self', None)

          class Foo():
          def bar(self, func):
          func.self = self # Functions can be a place to store global information.
          return func()





          share|improve this answer














          Use inspect:



          import inspect

          def baz():
          frame_infos = inspect.stack() # A list of FrameInfo.
          frame = frame_infos[1].frame # The frame of the caller.
          locs = frame.f_locals # The caller's locals dict.
          return locs['self']

          class Foo():
          def bar(self, func):
          return func()

          f1 = Foo()
          f2 = f1.bar(baz)
          print(f1)
          print(f2)
          print(f2 is f1) # True


          Or cheat:



          def baz():
          return getattr(baz, 'self', None)

          class Foo():
          def bar(self, func):
          func.self = self # Functions can be a place to store global information.
          return func()






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 10 '18 at 8:18

























          answered Nov 10 '18 at 7:54









          FMc

          32.9k1060124




          32.9k1060124























              1














              The above answer is perfect and this is another way to fulfill your need.



              import sys 
              import inspect

              def baz():
              """
              Return the object instance whose method calls me
              """
              for item in dir(sys.modules[__name__]):
              elem = eval(item)

              if inspect.isclass(elem):
              foo_instance = elem()
              break

              return foo_instance

              class Foo():
              """
              Foo class
              """
              def bar(self, func):
              return func() # should return the Foo object but how???

              # Instantiation and calling
              new_foo = Foo()
              new_foo_instance = new_foo.bar(baz)

              print(new_foo_instance) # <__main__.Foo object at 0x0000015C5A2F59E8>
              print(type(new_foo_instance)) # <class '__main__.Fo


              # E:UsersRishikeshProjectsPython3try>python Get_caller_object_final.py
              # <__main__.Foo object at 0x0000015C5A2F59E8>
              # <class '__main__.Foo'>


              References »

              • How can I get a list of all classes within current module in Python?

              • Python: get only classes defined in imported module with dir()?





              share|improve this answer



























                1














                The above answer is perfect and this is another way to fulfill your need.



                import sys 
                import inspect

                def baz():
                """
                Return the object instance whose method calls me
                """
                for item in dir(sys.modules[__name__]):
                elem = eval(item)

                if inspect.isclass(elem):
                foo_instance = elem()
                break

                return foo_instance

                class Foo():
                """
                Foo class
                """
                def bar(self, func):
                return func() # should return the Foo object but how???

                # Instantiation and calling
                new_foo = Foo()
                new_foo_instance = new_foo.bar(baz)

                print(new_foo_instance) # <__main__.Foo object at 0x0000015C5A2F59E8>
                print(type(new_foo_instance)) # <class '__main__.Fo


                # E:UsersRishikeshProjectsPython3try>python Get_caller_object_final.py
                # <__main__.Foo object at 0x0000015C5A2F59E8>
                # <class '__main__.Foo'>


                References »

                • How can I get a list of all classes within current module in Python?

                • Python: get only classes defined in imported module with dir()?





                share|improve this answer

























                  1












                  1








                  1






                  The above answer is perfect and this is another way to fulfill your need.



                  import sys 
                  import inspect

                  def baz():
                  """
                  Return the object instance whose method calls me
                  """
                  for item in dir(sys.modules[__name__]):
                  elem = eval(item)

                  if inspect.isclass(elem):
                  foo_instance = elem()
                  break

                  return foo_instance

                  class Foo():
                  """
                  Foo class
                  """
                  def bar(self, func):
                  return func() # should return the Foo object but how???

                  # Instantiation and calling
                  new_foo = Foo()
                  new_foo_instance = new_foo.bar(baz)

                  print(new_foo_instance) # <__main__.Foo object at 0x0000015C5A2F59E8>
                  print(type(new_foo_instance)) # <class '__main__.Fo


                  # E:UsersRishikeshProjectsPython3try>python Get_caller_object_final.py
                  # <__main__.Foo object at 0x0000015C5A2F59E8>
                  # <class '__main__.Foo'>


                  References »

                  • How can I get a list of all classes within current module in Python?

                  • Python: get only classes defined in imported module with dir()?





                  share|improve this answer














                  The above answer is perfect and this is another way to fulfill your need.



                  import sys 
                  import inspect

                  def baz():
                  """
                  Return the object instance whose method calls me
                  """
                  for item in dir(sys.modules[__name__]):
                  elem = eval(item)

                  if inspect.isclass(elem):
                  foo_instance = elem()
                  break

                  return foo_instance

                  class Foo():
                  """
                  Foo class
                  """
                  def bar(self, func):
                  return func() # should return the Foo object but how???

                  # Instantiation and calling
                  new_foo = Foo()
                  new_foo_instance = new_foo.bar(baz)

                  print(new_foo_instance) # <__main__.Foo object at 0x0000015C5A2F59E8>
                  print(type(new_foo_instance)) # <class '__main__.Fo


                  # E:UsersRishikeshProjectsPython3try>python Get_caller_object_final.py
                  # <__main__.Foo object at 0x0000015C5A2F59E8>
                  # <class '__main__.Foo'>


                  References »

                  • How can I get a list of all classes within current module in Python?

                  • Python: get only classes defined in imported module with dir()?






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 10 '18 at 15:57

























                  answered Nov 10 '18 at 8:22









                  hygull

                  3,25411228




                  3,25411228



























                      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%2f53236931%2fpython-standalone-function-return-object-instance-that-called-it%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

                      𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                      Crossroads (UK TV series)

                      ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế