python standalone function return object instance that called it
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
add a comment |
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
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 callnew_foo.bar(baz)
what do you expect to return. Is it newFoo
instance?
– Abdul Niyas P M
Nov 10 '18 at 7:42
@AbdulNiyasPM @hygull same instance asnew_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) withself
?(ie,return func(self)
– Abdul Niyas P M
Nov 10 '18 at 7:52
@AbdulNiyasPM oh, yes, I think that modification tobar
would work
– Legit Stack
Nov 10 '18 at 7:56
add a comment |
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
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
python metaprogramming
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 callnew_foo.bar(baz)
what do you expect to return. Is it newFoo
instance?
– Abdul Niyas P M
Nov 10 '18 at 7:42
@AbdulNiyasPM @hygull same instance asnew_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) withself
?(ie,return func(self)
– Abdul Niyas P M
Nov 10 '18 at 7:52
@AbdulNiyasPM oh, yes, I think that modification tobar
would work
– Legit Stack
Nov 10 '18 at 7:56
add a comment |
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 callnew_foo.bar(baz)
what do you expect to return. Is it newFoo
instance?
– Abdul Niyas P M
Nov 10 '18 at 7:42
@AbdulNiyasPM @hygull same instance asnew_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) withself
?(ie,return func(self)
– Abdul Niyas P M
Nov 10 '18 at 7:52
@AbdulNiyasPM oh, yes, I think that modification tobar
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
add a comment |
2 Answers
2
active
oldest
votes
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()
add a comment |
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()?
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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()
add a comment |
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()
add a comment |
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()
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()
edited Nov 10 '18 at 8:18
answered Nov 10 '18 at 7:54
FMc
32.9k1060124
32.9k1060124
add a comment |
add a comment |
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()?
add a comment |
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()?
add a comment |
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()?
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()?
edited Nov 10 '18 at 15:57
answered Nov 10 '18 at 8:22
hygull
3,25411228
3,25411228
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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 newFoo
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) withself
?(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