Skip to content Skip to sidebar Skip to footer

Creating Global Variable In Python 3 From Functions

I was wondering why I can't access the variable: 'variable_for_raw_data' after the function ends. The code is like this: def htmlfrom(Website_URL): import urllib.request r

Solution 1:

It looks like you're trying to dynamically create variables, I would imagine that your code looks something like this.

defhtmlfrom(website_url):
    import urllib.request
    response = urllib.request.urlopen(website_url)
    variable_for_raw_data =(input("What will this data be saved as: "))
    global variable_for_raw_data
    variable_for_raw_data = response.read()


if __name__ == "__main__":

    htmlfrom("www.stackoverflow.com")

    #html_stackoverflow is never created it is the value#of variable_for_raw_data before variable_for_raw_data#is overridden by response.read()#entering information into input doesn't create a variableprint(html_stackoverflow)

Here's how I would do it:

import urllib.request

defhtmlfrom(website_url): 
    '''
       docstrings
    '''

    response = urllib.request.urlopen(website_url)
    variable_for_raw_data = response.read()
    return variable_for_raw_data

if __name__ == "__main__":

    file_name = input("What will this data be saved as: ")
    html_from_website = htmlfrom("www.stackoverflow.com")

        withopen(file_name, 'w') as f: 
        f.write(html_from_website)

Explanation

if you have your import statement inside the function it is only accessable inside the function (i.e. other functions can't access it)

import urllib.request

PEP 8 has guidelines on how things should be named in python CamelCase is usually reserved for class names

defhtmlfrom(website_url): 
    '''
        docstring 
    '''

Docstrings are usually a good idea.

Check out this question for more information on the proper use of globals. Based on what I know about your situation I don't think you need to use them.

    response = urllib.request.urlopen(website_url)
    variable_for_raw_data = response.read()
    return variable_for_raw_data

If you don't know about `if name == 'main': you should read up on it.

if__name__== "__main__":

Don't forget to use meaningful variable names and not override the builtins (i.e. file = "foo.txt" would override the file builtin)

file_name = input("What will this data be saved as: ")
    html_from_website = htmlfrom("www.stackoverflow.com")

You can learn more about context managers here

withopen(file_name, 'w') as f: 
        f.write(html_from_website)

An edit using globals(), FOR WHICH NO USE CASE EXISTS AT ALL.

defhtmlfrom(website_url):
    import urllib.request
    response = urllib.request.urlopen(website_url)
    variable_for_raw_data =(input("What will this data be saved as: "))
    globals()[variable_for_raw_data] = response.read()

Post a Comment for "Creating Global Variable In Python 3 From Functions"