Python Forum
from global space to local space
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
from global space to local space
#1
in a function i am doing a return of the locals() dictionary. one of the values i want to include in that dictionary is in the global space (let's call it "foo"). so i was, at first, tempted to just code foo = foo which i presume would not work. what would be the appropriate way put a variable in that function's local name space, taking its value from the same name in the global name space.

i figure what i should do is:
d = locals()
d['foo'] = foo
return d
but this has got me curious if there is a direct one expression way to do that (in or before a return statement).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
I don't think there's a way to shortcut this. The local variables in a function are created when the function is defined, not when it is run. And, I don't know any method to work around the shadow of a local variable to explicitly ask for the global. If that could happen, you could set up the variable as local, but at runtime pull out the value of the global.

Without that, your trick of creating a new dictionary and adding in the (unshadowed) global seems pretty good, but of course your d will be one of the entries. That seems a little bit annoying.

With python3.9, you'll be able to do direct directory merges and return that. Until then you could get close with something like:

foo = "globalfoo"
def myfunc():
    locala = 12
    localb = "hello"
    return {**locals(), 'foo': foo}

print(myfunc())
Output:
{'locala': 12, 'localb': 'hello', 'foo': 'globalfoo'}
Reply
#3
is d really going to be in the local space before the assignment? if so, then i would add del d['d'] in there.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
You're correct. locals() will only show them after assignment. I had done some testing that made me think otherwise, but that was just an error on my side.
Reply
#5
i think locals() is returning a reference to the local name space rather than a copy of it. so another option is d = dict(locals()). now will d contain itself. i'll have to try that after posting this thought.

yay, d is not in there.
#!/usr/bin/env python3

gamma = ['me','too']

def f():
    alpha = 6
    beta = 'foo'
    d = dict(locals())
    d['gamma'] = gamma
    return d

x = f()
print(repr(x))

i think i need to try out this little idea:
def dictdeladd(*args,**kwargs):
    """Copy a dictionary (arg 1), deleting items (args 2 ..) and adding items (key word args)."""
    if args:
        d = args[0]
        if not d:
            d = {}
        if not isinstance(d,dict):
            raise TypeError('argument 1 is not a dictionary')
        if d:
            d = dict(d)
    else:
        d = {}
    for k in args[1:]:
        if k in d:
            del d[k]
    for k,v in kwargs.items():
        d[k] = v
    return d
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to space data on x axis m_kdch 0 301 May-05-2025, 12:55 PM
Last Post: m_kdch
  point transformation software in space johnjsi 2 1,211 Feb-01-2024, 01:31 AM
Last Post: johnjsi
  It's saying my global variable is a local variable Radical 5 6,508 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Python rule about the space character surrounding the equal sign ineuw 10 4,987 Sep-21-2023, 09:17 AM
Last Post: ineuw
  Dijkstra algorithm helping find new space 1bumcheek 7 2,635 Jul-28-2023, 08:30 AM
Last Post: Gribouillis
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 4,290 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  Failing regex, space before and after the "match" tester_V 6 2,947 Mar-06-2023, 03:03 PM
Last Post: deanhystad
  Global variables or local accessible caslor 4 2,298 Jan-27-2023, 05:32 PM
Last Post: caslor
  How to use global value or local value sabuzaki 4 2,262 Jan-11-2023, 11:59 AM
Last Post: Gribouillis
  Command line argument issue space issue mg24 5 2,453 Oct-26-2022, 11:05 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020