Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What you intend, in the way you want,would require file1 import file2 and vice-versa - in a plain code, that would lead to a circular import, which plainly does not work. </p> <p>But besides that, if your functions, classes or methods on a file need to know about data that is on the context of a file that imported them, the right thing to do is to pass this data in as function parameters.</p> <p>In your case, your "action" function should be:</p> <pre><code>def action(username): print username </code></pre> <p>and on file1:</p> <pre><code>from file2 import action username = "steven" action(username) </code></pre> <p>(You also should avoid using "import *" as it hides where names come from when reading the code, making it hard to maintain)</p> <p>Of course, Python being Python, there are work-arounds to do exactly what you want - you could create a special decorator to use on your imported functions that would recreate your function from another file, pointing it to the global variables from the current module - but that would be just silly.</p> <p>The "OOP" paradigm allows for one silly case which is more or less like what you are intending to do - where a method uses a class attribute - and if that attribute is overridden in a subclass, the method - even the original superclass method, will use the new attribute value - like in:</p> <pre><code>class A(object): username = "" def action(self): print self.__class__.username </code></pre> <p>and class B could be defined in other file, as you intend to:</p> <pre><code>from file2 import A class B(A): username = "Mike" b = B() b.action() </code></pre> <p>And now, just for giving you a complete answer - here is some code that will do what you want - but _don't do it - modify yoru functions to take parameters instead.</p> <p>What can be done is having a function to read the global variables of the place from where it was called. That is not only "not a good pratice" - it is just wrong, except for some very well documented frameworks where "magic variable names" are used for configuration. Even when I find a framework with this bad habit, I tend to patch its functions so that I can pass the configuration explicitly via a function call.</p> <pre><code>from inspect import currentframe def action(): caller_frame = current_frame(1) caller_globals = caller_frame.f_globals print caller_globals["username"] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload