Python Forum

Full Version: Explanation of code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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)
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.
(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
Ok, thank you!