adambard / learnxinyminutes-docs

Code documentation written as code! How novel and totally my idea!
https://learnxinyminutes.com/
Other
11.44k stars 3.32k forks source link

[python/en] wrappers issue #4870

Open annakz1 opened 6 months ago

annakz1 commented 6 months ago

I saw 2 issues in the '7. Advanced' section:

  1. In the "log_function" wrapper I don't see the '3' printed as explained: my_function(1,2) # => "Entering function my_function"
    # => "3" # => "Exiting function my_function" For the '3' to be printed I needed to add print(result) inside the log_function- I would suggest adding it.
  2. The last line in the article didn't work for me- print(my_function.__code__.co_argcount) # => prints 0 instead of 2 as expected. I see in debugger that co_argcount inside the wrapper function=2, but it prints 0 for print(my_function.__code__.co_argcount). Could it be that co_argcount is not supported in the functools @wraps?
jklebes commented 1 week ago

The code:

my_function(1,2) # => "Entering function my_function"
                               # => "3"
                               # => "Exiting function my_function"

# But there's a problem.
# What happens if we try to get some information about my_function?

print(my_function.__name__) # => 'wrapper'
print(my_function.__code__.co_argcount) # => 0. The argcount is 0 because both arguments in wrapper()'s signature are optional.
  1. For me (terminal interactive session) it prints

    Entering function my_function
    Exiting function my_function
    3

    in this different order. The two text lines are printed to terminal because of print(), while 3 is the return value of the function call and is printed only on REPL that echo return values.
    I suspect @annakz1 ran this block of examples in something like jupyter notebook with multiple evaluations in the same cell. Printing return values is not guaranteed on jupyter notebook: only the last return value of the cell is printed. Try running my_function(1,2) in its own cell.

  2. I don't see the problem, the code returns 0 and the comment leads one to expect 0, with explanation. This was already the case at the time of filing the issue. However the line is a bit long and the explanation is not visible without side-scrolling.