Wednesday, August 24, 2022

[FIXED] How to import module when module name has a '-' dash or hyphen in it?

Issue

I want to import foo-bar.py, this works:

foobar = __import__("foo-bar")

This does not:

from "foo-bar" import *

My question: Is there any way that I can use the above format i.e., from "foo-bar" import * to import a module that has a - in it?


Solution

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit 2: For python 3.1+, please see Julien's answer.

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 


Answered By - SingleNegationElimination
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.