0

I have a function within a module that lists defined variables

Simplified Example:

    for var_name in globals():
        if not var_name.startswith('__'):
            var_value = eval(var_name)
            var_type = type(var_value)
            print(var_name, "is", var_type, "and is equal to ", var_value)

This works when I run it from within the origin module, but not when the module is imported to another script. It only ever reads the variables defined in the origin module.

I also tried:

import __main__
for var_name in __main__.__dict__:

But that didn't work either. How can I get this function to work when imported into another script?

Thanks!

2
  • 1
    Right. globals, despite its name, is only global to a single file. Python does not have the concept of globals spanning multiple files or modules, and that's a Good Thing. __main__.__dict__ should do what you want. Commented Jul 5, 2022 at 20:45
  • I'm sorry, I did use __main__.__dict__, I just wrote it wrong in my question! Commented Jul 5, 2022 at 21:13

1 Answer 1

1

You mean to use __main__.__dict__, not __main__.dict. That, with some minor loop modifications (i.e. eval will not work as you want it to in this context, instead use __main__.__dict__[var_name]) should get your code working.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm sorry, I did use __main__.__dict__, I just wrote it wrong in my question! But you're right - using __main__.__dict__[var_name] solved it for me; thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.