Python Forum
Explanation of code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Explanation of code (/thread-41664.html)



Explanation of code - ejKDE - Feb-26-2024

Here's an example of the code. I'd like to know what ctx is here. It's not passed anywhere to a function and i can't use get('formats')[::-1] without this function. How does it work and called?

import yt_dlp

URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']

def format_selector(ctx):
    formats = ctx.get('formats')[::-1]

   .....


ydl_opts = {
    'format': format_selector,
}

with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    ydl.download(URLS)



RE: Explanation of code - Gribouillis - Feb-26-2024

Obviously the format_selector() function is called either by YoutubeDL(ydl_opts) or by ydl.download(URLS). The ctx argument is created internally by the yt_dlp module. You can find the type of this object and see where it is called by replacing the function by

def format_selector(ctx):
    raise RuntimeError(ctx)



RE: Explanation of code - ejKDE - Feb-26-2024

Thank you. So if i understood correctly, YoutubeDL looks at ydl_opts, sees format in 'format': format_selector and is sending all of the format related things to format_selector function even though function is called without arguments?

This is specific to yt_dlp, right? I can't do this with my own functions, i need to send arguments or use *args.


RE: Explanation of code - buran - Feb-26-2024

(Feb-26-2024, 02:41 PM)ejKDE Wrote: even though function is called without arguments?
You never call the function format_selector yourself, it's called internally from YoutubeDL.download and it expects that it takes ctx argument

From the docstring for YoutubeDL class

Quote: format: Video format code. see "FORMAT SELECTION" for more details.
You can also pass a function. The function takes 'ctx' as
argument and returns the formats to download



RE: Explanation of code - ejKDE - Feb-26-2024

Ok, thank you!