Python Forum
exec() instead of functions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
exec() instead of functions
#1
if i have some code that i want to collect all of its result values into an object and also run that code again in a different context and sane its different result values into another object, using a function for the code requires explicit context references, such as a dictionary style reference or a attribute style reference. i am looking at using exec() for this context switch. this way i don't need to have the code reference any context. the code assigns to simple variables in its single local and global context, and this gets returned by exec(). executed twice with separate contexts provided and returned looks like an easier way to go. coded variables can all be simple assignments. the big issue is where to put that source. a separate file would be easy to create. a big (triple quoted) string that has the source is another. but i am afraid that smart editors would treat that quoted code like any quoted text, making it hard to do it all in one file like that.
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
Could you post a concrete example?
Reply
#3
i'm hoping to get some feedback before i write any code along these lines because of the code variation referred to. but maybe my pyconfig() function would be a starting point, showing how i would set up the call to exec() with a file.
def pyconfig(*args,**kwargs):
    """Load a config file in Python format."""
    # position arguments are path components of the config file to load
    # key word arguments are initial config variables
    import os
    if not args:
        raise ValueError('pyconfig: no file path in position arguments')
    error_return = kwargs.pop('error_return',None) # return this if error
    while isinstance(args[0],(list,tuple)):
        # if arg 1 is a list or tuple then use its items as the arguments
        args = args[0]
        if not args:
            raise ValueError(f'pyconfig: no items in {type(args).__name__} in argument 1')
    file_name = os.path.expanduser(os.path.join(*args))
    if not os.path.exists(file_name):
        raise TypeError(f'pyconfig: config file {file_name!r} does not exist')
    if not os.path.isfile(file_name):
        raise TypeError(f'pyconfig: config file {file_name!r} is not a regular file')
    try:
        with open(file_name) as file:
            code = file.read()
        if code:
            exec(code,kwargs) # run the config file here
            del kwargs['__builtins__'] # we do not need these
        else:
            kwargs = {} # if no code then no results
    except Exception:
        kwargs = error_return # if error then return error
    return kwargs
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 could perhaps write all the config code in a function and return a copy of the locals(), as an alternative to exec
def my_config(param):
    spam = 'eggs' + param
    ham = 'bacon' * 10
    return dict(locals())
Reply
#5
the code i posted to show how i would call exec for config files does need to read a file. but the purpose for this thread does not. your idea would not help pyconfig() but it seems like a great idea for my current project which is one common code that needs to be run in 3 or 4 different contexts. in this project, having everything in the one source file is what i want.

why would wrapping it in dict() be needed?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
Skaperen Wrote:why would wrapping it in dict() be needed?
I don't know. I just wanted to ensure that it is an ordinary dict and nothing else. It is probably not needed but it does not harm.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  documentation is wrong for exec() Skaperen 9 3,284 Jul-28-2019, 02:49 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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