inspect.currentframe() can depending on the python implementation return None as stated in the documentation:

CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

mypy is just letting you know that's the case. To handle this you can just check if the return of currentframe() is None

from types import FrameType
frame = inspect.currentframe()
if frame is None:
    raise RuntimeError("unsupported python implementation")  # or give a default name
fn_name: str = frame.f_code.co_name
🌐
GitHub
github.com › pandas-dev › pandas › issues › 48733
BUG: AttributeError: 'function' object has no attribute 'currentframe' · Issue #48733 · pandas-dev/pandas
September 23, 2022 - Traceback (most recent call last): File "C:\Users\artur\PycharmProjects\Ex_Files_Python_EssT\Exercise Files\Chap02\pandas_debug.py", line 15, in db.check_case_sensitive("TABLE2", "") File "C:\Users\artur\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\io\sql.py", line 1664, in check_case_sensitive stacklevel=find_stack_level(inspect.currentframe()), AttributeError: 'function' object has no attribute 'currentframe' Same code was passing till version 1.4.4 ·
Author   huka81
Discussions

python - inspect.getargvalues() throws exception "AttributeError: 'tuple' object has no attribute 'f_code'" - Stack Overflow
I've googled that AttributeError exception, but with no luck. What am I doing wrong? (I've since found the problem, so I'm asking-and-answering this here so anyone who has this problem in future will find the answer here.) ... This similar question helped me discover the problem. The Python documentation for the inspect module mentions both "frame records" and "frame objects", and explains the difference. inspect.currentframe... More on stackoverflow.com
🌐 stackoverflow.com
August 17, 2017
final project - AttributeError: 'function' object has no attribute 'method' - CS50 Stack Exchange
Hey guys I've been working on my final project. I keep running into this error When I run flask, this error occurs File "/home/ubuntu/project/app.py", line 88, in login if request.method ... More on cs50.stackexchange.com
🌐 cs50.stackexchange.com
python - How to Prevent "AttributeError: 'function' object has no attribute ''" - Stack Overflow
I have been working on a program that is meant to encrypt messages inputted by the user. There are two encryption options, and the second one is meant to make each character in the message what it ... More on stackoverflow.com
🌐 stackoverflow.com
python - AttributeError when using pandas to_sql - Stack Overflow
AttributeError: 'function' object has no attribute 'currentframe' More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
python-list.python.narkive.com › E1Bg6h0e › i-think-i-found-a-bug-in-python-2-6-4-in-the-inspect-module
I think I found a bug in Python 2.6.4 (in the inspect module)
dir(a) ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr_ _', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globa ls__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__' , '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subcla sshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc' , 'func_globals', 'func_name'] So i'm guessing that the attribute has been changed from func_code to f_code but the inspect module wasn't updated to reflect that. No, that wasn't the case. The argument of inspect.getargvalues() is a 'frame object' not 'function object'. ... inspect.getargvalues(inspect.currentframe()) You could argue that the error message is misleading (should be TypeError instead), do you want a bug report on that?
🌐
Databricks
kb.databricks.com › en_US › python › function-object-no-attribute
AttributeError: 'function' object has no attribute
May 19, 2022 - Using protected keywords from the DataFrame API as column names results in a function object has no attribute error message.
Top answer
1 of 2
7

This similar question helped me discover the problem.

The Python documentation for the inspect module mentions both "frame records" and "frame objects", and explains the difference.

  • inspect.currentframe() returns a frame object, but
  • inspect.getouterframes() returns a list of frame records.

The mistake in the code above is not extracting the frame object from the frame record of the calling function, and passing inspect.getouterframes() the frame record instead of the frame object. (Note that inspect.getouterframes() doesn't check that its argument is a frame object.)

Here's the fixed definition of caller_args() (with the change to the assignment to caller_frame):

def caller_args():
    frame = inspect.currentframe()
    outer_frames = inspect.getouterframes(frame)
    caller_frame = outer_frames[1][0]
    return inspect.getargvalues(caller_frame)

Which runs as desired:

$ python getargvalues_test_fixed.py
ArgInfo(args=['arg1'], varargs=None, keywords=None, locals={'arg1': 'foo'})
2 of 2
-1

cause of error

AttributeError: 'tuple' object has no attribute 'f_code'

in your function

def caller_args()

is that caller_frame is an array of which you need item [1][0] as argument for

inspect.getargvalues(...)

this works :

currframe = inspect.currentframe()
callerframe = inspect.getouterframes(currframe, 2)
inspect.getargvalues(callerframe[1][0])

Also, the getargvalues function returns 4 values. First three are unimportant in this case, fourth contains JSON like format key/value list of callerframe arguments

 _,_,_,values = inspect.getargvalues(callerframe[1][0])
 for i in values:
     argsstring += str(i) + ' : ' + str(values[i])

My test looks like this :

import inspect

def log(text):
    currframe = inspect.currentframe()
    callerframe = inspect.getouterframes(currframe, 2)
    _,_,_,values = inspect.getargvalues(callerframe[1][0])
    argsstring = ''
    for i in values:
        argsstring += str(i) + ' : ' + str(values[i])
    print('name of file : ' + callerframe[1][1])
    print('name of function : ' + callerframe[1][3])
    print('line number : ' + str(callerframe[1][2]))
    print('caller function arguments : ' + argsstring)

def doTest(text):
    log(text) 

doTest('this is a test')
🌐
Itsourcecode
itsourcecode.com › home › attributeerror: ‘function’ object has no attribute
attributeerror: 'function' object has no attribute [SOLVED]
April 17, 2023 - It is possible that you might misspell the attribute or method that you are trying to access. Make sure that the spelling matches exactly with what you are using. ... def my_function(): return "This is an example of function object has no attribute!" print(my_function.lenght) # incorrect spelling
Find elsewhere
🌐
JetBrains
youtrack.jetbrains.com › issue › PY-8940
'function' object has no attribute 'func_closure'" : PY-8940
November 1, 2021 - {{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Cumulative Sum
cumsum.wordpress.com › 2021 › 03 › 05 › pandas-attributeerror-function-object-has-no-attribute-xxx
[pandas] AttributeError: 'function' object has no attribute xxx
March 6, 2021 - This error happens when you have a column name which conflicts with an existing method defined for data frame instance. For instance, given a data frame as below: df = pd.DataFrame({'count': ['yes', 'no', 'yes']}) df # count #0 yes #1 no #2 ...
🌐
Codecademy
codecademy.com › forum_questions › 534f3c4b52f8637aa1000033
Practice Makes Perfect : Function Object Has No Attribute Append Error | Codecademy
In the line “reverse.append((characters[count]))” you are trying to append to your function(an object), if you probably want to reverse text instead.
🌐
GitHub
github.com › salesforce › CodeTF › issues › 29
AttributeError: 'function' object has no attribute '__func__' · Issue #29 · salesforce/CodeTF
June 13, 2023 - 1759 model, self.optimizer, self.lr_scheduler = self.accelerator.prepare( 1760 self.model, self.optimizer, self.lr_scheduler 1761 ) File [~/.conda/envs/codetf/lib/python3.8/site-packages/accelerate/accelerator.py:1182](https://vscode-remote+wsl-002bubuntu.vscode-resource.vscode-cdn.net/home/paul/projects/edu/master/mdl-ii/src/modeling/~/.conda/envs/codetf/lib/python3.8/site-packages/accelerate/accelerator.py:1182), in Accelerator.prepare(self, device_placement, *args) 1180 result = self._prepare_megatron_lm(*args) 1181 else: -> 1182 result = tuple( 1183 self._prepare_one(obj, first_pass=True,
Author   Paul-B98
🌐
Fast.ai
forums.fast.ai › fastai
Resnet34 model: AttributeError: function object has no attribute 'children' - fastai - fast.ai Course Forums
August 11, 2022 - I was able to successfully create the model body you are looking for by instantiating the model class like this: create_body(resnet34(), cut=-2) · Additionally, I had to use from fastai.vision.all import * instead of just importing fastai (the top level library) · Sorry for the late reply, ...
🌐
Stack Overflow
stackoverflow.com › questions › 73048265 › attributeerror-function-object-has-no-attribute-gamesstate
python - AttributeError: 'function' object has no attribute 'GamesState' - Stack Overflow
July 20, 2022 - Traceback (most recent call last): File "/home/pj/PycharmProjects/Chess Game/ChessMain.py", line 34, in <module> main() File "/home/pj/PycharmProjects/Chess Game/ChessMain.py", line 31, in main gs = chess_engines.GamesState() AttributeError: type object 'ChessEngine' has no attribute 'GamesState' ... The class is called GameState and you try to access GamesState. Additionally there's an error in your GameState class. You defined the function as _init_, but it's called __init__ (magic methods have double underscores).
🌐
Django Forum
forum.djangoproject.com › using django › forms & apis
Don't know how to fix AttributeError: 'function' object has no attribute 'pk' when trying to create new users from registration form - Forms & APIs - Django Forum
September 2, 2023 - Hi, I’m still very new to Python and Django. I am trying to create a working registration page and i get this error when submitting the form. I can’t find this error when looking on stack overflow or the forum and don’t know how to fix this issue. I copied the views and models code here.
🌐
Reddit
reddit.com › r/learnpython › what is "attributeerror: 'function' object has no attribute 'find'"
r/learnpython on Reddit: what is "AttributeError: 'function' object has no attribute 'find'"
June 18, 2022 -
morseCodeM={".-":"A",
            "-...":"B",
            "-.-.":"C",
            "-..":"D",
            ".":"E",
            "..-.":"F",
            "--.":"G",
            "....":"H",
            "..":"I",
            ".---":"J",
            "-.-":"K",
            ".-..":"L",
            "--":"M",
            "-.":"N",
            "---":"O",
            ".--.":"P",
            "--.-":"Q",
            ".-.":"R",
            "...":"S",
            "-":"T",
            "..-":"U",
            "...-":"V",
            ".--":"W",
            "-..-":"x",
            "-.--":"Y",
            "--..":"Z",
            " / ":" "}
def morseToText(inp):
  out=""
  while(inp!=" "):
    for i in morseCodeM:
      if(inp.find(i)!=-1):    <-----------------------
        out=out+morseCodeM[i]
        inp2=list(inp)
        inp2[inp.find(i):inp.find(i)+(len(i)-1)]=""
        inp="".join(inp2)
        return out

I honestly don't know whats wrong it just gives the error :"AttributeError: 'function' object has no attribute 'find'" on the line with the arrow .

edit: the code is about converting morse code to text