Modifying global variable with same name as local variable












20















Suppose I have a global variable a. And within a function definition, we also have a local variable named a. Is there any way to assign the value of the global variable to that of the local variable?



a = 'foo'

def my_func(a = 'bar'):
# how to set global a to value of the local a?









share|improve this question

























  • use 'global a' statement within the function definition?

    – newtover
    Apr 19 '12 at 20:13











  • @newtover: But then I can't access the value of the local a in order to assign it to the global one.

    – tskuzzy
    Apr 19 '12 at 20:15






  • 3





    WHY???!!1!11one|11!1ELEVE||1!?. To start, using globals is a bad practice, add a parameter to your func or make a class. Second, why would you want to use the same variable name in different contexts and relate their content. Can you try harder in making your code more ugly and confusing?

    – KurzedMetal
    Apr 19 '12 at 20:19






  • 3





    This is exactly why using global variables is discouraged. Even if there is a way to do this, you shouldn't do it. Change the local variable name, or -- better yet -- don't use a global variable.

    – senderle
    Apr 19 '12 at 20:20






  • 1





    A bit late to the party, but whenever I hit the local/global collision issue, I use an empty class as a namespace container (class Container(): pass, settings = Container(), settings.a = 'foo') and store my global variables in there. It's both mutable and distinguishable: if var1 is None: var1 = settings.var1, else: settings.var1 = var1 and so on.

    – Nisan.H
    May 9 '12 at 20:34
















20















Suppose I have a global variable a. And within a function definition, we also have a local variable named a. Is there any way to assign the value of the global variable to that of the local variable?



a = 'foo'

def my_func(a = 'bar'):
# how to set global a to value of the local a?









share|improve this question

























  • use 'global a' statement within the function definition?

    – newtover
    Apr 19 '12 at 20:13











  • @newtover: But then I can't access the value of the local a in order to assign it to the global one.

    – tskuzzy
    Apr 19 '12 at 20:15






  • 3





    WHY???!!1!11one|11!1ELEVE||1!?. To start, using globals is a bad practice, add a parameter to your func or make a class. Second, why would you want to use the same variable name in different contexts and relate their content. Can you try harder in making your code more ugly and confusing?

    – KurzedMetal
    Apr 19 '12 at 20:19






  • 3





    This is exactly why using global variables is discouraged. Even if there is a way to do this, you shouldn't do it. Change the local variable name, or -- better yet -- don't use a global variable.

    – senderle
    Apr 19 '12 at 20:20






  • 1





    A bit late to the party, but whenever I hit the local/global collision issue, I use an empty class as a namespace container (class Container(): pass, settings = Container(), settings.a = 'foo') and store my global variables in there. It's both mutable and distinguishable: if var1 is None: var1 = settings.var1, else: settings.var1 = var1 and so on.

    – Nisan.H
    May 9 '12 at 20:34














20












20








20


6






Suppose I have a global variable a. And within a function definition, we also have a local variable named a. Is there any way to assign the value of the global variable to that of the local variable?



a = 'foo'

def my_func(a = 'bar'):
# how to set global a to value of the local a?









share|improve this question
















Suppose I have a global variable a. And within a function definition, we also have a local variable named a. Is there any way to assign the value of the global variable to that of the local variable?



a = 'foo'

def my_func(a = 'bar'):
# how to set global a to value of the local a?






python global-variables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 19 '12 at 20:16







tskuzzy

















asked Apr 19 '12 at 20:10









tskuzzytskuzzy

28.5k1256123




28.5k1256123













  • use 'global a' statement within the function definition?

    – newtover
    Apr 19 '12 at 20:13











  • @newtover: But then I can't access the value of the local a in order to assign it to the global one.

    – tskuzzy
    Apr 19 '12 at 20:15






  • 3





    WHY???!!1!11one|11!1ELEVE||1!?. To start, using globals is a bad practice, add a parameter to your func or make a class. Second, why would you want to use the same variable name in different contexts and relate their content. Can you try harder in making your code more ugly and confusing?

    – KurzedMetal
    Apr 19 '12 at 20:19






  • 3





    This is exactly why using global variables is discouraged. Even if there is a way to do this, you shouldn't do it. Change the local variable name, or -- better yet -- don't use a global variable.

    – senderle
    Apr 19 '12 at 20:20






  • 1





    A bit late to the party, but whenever I hit the local/global collision issue, I use an empty class as a namespace container (class Container(): pass, settings = Container(), settings.a = 'foo') and store my global variables in there. It's both mutable and distinguishable: if var1 is None: var1 = settings.var1, else: settings.var1 = var1 and so on.

    – Nisan.H
    May 9 '12 at 20:34



















  • use 'global a' statement within the function definition?

    – newtover
    Apr 19 '12 at 20:13











  • @newtover: But then I can't access the value of the local a in order to assign it to the global one.

    – tskuzzy
    Apr 19 '12 at 20:15






  • 3





    WHY???!!1!11one|11!1ELEVE||1!?. To start, using globals is a bad practice, add a parameter to your func or make a class. Second, why would you want to use the same variable name in different contexts and relate their content. Can you try harder in making your code more ugly and confusing?

    – KurzedMetal
    Apr 19 '12 at 20:19






  • 3





    This is exactly why using global variables is discouraged. Even if there is a way to do this, you shouldn't do it. Change the local variable name, or -- better yet -- don't use a global variable.

    – senderle
    Apr 19 '12 at 20:20






  • 1





    A bit late to the party, but whenever I hit the local/global collision issue, I use an empty class as a namespace container (class Container(): pass, settings = Container(), settings.a = 'foo') and store my global variables in there. It's both mutable and distinguishable: if var1 is None: var1 = settings.var1, else: settings.var1 = var1 and so on.

    – Nisan.H
    May 9 '12 at 20:34

















use 'global a' statement within the function definition?

– newtover
Apr 19 '12 at 20:13





use 'global a' statement within the function definition?

– newtover
Apr 19 '12 at 20:13













@newtover: But then I can't access the value of the local a in order to assign it to the global one.

– tskuzzy
Apr 19 '12 at 20:15





@newtover: But then I can't access the value of the local a in order to assign it to the global one.

– tskuzzy
Apr 19 '12 at 20:15




3




3





WHY???!!1!11one|11!1ELEVE||1!?. To start, using globals is a bad practice, add a parameter to your func or make a class. Second, why would you want to use the same variable name in different contexts and relate their content. Can you try harder in making your code more ugly and confusing?

– KurzedMetal
Apr 19 '12 at 20:19





WHY???!!1!11one|11!1ELEVE||1!?. To start, using globals is a bad practice, add a parameter to your func or make a class. Second, why would you want to use the same variable name in different contexts and relate their content. Can you try harder in making your code more ugly and confusing?

– KurzedMetal
Apr 19 '12 at 20:19




3




3





This is exactly why using global variables is discouraged. Even if there is a way to do this, you shouldn't do it. Change the local variable name, or -- better yet -- don't use a global variable.

– senderle
Apr 19 '12 at 20:20





This is exactly why using global variables is discouraged. Even if there is a way to do this, you shouldn't do it. Change the local variable name, or -- better yet -- don't use a global variable.

– senderle
Apr 19 '12 at 20:20




1




1





A bit late to the party, but whenever I hit the local/global collision issue, I use an empty class as a namespace container (class Container(): pass, settings = Container(), settings.a = 'foo') and store my global variables in there. It's both mutable and distinguishable: if var1 is None: var1 = settings.var1, else: settings.var1 = var1 and so on.

– Nisan.H
May 9 '12 at 20:34





A bit late to the party, but whenever I hit the local/global collision issue, I use an empty class as a namespace container (class Container(): pass, settings = Container(), settings.a = 'foo') and store my global variables in there. It's both mutable and distinguishable: if var1 is None: var1 = settings.var1, else: settings.var1 = var1 and so on.

– Nisan.H
May 9 '12 at 20:34












4 Answers
4






active

oldest

votes


















29














Use built-in function globals().




globals()



Return a dictionary representing the current global symbol
table. This is always the dictionary of the current module (inside a
function or method, this is the module where it is defined, not the
module from which it is called).




a = 'foo'

def my_func(a = 'bar'):
globals()['a'] = a


BTW, it's worth mentioning that a global is only "global" within the scope of a module.






share|improve this answer


























  • Works perfectly! Thank you!

    – tskuzzy
    Apr 19 '12 at 20:24



















1














Let python know that you want the global version;



def my_func():
global a
a = 'bar'





share|improve this answer
























  • Sorry, rephrased the question. I want to set the global a to the value of the local a.

    – tskuzzy
    Apr 19 '12 at 20:14



















0














>>> a = 'foo'
>>> def my_func(a='bar'):
... return globals()['a']
...
>>> my_func()
'foo'





share|improve this answer































    0














    Don't muddle global and local namespaces to begin with. Always try and use a local variable versus a global one when possible. If you must share variables between scopes you can still pass the variables without need for a global placeholder. Local variables are also referenced much more efficiently accessed than globals.



    A few links:



    Sharing Variables in Python



    Variable performance






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10235973%2fmodifying-global-variable-with-same-name-as-local-variable%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      29














      Use built-in function globals().




      globals()



      Return a dictionary representing the current global symbol
      table. This is always the dictionary of the current module (inside a
      function or method, this is the module where it is defined, not the
      module from which it is called).




      a = 'foo'

      def my_func(a = 'bar'):
      globals()['a'] = a


      BTW, it's worth mentioning that a global is only "global" within the scope of a module.






      share|improve this answer


























      • Works perfectly! Thank you!

        – tskuzzy
        Apr 19 '12 at 20:24
















      29














      Use built-in function globals().




      globals()



      Return a dictionary representing the current global symbol
      table. This is always the dictionary of the current module (inside a
      function or method, this is the module where it is defined, not the
      module from which it is called).




      a = 'foo'

      def my_func(a = 'bar'):
      globals()['a'] = a


      BTW, it's worth mentioning that a global is only "global" within the scope of a module.






      share|improve this answer


























      • Works perfectly! Thank you!

        – tskuzzy
        Apr 19 '12 at 20:24














      29












      29








      29







      Use built-in function globals().




      globals()



      Return a dictionary representing the current global symbol
      table. This is always the dictionary of the current module (inside a
      function or method, this is the module where it is defined, not the
      module from which it is called).




      a = 'foo'

      def my_func(a = 'bar'):
      globals()['a'] = a


      BTW, it's worth mentioning that a global is only "global" within the scope of a module.






      share|improve this answer















      Use built-in function globals().




      globals()



      Return a dictionary representing the current global symbol
      table. This is always the dictionary of the current module (inside a
      function or method, this is the module where it is defined, not the
      module from which it is called).




      a = 'foo'

      def my_func(a = 'bar'):
      globals()['a'] = a


      BTW, it's worth mentioning that a global is only "global" within the scope of a module.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jan 18 at 18:45









      Rob Stewart

      72




      72










      answered Apr 19 '12 at 20:21









      vartecvartec

      95.5k26177219




      95.5k26177219













      • Works perfectly! Thank you!

        – tskuzzy
        Apr 19 '12 at 20:24



















      • Works perfectly! Thank you!

        – tskuzzy
        Apr 19 '12 at 20:24

















      Works perfectly! Thank you!

      – tskuzzy
      Apr 19 '12 at 20:24





      Works perfectly! Thank you!

      – tskuzzy
      Apr 19 '12 at 20:24













      1














      Let python know that you want the global version;



      def my_func():
      global a
      a = 'bar'





      share|improve this answer
























      • Sorry, rephrased the question. I want to set the global a to the value of the local a.

        – tskuzzy
        Apr 19 '12 at 20:14
















      1














      Let python know that you want the global version;



      def my_func():
      global a
      a = 'bar'





      share|improve this answer
























      • Sorry, rephrased the question. I want to set the global a to the value of the local a.

        – tskuzzy
        Apr 19 '12 at 20:14














      1












      1








      1







      Let python know that you want the global version;



      def my_func():
      global a
      a = 'bar'





      share|improve this answer













      Let python know that you want the global version;



      def my_func():
      global a
      a = 'bar'






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Apr 19 '12 at 20:13









      AlGAlG

      10.4k43447




      10.4k43447













      • Sorry, rephrased the question. I want to set the global a to the value of the local a.

        – tskuzzy
        Apr 19 '12 at 20:14



















      • Sorry, rephrased the question. I want to set the global a to the value of the local a.

        – tskuzzy
        Apr 19 '12 at 20:14

















      Sorry, rephrased the question. I want to set the global a to the value of the local a.

      – tskuzzy
      Apr 19 '12 at 20:14





      Sorry, rephrased the question. I want to set the global a to the value of the local a.

      – tskuzzy
      Apr 19 '12 at 20:14











      0














      >>> a = 'foo'
      >>> def my_func(a='bar'):
      ... return globals()['a']
      ...
      >>> my_func()
      'foo'





      share|improve this answer




























        0














        >>> a = 'foo'
        >>> def my_func(a='bar'):
        ... return globals()['a']
        ...
        >>> my_func()
        'foo'





        share|improve this answer


























          0












          0








          0







          >>> a = 'foo'
          >>> def my_func(a='bar'):
          ... return globals()['a']
          ...
          >>> my_func()
          'foo'





          share|improve this answer













          >>> a = 'foo'
          >>> def my_func(a='bar'):
          ... return globals()['a']
          ...
          >>> my_func()
          'foo'






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 19 '12 at 20:23









          KurzedMetalKurzedMetal

          9,21932952




          9,21932952























              0














              Don't muddle global and local namespaces to begin with. Always try and use a local variable versus a global one when possible. If you must share variables between scopes you can still pass the variables without need for a global placeholder. Local variables are also referenced much more efficiently accessed than globals.



              A few links:



              Sharing Variables in Python



              Variable performance






              share|improve this answer






























                0














                Don't muddle global and local namespaces to begin with. Always try and use a local variable versus a global one when possible. If you must share variables between scopes you can still pass the variables without need for a global placeholder. Local variables are also referenced much more efficiently accessed than globals.



                A few links:



                Sharing Variables in Python



                Variable performance






                share|improve this answer




























                  0












                  0








                  0







                  Don't muddle global and local namespaces to begin with. Always try and use a local variable versus a global one when possible. If you must share variables between scopes you can still pass the variables without need for a global placeholder. Local variables are also referenced much more efficiently accessed than globals.



                  A few links:



                  Sharing Variables in Python



                  Variable performance






                  share|improve this answer















                  Don't muddle global and local namespaces to begin with. Always try and use a local variable versus a global one when possible. If you must share variables between scopes you can still pass the variables without need for a global placeholder. Local variables are also referenced much more efficiently accessed than globals.



                  A few links:



                  Sharing Variables in Python



                  Variable performance







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 23 '12 at 13:48

























                  answered Apr 19 '12 at 20:25









                  PenguinCoderPenguinCoder

                  3,6612036




                  3,6612036






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10235973%2fmodifying-global-variable-with-same-name-as-local-variable%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Homophylophilia

                      Updating UILabel text programmatically using a function

                      Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage