Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's not very Pythonic, but if you really must:</p> <pre><code>import inspect def compact(*names): caller = inspect.stack()[1][0] # caller of compact() vars = {} for n in names: if n in caller.f_locals: vars[n] = caller.f_locals[n] elif n in caller.f_globals: vars[n] = caller.f_globals[n] return vars def extract(vars): caller = inspect.stack()[1][0] # caller of extract() for n, v in vars.items(): caller.f_locals[n] = v # NEVER DO THIS - not guaranteed to work </code></pre> <p>I've used these implementations quite a bit, and they work, but technically modifying <code>f_locals</code> is not supported.</p> <p>Seriously though, if you really feel you have a need to use these functions, you're probably doing something the wrong way. It seems to run against <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">Python's philosophy</a> on at least three counts: "explicit is better than implicit", "simple is better than complex", "if the implementation is hard to explain, it's a bad idea", maybe more (and really, if you have enough experience in Python you know that stuff like this just isn't done). I could see it being useful for a debugger or post-mortem analysis, or perhaps for some sort of <em>very general</em> framework that frequently needs to create variables with dynamically chosen names and values, but it's a stretch.</p> <p>If you are going to use these functions, you should at least keep the <code>extract</code>ed variables contained to within small scopes. Wrap them in functions that you can then consider to be "black boxes". The main reason <code>extract</code> is bad is that it puts variables in your symbol table in a way that isn't clear from inspecting the code. If you keep the effects of those variables localized to a very small function, and explain what you're doing with clear code and comments, it's not that big of a problem.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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