mCodingLLC / VideosSampleCode

Code from the mCoding sample videos
MIT License
952 stars 198 forks source link

AttributeError: __enter__ #5

Closed sarimmehdi closed 2 years ago

sarimmehdi commented 2 years ago

I am using the following function as a decorator:

def profile_func(func):
    def decorator_func(*args, **kwargs):
        with cProfile.Profile() as pr:
            val = func(*args, **kwargs)
        stats = pstats.Stats(pr)
        stats.sort_stats(pstats.SortKey.TIME)
        stats.dump_stats(filename=os.path.join(memex_utils.config.session, 'profiling.prof'))
        return val
    return decorator_func

But I get the following error:

with cProfile.Profile() as pr:
AttributeError: __enter__

I am using Python 3.7

sarimmehdi commented 2 years ago

I solved the problem by updating to Python 3.8. For those who still want to use Python 3.7, please change the above code to the following:

def profile_func(func):
    def decorator_func(*args, **kwargs):
        pr = cProfile.Profile()
        pr.enable()
        val = func(*args, **kwargs)
        pr.disable()
        s = io.StringIO()
        sortby = SortKey.CUMULATIVE
        ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
        ps.dump_stats(filename=os.path.join(memex_utils.config.session, 'profiling.prof'))
        return val
    return decorator_func
arcstur commented 2 years ago

Remember to from pstats import SecretKey, or use pstats.SecretKey