Search code examples
pythonpython-3.xglobal-variablesinstancepafy

Python pafy global not working across a function-call boundary


Okay, I was trying to make a simple script to download youtube videos using pafy. Currently I have a problem with the global variable video which I use to store what pafy.new('url') returns. Here's the two functions I use:

video = {};

def downloadVideo():

    options = {};
    options['initialdir'] = 'C:\\';
    options['mustexist'] = False;
    options['title'] = 'Download folder';

    dir_path = tkinter.filedialog.askdirectory(**options);
    global video;
    video.getbest(preftype="mp4").download(quiet=True, filepath=dir_path);

def get():
    url = url_entry.get();

    if url == '':
        return

    global video;
    video = pafy.new(url);

    # Some code to display video info

First I use get() function to get the video from url_entry which is a tkinter Entry widget. So far so good, but when I call downloadVideo() I get this error:

AttributeError: 'NoneType' object has no attribute 'download'


Solution

  • Found the problem in this line:

    video.getbest(preftype="mp4").download(quiet=True, filepath=dir_path);
    

    This:

    video.getbest(preftype="mp4")
    

    actually returned a NoneType object since it didn't contain any mp4 stream. So, it's not exactly a problem, it's just something I should check before calling download(). Now I just get all the streams video.streams and download what I need or just let it download the best available video.getbest().download().