2

in Python, I am trying to import the open function object from the built-in os module, but it would not let me import it as it has the same name as the built-in open function, which is used for opening files. How do I import an object/attribute from a module which uses the same name as a reserved built-in function/keyword?

Like

from os import open
  • 1
    I don't have an error doing `from os import open`. – Green Cloak Guy Apr 23 '21 at 20:02
  • 1
    It's probably a good idea to alias it as James says below, but nothing should prevent `from os import open` from working. That will just shadow the built-in function. (Note that `open` is not a reserved word. `from foo import class` or `from bar import def` does give a `SyntaxError`.) – ChrisGPT was on strike Apr 23 '21 at 20:03

2 Answers2

2

You can alias it using as.

from os import open as osopen
James
  • 32,991
  • 4
  • 47
  • 70
1

you can import as another name by as

Am_Ha
  • 11
  • 1
  • 1
    Welcome to Stack Overflow. Please read [answer]. How does this answer improve upon what's already here? – ChrisGPT was on strike Apr 23 '21 at 20:08
  • @Chris I cannot see the timeline to the minute, were these two answers at about the same time, or at least several minutes apart? This poster might not have seen the other answer when they answered. That being said, I still agree the other answer is better. – joanis Apr 23 '21 at 21:22
  • 1
    @joanis, mouse over the timestamp (e.g. "1 hour ago") to see the UTC time to the second. This was almost 6 minutes after James'. Considering how short this answer is it seems likely that James' answer was here when they started to answer. – ChrisGPT was on strike Apr 23 '21 at 21:24