-1

I am trying to import just one function from a .py file which has a space in its title. Due to external constraints, I cannot rename the file.

My first try was:

from File 1 import my_func

But that got a SyntaxError. Following advice on other StackOverflow, I found ways to import all the functions from a module/file:

V1:

exec(open("File 1.py").read())

V2:

globals().update(vars(__import__('File 1')))

However, I would like to only import my_func. I would also prefer to do this without using other modules like importlib. Any help is very much appreciated, I am still learning!

JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24

1 Answers1

1

Editing the answer as requsted:
Source: How do you import a file in python with spaces in the name?.

Importing single function from a module with spaces in name without using importlib is simply impossible, since your only weapon here is __import__.

Your only option is to import the whole module and only keep functions you like. But it still imports the whole module.

Important notice

Getting rid of spaces and other non-alphanumeric symbols from module names is strongly recommended.

Example

File 1.py

def foo():
    print("Foonction.")

def spam():
    print("Get out!")

main.py

globals()["foo"] = getattr(__import__("File 1"),"foo")
Community
  • 1
  • 1
rayt
  • 582
  • 5
  • 12
  • Thanks for your comment. This is a simplified example of the real scenario. (It's not actually called File 1!). I read the link provided, but it did not answer the original question, so please could I have some more assistance? – JimmyCarlos Aug 18 '18 at 09:12
  • @JimmyCarlos Despite the real name of the module might be sensible, it is not sensible to keep non-alphanumeric characters in the file name. You should never be constrained externally to do things the wrong way. Try changing the policies to camel case or underscores. *ModuleName* or *module_name* are the only **right** approaches here. – rayt Aug 18 '18 at 10:07