eksperimental

eksperimental

Conditional import and lexical scope

Is there a way to conditionally import a function, but make the import available outside the if or case?

this obviously works:

  def foo() do
    import Enum, only: [map: 2]

    map(1..5, &IO.inspect(&1))
  end

this works as well:

    if is_integer(term) do
      import Enum, only: [map: 2]
      map(1..term, &IO.inspect(&1))
    end

this does not work due to lexical scope.

    if true do
      import Enum, only: [map: 2]
    end
  
    map(1..integer, &IO.inspect(&1))

So far so good.
My question is, how can we import conditionally at runtime, and make the import available outside the condition clause.

The only solution that I thought it could make it work was this, it does not and it baffles me.:

    true && (import Enum, only: [map: 2])
    map(1..integer, &IO.inspect(&1))

Note: for my use case I can solve this by running the condition at compile time, but I am just trying to understand how to do it at runtime.

Thank you

Marked As Solved

al2o3cr

al2o3cr

The behavior makes sense if you look at the implementation:
https://github.com/elixir-lang/elixir/blob/74bfab8ee271e53d24cb0012b5db1e2a931e0470/lib/elixir/lib/kernel.ex#L3791-L3803

The right-hand expression in && winds up inside a case statement, so the import does not leak out.

Also Liked

LostKobrakai

LostKobrakai

That’s what I’d do, which seems a lot cleaner than conditionally importing things.

mod = if condition, do: Stream, else: Enum
mod.map(1..integer, &IO.inspect(&1))
ityonemo

ityonemo

Imports are compile-time.

dimitarvp

dimitarvp

Elixir being FP I don’t see any other way except closures or just passing a function like so

defmodule Helper
  if compile_time_condition do
    def with_scope(fun) do
      import Enum
      fun.()
    end
  else
    def with_scope(fun) do
      import Stream
      fun.()
    end
  end
end

Or you can do it with a keyword list parameter with :do and :else like the if macro does.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement